nearest.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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 pokemonLookup = new Fuse(database, { keys: [ "name" ] });
  16. // hex codes already include leading # in these functions
  17. // rgb values are [0, 1] in these functions
  18. const luv2hex = $.colorspaces.converter("CIELUV", "hex");
  19. const rgb2luv = $.colorspaces.converter("sRGB", "CIELUV");
  20. const rgb2hex = $.colorspaces.converter("sRGB", "hex");
  21. const hex2rgb = $.colorspaces.converter("hex", "sRGB");
  22. // scoring functions
  23. const getNormedScorer = (c, q) => {
  24. const factor = c / vectorMag(q);
  25. return yVec => factor * vectorDot(q, yVec) / vectorMag(yVec);
  26. };
  27. const getUnnormedScorer = (c, q) => yVec => c * vectorDot(q, yVec);
  28. // create a tile of a given hex color
  29. const createTile = hexColor => {
  30. const tile = document.createElement("div");
  31. tile.setAttribute("class", "color-tile");
  32. tile.setAttribute("style", `background-color: ${hexColor};`)
  33. tile.textContent = hexColor;
  34. return tile;
  35. }
  36. const createPokemon = ({ name, score, yRGB, yLUV }) => {
  37. const img = document.createElement("img");
  38. img.setAttribute("src", getSprite(name));
  39. const titleName = titleCase(name);
  40. const text = score ? `${titleName}: ${score.toFixed(3)}` : titleName
  41. const pkmn = document.createElement("div");
  42. pkmn.setAttribute("class", "pokemon");
  43. pkmn.appendChild(img);
  44. const textSpan = document.createElement("span");
  45. textSpan.textContent = text;
  46. textSpan.setAttribute("class", "pokemon_text");
  47. pkmn.appendChild(textSpan);
  48. pkmn.appendChild(createTile(rgb2hex(yRGB.map(x => x / 255))));
  49. pkmn.appendChild(createTile(luv2hex(yLUV)));
  50. return pkmn;
  51. }
  52. let lastColorSearch = null;
  53. let lastPkmnSearch = null;
  54. const paramsChanged = (...args) => {
  55. const old = lastColorSearch;
  56. lastColorSearch = args;
  57. return old === null || old.filter((p, i) => p !== args[i]).length > 0
  58. }
  59. const onUpdate = (event) => {
  60. if (event) {
  61. event.preventDefault();
  62. }
  63. // Configuration Loading
  64. const includeX = document.getElementById("include-x")?.checked ?? false;
  65. const normQY = document.getElementById("norm-q-y")?.checked ?? false;
  66. const closeCoeff = document.getElementById("close-coeff")?.value ?? 2;
  67. const useRGB = document.getElementById("color-space")?.textContent === "RGB";
  68. const numPoke = document.getElementById("num-poke")?.value ?? 20;
  69. const pokemonName = document.getElementById("pokemon-name")?.value?.toLowerCase() ?? "";
  70. const targetColor = "#" + (document.getElementById("color-input")?.value?.replace("#", "") ?? "FFFFFF");
  71. const targetRGB = hex2rgb(targetColor).map(x => x * 255);
  72. // Update display values
  73. document.getElementById("x-term").textContent = includeX ? "X(P)" : "";
  74. document.getElementById("c-value").textContent = closeCoeff;
  75. document.getElementById("q-vec").textContent = normQY ? "q̂" : "q";
  76. document.getElementById("y-vec").textContent = normQY ? "Ŷ(P)" : "Y(P)";
  77. document.getElementById("close-coeff-display").innerHTML = closeCoeff;
  78. document.getElementById("num-poke-display").textContent = numPoke;
  79. // determine metrics from configuration
  80. const targetInSpace = useRGB ? targetRGB : rgb2luv(targetRGB.map(x => x / 255));
  81. const xSelector = includeX ? (useRGB ? ({ xRGB }) => xRGB : ({ xLUV }) => xLUV) : () => 0;
  82. const ySelector = useRGB ? ({ yRGB }) => yRGB : ({ yLUV }) => yLUV;
  83. const yScorer = (normQY ? getNormedScorer : getUnnormedScorer)(closeCoeff, targetInSpace);
  84. const totalScorer = info => xSelector(info) - yScorer(ySelector(info));
  85. const newParams = paramsChanged(includeX, normQY, closeCoeff, useRGB, numPoke, targetColor);
  86. if (targetColor.length === 7 && newParams) {
  87. // calculate luminance to determine if text should be dark or light
  88. const textColor = vectorDot(targetRGB, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  89. document.querySelector("body").setAttribute("style", `background: ${targetColor}; color: ${textColor}`);
  90. const bestList = document.getElementById("best-list");
  91. bestList.innerHTML = ''; // do the lazy thing
  92. // actually score pokemon
  93. database
  94. .map(info => ({ ...info, score: totalScorer(info) }))
  95. .sort((a, b) => a.score - b.score)
  96. .slice(0, numPoke)
  97. .forEach(info => {
  98. const li = document.createElement("li");
  99. li.appendChild(createPokemon(info))
  100. bestList.appendChild(li);
  101. });
  102. }
  103. if (pokemonName.length > 0 && (lastPkmnSearch !== pokemonName || newParams)) {
  104. lastPkmnSearch = pokemonName;
  105. // lookup by pokemon too
  106. const searchList = document.getElementById("search-list");
  107. searchList.innerHTML = '';
  108. pokemonLookup
  109. .search(pokemonName, { limit: 15 })
  110. .map(({ item }) => ({ ...item, score: totalScorer(item) }))
  111. .forEach(item => {
  112. const li = document.createElement("li");
  113. li.appendChild(createPokemon(item))
  114. searchList.appendChild(li);
  115. });
  116. }
  117. };
  118. const onRandomColor = () => {
  119. document.getElementById("color-input").value = rgb2hex([Math.random(), Math.random(), Math.random()]);
  120. onUpdate();
  121. };
  122. const onToggleSpace = () => {
  123. const element = document.getElementById("color-space");
  124. const current = element?.textContent;
  125. element.textContent = current === "RGB" ? "CIELUV" : "RGB";
  126. document.getElementById("space-toggle").textContent = `Swap to ${current}`
  127. onUpdate();
  128. };