nearest.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. const stripForm = ["flabebe", "floette", "florges", "vivillon", "basculin", "furfrou", "magearna"];
  2. const getSprite = pokemon => {
  3. pokemon = pokemon
  4. .replace("-alola", "-alolan")
  5. .replace("-galar", "-galarian")
  6. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  7. if (stripForm.find(s => pokemon.includes(s))) {
  8. pokemon = pokemon.replace(/-.*$/, "");
  9. }
  10. return `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`;
  11. }
  12. const titleCase = s => s.charAt(0).toUpperCase() + s.substr(1);
  13. const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
  14. const vectorMag = v => Math.sqrt(vectorDot(v, v));
  15. const getContrastingTextColor = rgb => vectorDot(rgb, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd"
  16. const pokemonLookup = new Fuse(database, { keys: [ "name" ] });
  17. // hex codes already include leading # in these functions
  18. // rgb values are [0, 255] in these functions
  19. const jab2hex = jab => d3.jab(...jab).formatHex();
  20. const rgb2hex = rgb => d3.rgb(...rgb).formatHex();
  21. const rgb2jab = rgb => {
  22. const { J, a, b } = d3.jab(d3.rgb(...rgb));
  23. return [ J, a, b ];
  24. }
  25. const hex2rgb = hex => {
  26. const { r, g, b } = d3.rgb(hex);
  27. return [ r, g, b ];
  28. };
  29. // scoring functions
  30. const getNormedScorer = (c, qRGB, qJAB) => {
  31. const fRGB = c / vectorMag(qRGB);
  32. const fJAB = c / vectorMag(qJAB);
  33. return ({ yRGB, yJAB }) => ({
  34. scoreRGB: fRGB * vectorDot(qRGB, yRGB) / vectorMag(yRGB),
  35. scoreJAB: fJAB * vectorDot(qJAB, yJAB) / vectorMag(yJAB),
  36. });
  37. };
  38. const getUnnormedScorer = (c, qRGB, qJAB) => ({ yRGB, yJAB }) => ({
  39. scoreRGB: c * vectorDot(qRGB, yRGB),
  40. scoreJAB: c * vectorDot(qJAB, yJAB),
  41. });
  42. // create a tile of a given hex color
  43. const createTile = hexColor => {
  44. const tile = document.createElement("div");
  45. tile.setAttribute("class", "color-tile");
  46. tile.setAttribute("style", `background-color: ${hexColor};`)
  47. tile.textContent = hexColor;
  48. return tile;
  49. }
  50. const renderPokemon = (
  51. { name, scoreRGB = null, scoreJAB = null, yRGB, yJAB },
  52. { rgbClass = "", jabClass = "" } = {},
  53. ) => {
  54. const titleName = titleCase(name);
  55. const rgbHex = rgb2hex(yRGB);
  56. const jabHex = jab2hex(yJAB);
  57. const textHex = getContrastingTextColor(yRGB);
  58. const rgbVec = yRGB.map(c => c.toFixed()).join(", ")
  59. const jabVec = yJAB.map(c => c.toFixed(2)).join(", ")
  60. const scoreClass = scoreRGB === null || scoreJAB === null ? "hide" : "";
  61. const pkmn = document.createElement("div");
  62. pkmn.setAttribute("class", "pokemon_tile");
  63. pkmn.innerHTML = `
  64. <img src="${getSprite(name)}" />
  65. <div class="pokemon_tile-info_panel">
  66. <span class="pokemon_tile-pokemon_name">${titleName}</span>
  67. <div class="pokemon_tile-results">
  68. <div class="pokemon_tile-labels">
  69. <span class="${jabClass}">Jab: </span>
  70. <span class="${rgbClass}">RGB: </span>
  71. </div>
  72. <div class="pokemon_tile-score_column ${scoreClass}">
  73. <span class="pokemon_tile-no_flex ${jabClass}">
  74. ${scoreJAB?.toFixed(2)}
  75. </span>
  76. <span class="pokemon_tile-no_flex ${rgbClass}">
  77. ${scoreRGB?.toFixed(2)}
  78. </span>
  79. </div>
  80. <div class="pokemon_tile-hex_column">
  81. <div class="pokemon_tile-hex_color ${jabClass}" style="background-color: ${jabHex}; color: ${textHex}">
  82. ${jabHex}
  83. </div>
  84. <div class="pokemon_tile-hex_color ${rgbClass}" style="background-color: ${rgbHex}; color: ${textHex}">
  85. ${rgbHex}
  86. </div>
  87. </div>
  88. <div class="pokemon_tile-vector_column">
  89. <span class="pokemon_tile-no_flex ${rgbClass}">(${rgbVec})</span>
  90. <span class="pokemon_tile-no_flex ${jabClass}">(${jabVec})</span>
  91. </div>
  92. </div>
  93. </div>
  94. `;
  95. return pkmn;
  96. }
  97. let lastColorSearch = null;
  98. let lastPkmnSearch = null;
  99. const paramsChanged = (...args) => {
  100. const old = lastColorSearch;
  101. lastColorSearch = args;
  102. return old === null || old.filter((p, i) => p !== args[i]).length > 0
  103. }
  104. const renderVec = math => `\\vec{${math.charAt(0)}}${math.substr(1)}`;
  105. const renderNorm = vec => `\\frac{${vec}}{\\left|\\left|${vec}\\right|\\right|}`;
  106. const renderMath = (includeX, normQY, closeCoeff) => {
  107. const xTerm = includeX ? "X\\left(P\\right)" : "";
  108. const qyMod = normQY ? c => renderNorm(renderVec(c)) : renderVec;
  109. return TeXZilla.toMathML(`${xTerm}-${closeCoeff}${qyMod("q")}\\cdot ${qyMod("Y\\left(P\\right)")}`);
  110. }
  111. const changePageColors = color => {
  112. // calculate luminance to determine if text should be dark or light
  113. const textColor = getContrastingTextColor([color.r, color.g, color.b]);
  114. document.querySelector("body").setAttribute("style", `background: ${color.formatHex()}; color: ${textColor}`);
  115. }
  116. const readColor = rgb => {
  117. const { J, a, b } = d3.jab(rgb);
  118. return [[rgb.r, rgb.g, rgb.b], [J, a, b]];
  119. }
  120. const onUpdate = (event) => {
  121. if (event) {
  122. event.preventDefault();
  123. }
  124. // Configuration Loading
  125. const includeX = document.getElementById("include-x")?.checked ?? false;
  126. const normQY = document.getElementById("norm-q-y")?.checked ?? false;
  127. const closeCoeff = document.getElementById("close-coeff")?.value ?? 2;
  128. const useRGB = document.getElementById("color-space")?.textContent === "RGB";
  129. const numPoke = document.getElementById("num-poke")?.value ?? 20;
  130. const pokemonName = document.getElementById("pokemon-name")?.value?.toLowerCase() ?? "";
  131. const colorInput = "#" + (document.getElementById("color-input")?.value?.replace("#", "") ?? "FFFFFF");
  132. // Check if parameters have changed
  133. const newParams = paramsChanged(includeX, normQY, closeCoeff, useRGB, numPoke, colorInput);
  134. if (newParams) {
  135. // Update display values
  136. document.getElementById("close-coeff-display").innerHTML = closeCoeff;
  137. document.getElementById("num-poke-display").textContent = numPoke;
  138. const objFnElem = document.getElementById("obj-fn");
  139. objFnElem.innerHTML = "";
  140. objFnElem.appendChild(renderMath(includeX, normQY, closeCoeff));
  141. }
  142. // Only modified if current color is valid
  143. let totalScorer = info => info;
  144. // Lookup by color
  145. if (colorInput.length === 7) {
  146. // Convert input color
  147. const targetColor = d3.color(colorInput);
  148. const [ targetRGB, targetJAB ] = readColor(targetColor);
  149. // Update the color display
  150. changePageColors(targetColor);
  151. // TODO render q vectors somewhere
  152. // Determine metrics from configuration
  153. const xSelector = includeX ? ({ xRGB, xJAB }) => [ xRGB, xJAB ] : () => [ 0, 0 ];
  154. const yScorer = (normQY ? getNormedScorer : getUnnormedScorer)(closeCoeff, targetRGB, targetJAB);
  155. // Set the scoring function
  156. totalScorer = info => {
  157. const [ xRGB, xJAB ] = xSelector(info);
  158. const { scoreRGB, scoreJAB } = yScorer(info);
  159. return {
  160. ...info,
  161. scoreRGB: xRGB - scoreRGB,
  162. scoreJAB: xJAB - scoreJAB,
  163. }
  164. };
  165. // Rescore Pokemon and update lists if config has changed
  166. if (newParams) {
  167. const scored = database.map(info => totalScorer(info));
  168. const bestListRGB = document.getElementById("best-list-rgb");
  169. bestListRGB.innerHTML = '';
  170. scored
  171. .sort((a, b) => a.scoreRGB - b.scoreRGB)
  172. .slice(0, numPoke)
  173. .forEach(info => {
  174. const li = document.createElement("li");
  175. li.appendChild(renderPokemon(info, { jabClass: "hide" }))
  176. bestListRGB.appendChild(li);
  177. });
  178. const bestListJAB = document.getElementById("best-list-jab");
  179. bestListJAB.innerHTML = '';
  180. scored
  181. .sort((a, b) => a.scoreJAB - b.scoreJAB)
  182. .slice(0, numPoke)
  183. .forEach(info => {
  184. const li = document.createElement("li");
  185. li.appendChild(renderPokemon(info, { rgbClass: "hide" }))
  186. bestListJAB.appendChild(li);
  187. });
  188. }
  189. }
  190. // Lookup by name
  191. if (pokemonName.length === 0) {
  192. const searchList = document.getElementById("search-list");
  193. searchList.innerHTML = '';
  194. } else if (lastPkmnSearch !== pokemonName || newParams) {
  195. // Update last search
  196. lastPkmnSearch = pokemonName;
  197. const searchList = document.getElementById("search-list");
  198. searchList.innerHTML = '';
  199. pokemonLookup
  200. .search(pokemonName, { limit: 10 })
  201. // If scoring is impossible, totalScorer will just be identity
  202. .map(({ item }) => totalScorer(item))
  203. .forEach(item => {
  204. const li = document.createElement("li");
  205. li.appendChild(renderPokemon(item))
  206. searchList.appendChild(li);
  207. });
  208. }
  209. };
  210. const onRandomColor = () => {
  211. document.getElementById("color-input").value = rgb2hex([Math.random(), Math.random(), Math.random()].map(c => c * 255));
  212. onUpdate();
  213. };