nearest.js 5.3 KB

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