nearest.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 = () => {
  60. // Configuration Loading
  61. const includeX = document.getElementById("include-x")?.checked ?? false;
  62. const normQY = document.getElementById("norm-q-y")?.checked ?? false;
  63. const closeCoeff = document.getElementById("close-coeff")?.value ?? 2;
  64. const useRGB = document.getElementById("color-space")?.textContent === "RGB";
  65. const numPoke = document.getElementById("num-poke")?.value ?? 20;
  66. const pokemonName = document.getElementById("pokemon-name")?.value?.toLowerCase() ?? "";
  67. const targetColor = "#" + (document.getElementById("color-input")?.value?.replace("#", "") ?? "FFFFFF");
  68. const targetRGB = hex2rgb(targetColor).map(x => x * 255);
  69. // Update display values
  70. document.getElementById("x-term").textContent = includeX ? "X(P)" : "";
  71. document.getElementById("c-value").textContent = closeCoeff;
  72. document.getElementById("q-vec").textContent = normQY ? "q̂" : "q";
  73. document.getElementById("y-vec").textContent = normQY ? "Ŷ(P)" : "Y(P)";
  74. document.getElementById("close-coeff-display").innerHTML = closeCoeff;
  75. document.getElementById("num-poke-display").textContent = numPoke;
  76. // determine metrics from configuration
  77. const targetInSpace = useRGB ? targetRGB : rgb2luv(targetRGB.map(x => x / 255));
  78. const xSelector = includeX ? (useRGB ? ({ xRGB }) => xRGB : ({ xLUV }) => xLUV) : () => 0;
  79. const ySelector = useRGB ? ({ yRGB }) => yRGB : ({ yLUV }) => yLUV;
  80. const yScorer = (normQY ? getNormedScorer : getUnnormedScorer)(closeCoeff, targetInSpace);
  81. const totalScorer = info => xSelector(info) - yScorer(ySelector(info));
  82. const newParams = paramsChanged(includeX, normQY, closeCoeff, useRGB, numPoke, targetColor);
  83. if (targetColor.length === 7 && newParams) {
  84. // calculate luminance to determine if text should be dark or light
  85. const textColor = vectorDot(targetRGB, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  86. document.querySelector("body").setAttribute("style", `background: ${targetColor}; color: ${textColor}`);
  87. const bestList = document.getElementById("best-list");
  88. bestList.innerHTML = ''; // do the lazy thing
  89. // actually score pokemon
  90. database
  91. .map(info => ({ ...info, score: totalScorer(info) }))
  92. .sort((a, b) => a.score - b.score)
  93. .slice(0, numPoke)
  94. .forEach(info => {
  95. const li = document.createElement("li");
  96. li.appendChild(createPokemon(info))
  97. bestList.appendChild(li);
  98. });
  99. }
  100. if (pokemonName.length > 0 && (lastPkmnSearch !== pokemonName || newParams)) {
  101. lastPkmnSearch = pokemonName;
  102. // lookup by pokemon too
  103. const searchList = document.getElementById("search-list");
  104. searchList.innerHTML = '';
  105. pokemonLookup
  106. .search(pokemonName, { limit: 15 })
  107. .map(({ item }) => ({ ...item, score: totalScorer(item) }))
  108. .forEach(item => {
  109. const li = document.createElement("li");
  110. li.appendChild(createPokemon(item))
  111. searchList.appendChild(li);
  112. });
  113. }
  114. };
  115. const onRandomColor = () => {
  116. document.getElementById("color-input").value = rgb2hex([Math.random(), Math.random(), Math.random()]);
  117. onUpdate();
  118. };
  119. const onToggleSpace = () => {
  120. const element = document.getElementById("color-space");
  121. const current = element?.textContent;
  122. element.textContent = current === "RGB" ? "CIELUV" : "RGB";
  123. document.getElementById("space-toggle").textContent = `Swap to ${current}`
  124. onUpdate();
  125. };