nearest.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. // Selectors + DOM Manipulation
  2. const getColorInputNode = () => document.getElementById("color-input");
  3. const getMetricDropdownNode = () => document.getElementById("metric");
  4. const getClusterChoiceDropdownNode = () => document.getElementById("image-summary");
  5. const getClusterScaleToggleNode = () => document.getElementById("scale-by-cluster-size");
  6. const getClusterMeanWarning = () => document.getElementById("cluster-mean-warning");
  7. const getIncludeXToggleNode = () => document.getElementById("include-x");
  8. const getNormQYToggleNode = () => document.getElementById("norm-q-y");
  9. const getCloseCoeffSliderNode = () => document.getElementById("close-coeff");
  10. const getCloseCoeffDisplayNode = () => document.getElementById("close-coeff-display");
  11. const getLimitSliderNode = () => document.getElementById("num-poke");
  12. const getLimitDisplayNode = () => document.getElementById("num-poke-display");
  13. const getNameInputNode = () => document.getElementById("pokemon-name");
  14. const getScoreListJABNode = () => document.getElementById("best-list-jab");
  15. const getScoreListRGBNode = () => document.getElementById("best-list-rgb");
  16. const getSearchSpaceDisplayNode = () => document.getElementById("search-space-display");
  17. const getSearchListNode = () => document.getElementById("search-list");
  18. const getHideableControlNodes = () => document.querySelectorAll(".hideable_control");
  19. const getQJABDisplay = () => document.getElementById("q-vec-jab");
  20. const getQRGBDisplay = () => document.getElementById("q-vec-rgb");
  21. const getObjFnDisplay = () => document.getElementById("obj-fn");
  22. const clearNodeContents = node => { node.innerHTML = ""; };
  23. const hideCustomControls = () => getHideableControlNodes()
  24. .forEach(n => n.setAttribute("class", "hideable_control hideable_control--hidden"));
  25. const showCustomControls = () => getHideableControlNodes()
  26. .forEach(n => n.setAttribute("class", "hideable_control"));
  27. // Vector Math
  28. const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
  29. const vectorSqMag = v => vectorDot(v, v);
  30. const vectorMag = v => Math.sqrt(vectorSqMag(v));
  31. const vectorSqDist = (u, v) => vectorSqMag(u.map((x, i) => x - v[i]));
  32. const vectorDist = (u, v) => Math.sqrt(vectorSqDist(u, v));
  33. const vectorNorm = v => { const n = vectorMag(v); return [ n, v.map(c => c / n) ]; };
  34. // Angle Math
  35. const angleDiff = (a, b) => { const raw = Math.abs(a - b); return raw < 180 ? raw : (360 - raw); };
  36. const rad2deg = 180 / Math.PI;
  37. // Conversions
  38. const jab2hex = jab => d3.jab(...jab).formatHex();
  39. const rgb2hex = rgb => d3.rgb(...rgb).formatHex();
  40. const jab2hue = ([, a, b]) => rad2deg * Math.atan2(b, a);
  41. const rgb2hue = rgb => d3.hsl(d3.rgb(...rgb)).h || 0;
  42. const hex2rgb = hex => {
  43. const { r, g, b } = d3.color(hex);
  44. return [r, g, b];
  45. };
  46. // Arg Compare
  47. const argComp = comp => ra => ra.map((x, i) => [x, i]).reduce((a, b) => comp(a[0], b[0]) > 0 ? b : a)[1];
  48. const argMin = argComp((a, b) => a - b);
  49. const argMax = argComp((a, b) => b - a);
  50. // Pre-Compute Data
  51. const computeVectorData = (vector, toHex, toHue) => {
  52. const [ magnitude, unit ] = vectorNorm(vector);
  53. return {
  54. vector,
  55. magnitude,
  56. magSq: magnitude * magnitude,
  57. unit,
  58. hex: toHex(vector),
  59. hue: toHue(vector),
  60. };
  61. };
  62. const computeStats = (inertia, trueMeanVec, kMeanStruct, toHex, toHue) => ({
  63. inertia,
  64. trueMean: computeVectorData(trueMeanVec, toHex, toHue),
  65. kMeans: kMeanStruct.slice(0, 3).map(z => computeVectorData(z, toHex, toHue)),
  66. kWeights: kMeanStruct[3],
  67. largestCluster: argMax(kMeanStruct[3]),
  68. smallestCluster: argMin(kMeanStruct[3]),
  69. });
  70. const pokemonColorData = database.map(({
  71. name, xJAB, xRGB, yJAB, yRGB, zJAB, zRGB,
  72. }) => ({
  73. name,
  74. jabStats: computeStats(xJAB, yJAB, zJAB, jab2hex, jab2hue),
  75. rgbStats: computeStats(xRGB, yRGB, zRGB, rgb2hex, rgb2hue),
  76. }));
  77. const pokemonLookup = new Fuse(pokemonColorData, { keys: [ "name" ] });
  78. // Color Calculations
  79. const getContrastingTextColor = rgb => vectorDot(rgb, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  80. const readColorInput = () => {
  81. const colorInput = "#" + (getColorInputNode()?.value?.replace("#", "") ?? "FFFFFF");
  82. if (colorInput.length !== 7) {
  83. return;
  84. }
  85. const rgb = d3.color(colorInput);
  86. const { J, a, b } = d3.jab(rgb);
  87. return {
  88. jabData: computeVectorData([ J, a, b ], jab2hex, jab2hue),
  89. rgbData: computeVectorData([ rgb.r, rgb.g, rgb.b ], rgb2hex, rgb2hue),
  90. };
  91. };
  92. // State
  93. const state = {
  94. metric: null,
  95. clusterChoice: null,
  96. includeScale: null,
  97. includeX: null,
  98. normQY: null,
  99. closeCoeff: null,
  100. numPoke: null,
  101. searchTerm: null,
  102. searchSpace: null,
  103. targetColor: null,
  104. searchResults: null,
  105. clusterToggles: {},
  106. currentScores: {},
  107. };
  108. // Metrics
  109. const getBestKMean = (stats, q) => argMin(stats.kMeans.map((z, i) => vectorDist(z.vector, q.vector) / stats.kWeights[i]));
  110. const getWorstKMean = (stats, q) => argMax(stats.kMeans.map((z, i) => vectorDist(z.vector, q.vector) / stats.kWeights[i]));
  111. const getScale = weight => state.includeScale ? (1 / weight) : 1;
  112. const summarySelectors = [
  113. // true mean
  114. stats => [stats.trueMean, 1],
  115. // largest cluster
  116. stats => [stats.kMeans[stats.largestCluster], getScale(stats.kWeights[stats.largestCluster])],
  117. // smallest cluster
  118. stats => [stats.kMeans[stats.smallestCluster], getScale(stats.kWeights[stats.smallestCluster])],
  119. // best fit cluster
  120. (stats, q) => {
  121. const best = getBestKMean(stats, q);
  122. return [stats.kMeans[best], getScale(stats.kWeights[best])];
  123. },
  124. // worst fit cluster
  125. (stats, q) => {
  126. const worst = getWorstKMean(stats, q);
  127. return [stats.kMeans[worst], getScale(stats.kWeights[worst])];
  128. },
  129. ];
  130. const selectedSummary = (stats, q) => summarySelectors[state.clusterChoice](stats, q);
  131. // TODO unfortunately the addition of the scaling factor means we have to compute *real*
  132. // metrics instead of cheaper approximations. would be nice to fix this
  133. const metrics = [
  134. // RMS
  135. (stats, q) => {
  136. const [ mean, scale ] = selectedSummary(stats, q);
  137. return (stats.inertia - 2 * vectorDot(mean.vector, q.vector)) * scale;
  138. },
  139. // mean angle
  140. (stats, q) => {
  141. const [ mean, scale ] = selectedSummary(stats, q);
  142. return rad2deg * Math.acos(vectorDot(mean.unit, q.unit)) * scale;
  143. },
  144. // mean dist
  145. (stats, q) => {
  146. const [ mean, scale ] = selectedSummary(stats, q);
  147. // TODO I know there's some way to avoid recalculation here but I'm just too lazy right now
  148. return vectorDist(mean.vector, q.vector) * scale;
  149. },
  150. // hue angle
  151. (stats, q) => {
  152. const [ mean, scale ] = selectedSummary(stats, q);
  153. return angleDiff(mean.hue, q.hue) * scale;
  154. },
  155. // max inertia
  156. (stats, q) => {
  157. const [ , scale ] = selectedSummary(stats, q);
  158. return -stats.inertia * scale;
  159. },
  160. // custom
  161. (stats, q) => {
  162. const [ mean, scale ] = selectedSummary(stats, q);
  163. return (
  164. (state.includeX ? stats.inertia : 0)
  165. -
  166. state.closeCoeff * vectorDot(
  167. mean[state.normQY ? "unit" : "vector"],
  168. state.normQY ? q.unit : q.vector,
  169. )
  170. ) * scale;
  171. },
  172. ];
  173. const scorePokemon = pkmn => ({
  174. jab: metrics[state.metric](pkmn.jabStats, state.targetColor.jabData),
  175. rgb: metrics[state.metric](pkmn.rgbStats, state.targetColor.rgbData),
  176. });
  177. const calcDisplayMetrics = (meanData, q) => ({
  178. theta: rad2deg * Math.acos(vectorDot(q.unit, meanData.unit)),
  179. delta: vectorDist(q.vector, meanData.vector),
  180. phi: angleDiff(q.hue, meanData.hue),
  181. });
  182. // Math Rendering
  183. const renderQVec = (q, node, sub) => {
  184. node.innerHTML = TeXZilla.toMathMLString(String.raw`\vec{q}_{\text{${sub}}} = \left(\text{${q.join(", ")}}\right)`);
  185. };
  186. const mathArgBest = (mxn, arg) => `\\underset{${arg}}{\\arg\\${mxn}}`;
  187. const mathDefinitions = {
  188. "main-definition": String.raw`
  189. \begin{aligned}
  190. \vec{\mu}\left(P\right) &= \frac{1}{\left|P\right|}\sum_{p\in P}{\vec{p}} \\
  191. I\left(P\right) &= \frac{1}{\left|P\right|}\sum_{p\in P}{\left|\left|\vec{p}\right|\right|^2} \\
  192. \delta\left(P\right) &= \left|\left| \vec{q} - \vec{\mu}\left(P\right) \right|\right| \\
  193. \theta\left(P\right) &= \angle \left(\vec{q}, \vec{\mu}\left(P\right)\right) \\
  194. \vec{x}_{\perp} &= \text{oproj}_{\left\{\vec{J}, \vec{L}\right\}}{\vec{x}} \\
  195. \phi\left(P\right) &= \angle \left(\vec{q}_{\perp}, \vec{\mu}\left(P\right)_{\perp} \right) \\
  196. \sigma\left(P\right) &= \sqrt{E\left[\left(\vec{q} - P\right)^2\right]} \\
  197. &= \sqrt{\frac{1}{|P|}\sum_{p \in P}{\left|\left|\vec{p} - \vec{q}\right|\right|^2}}
  198. \end{aligned}
  199. `,
  200. "cluster-definition": String.raw`
  201. \begin{aligned}
  202. \left\{P_1, P_2, P_3\right\} &= ${mathArgBest("max", String.raw`\left\{P_1, P_2, P_3\right\}`)} \sum_{i=1}^3 \sum_{p\inP_i} \left|\left| \vec{p} - \vec{\mu}\left(P_i\right) \right|\right|^2 \\
  203. \pi_i &= \frac{\left|P_i\right|}{\left|P\right|} \\
  204. M\left(P\right) &= ${mathArgBest("max", "P_i")} \left( \left|P_i\right| \right) \\
  205. m\left(P\right) &= ${mathArgBest("min", "P_i")} \left( \left|P_i\right| \right) \\
  206. \alpha\left(P\right) &= ${mathArgBest("min", "P_i")} \left[ \frac{1}{\pi_i} \left|\left| \vec{q} - \vec{\mu}\left(P_i\right) \right|\right| \right] \\
  207. \omega\left(P\right) &= ${mathArgBest("max", "P_i")} \left[ \frac{1}{\pi_i} \left|\left| \vec{q} - \vec{\mu}\left(P_i\right) \right|\right| \right]
  208. \end{aligned}
  209. `,
  210. };
  211. const includeScaleFactor = muArg => state.clusterChoice > 0 && state.includeScale ? String.raw`\frac{\left|P\right|}{\left|${muArg}\right|}` : ""
  212. const metricText = [
  213. muArg => String.raw`
  214. ${mathArgBest("min", "P")}\left[
  215. ${includeScaleFactor(muArg)}I\left(P\right)
  216. - 2\vec{q}\cdot ${includeScaleFactor(muArg)}\vec{\mu}\left(${muArg}\right)
  217. \right]`,
  218. muArg => String.raw`${mathArgBest("min", "P")}\left[${includeScaleFactor(muArg)}\angle \left(\vec{q}, \vec{\mu}\left(${muArg}\right)\right)\right]`,
  219. muArg => String.raw`${mathArgBest("min", "P")}\left[${includeScaleFactor(muArg)}\left|\left|\vec{q} - \vec{\mu}\left(${muArg}\right) \right|\right|\right]`,
  220. muArg => String.raw`${mathArgBest("min", "P")}\left[${includeScaleFactor(muArg)}\angle \left(\vec{q}_{\perp}, \vec{\mu}\left(${muArg}\right)_{\perp}\right)\right]`,
  221. muArg => String.raw`${mathArgBest("min", "P")}\left[-${includeScaleFactor(muArg)}I\left(P\right)\right]`,
  222. ].map(s => muArg => TeXZilla.toMathML(s(muArg)));
  223. const muArgs = [
  224. "P",
  225. String.raw`M\left(P\right)`,
  226. String.raw`m\left(P\right)`,
  227. String.raw`\alpha\left(P\right)`,
  228. String.raw`\omega\left(P\right)`,
  229. ];
  230. const renderVec = math => String.raw`\vec{${math.charAt(0)}}${math.substr(1)}`;
  231. const renderNorm = vec => String.raw`\frac{${vec}}{\left|\left|${vec}\right|\right|}`;
  232. const updateObjective = () => {
  233. const muArg = muArgs[state.clusterChoice];
  234. let tex = metricText?.[state.metric]?.(muArg);
  235. if (!tex) {
  236. const { includeX, normQY, closeCoeff } = state;
  237. if (!includeX && closeCoeff === 0) {
  238. tex = TeXZilla.toMathML(String.raw`\text{Malamar-ness}`);
  239. } else {
  240. const qyMod = normQY ? renderNorm : c => c;
  241. tex = TeXZilla.toMathML(String.raw`
  242. ${mathArgBest("min", "P")}
  243. \left[
  244. ${includeX ? String.raw`${includeScaleFactor(muArg)}I\left(P\right)` : ""}
  245. ${closeCoeff === 0 ? "" : String.raw`
  246. -
  247. ${closeCoeff}
  248. ${qyMod("\\vec{q}")}
  249. \cdot
  250. ${includeScaleFactor(muArg)}${qyMod(String.raw`\vec{\mu}\left(${muArg}\right)`)}
  251. `}
  252. \right]
  253. `);
  254. }
  255. }
  256. const objFnNode = getObjFnDisplay();
  257. clearNodeContents(objFnNode);
  258. objFnNode.appendChild(tex);
  259. };
  260. // Pokemon Rendering
  261. const stripForm = ["flabebe", "floette", "florges", "vivillon", "basculin", "furfrou", "magearna"];
  262. const getSprite = pokemon => {
  263. pokemon = pokemon
  264. .replace("-alola", "-alolan")
  265. .replace("-galar", "-galarian")
  266. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  267. if (stripForm.find(s => pokemon.includes(s))) {
  268. pokemon = pokemon.replace(/-.*$/, "");
  269. }
  270. return `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`;
  271. };
  272. const renderCluster = ({
  273. index, big, small, best, worst, pi, theta, delta, phi, hex, vector,
  274. }) => `
  275. <div
  276. class="pkmn_tile-cluster"
  277. style="grid-area: k${index + 1}; color: ${getContrastingTextColor(hex2rgb(hex))}; background-color: ${hex};"
  278. >
  279. <div class="pkmn_tile-cluster-top_label" style="grid-area: lbl;">
  280. ${index === big ? "<span>M</span>" : ""}
  281. ${index === small ? "<span>m</span>" : ""}
  282. ${index === best ? "<span>α</span>" : ""}
  283. ${index === worst ? "<span>ω</span>" : ""}
  284. </div>
  285. <div class="pkmn_tile-cluster-stat_label" style="grid-area: mu;">μ =</div>
  286. <div class="pkmn_tile-cluster-stat_label" style="grid-area: pi;">π =</div>
  287. <div class="pkmn_tile-cluster-stat_label" style="grid-area: th;">θ =</div>
  288. <div class="pkmn_tile-cluster-stat_label" style="grid-area: dl;">δ =</div>
  289. <div class="pkmn_tile-cluster-stat_label" style="grid-area: ph;">ϕ =</div>
  290. <div style="grid-area: mux">${hex}</div>
  291. <div style="grid-area: muv; justify-self: center;">(${vector.map(c => c.toFixed(2)).join(", ")})</div>
  292. <div style="grid-area: piv">${(pi * 100).toFixed(1)}%</div>
  293. <div style="grid-area: thv">${theta.toFixed(2)}°</div>
  294. <div style="grid-area: dlv">${delta.toFixed(2)}</div>
  295. <div style="grid-area: phv">${phi.toFixed(2)}°</div>
  296. </div>
  297. `;
  298. const getPokemonRenderer = targetList => (name, stats, q, score, idPostfix) => {
  299. let sigma, metrics, kMeanInfo, kMeanResults;
  300. if (q) {
  301. sigma = Math.sqrt(stats.inertia - 2 * vectorDot(stats.trueMean.vector, q.vector) + q.magSq)
  302. metrics = calcDisplayMetrics(stats.trueMean, q)
  303. kMeanInfo = {
  304. big: stats.largestCluster,
  305. small: stats.smallestCluster,
  306. best: getBestKMean(stats, q),
  307. worst: getWorstKMean(stats, q), // TODO yeah yeah this is a recalc whatever
  308. };
  309. kMeanResults = stats.kMeans.map(k => calcDisplayMetrics(k, q));
  310. } else {
  311. // no target color, just do all zeros
  312. sigma = 0;
  313. metrics = { theta: 0, delta: 0, phi: 0 };
  314. kMeanInfo = { big: 0, small: 0, best: 0, worst: 0 };
  315. kMeanResults = [ metrics, metrics, metrics ];
  316. }
  317. const clusterToggleId = `reveal_clusters-${name}-${idPostfix}`;
  318. const li = document.createElement("li");
  319. li.innerHTML = `
  320. <div class="pkmn_tile">
  321. <img class="pkmn_tile-img" src="${getSprite(name)}" />
  322. <span class="pkmn_tile-name">
  323. ${name.split("-").map(part => part.charAt(0).toUpperCase() + part.substr(1)).join(" ")}
  324. </span>
  325. <div class="pkmn_tile-fn">
  326. ${score?.toFixed(3) ?? ""}
  327. </div>
  328. <input
  329. type="checkbox"
  330. ${state.clusterToggles?.[clusterToggleId] ? "checked" : ""}
  331. id="${clusterToggleId}"
  332. onchange="state.clusterToggles['${clusterToggleId}'] = event.target.checked"
  333. class="pkmn_tile-reveal_clusters"
  334. role="button"
  335. >
  336. <label class="pkmn_tile-reveal_clusters_label" for="${clusterToggleId}">
  337. <div class="pkmn_tile-reveal_clusters_label--closed">►</div>
  338. <div class="pkmn_tile-reveal_clusters_label--open">▼</div>
  339. </label>
  340. <div
  341. class="pkmn_tile-true_mean"
  342. style="color: ${getContrastingTextColor(hex2rgb(stats.trueMean.hex))}; background-color: ${stats.trueMean.hex};"
  343. >
  344. <div class="pkmn_tile-true_mean-value">
  345. <div class="pkmn_tile-true_mean-mu_label">μ =</div>
  346. <div class="pkmn_tile-true_mean-mu_hex">${stats.trueMean.hex}</div>
  347. <div class="pkmn_tile-true_mean-mu_vec">
  348. (${stats.trueMean.vector.map(c => c.toFixed(2)).join(", ")})
  349. </div>
  350. </div>
  351. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-inertia">
  352. 𝖨 = ${stats.inertia.toFixed(2)}
  353. </div>
  354. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-sigma">
  355. σ = ${sigma.toFixed(2)}
  356. </div>
  357. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-theta">
  358. θ = ${metrics.theta.toFixed(2)}°
  359. </div>
  360. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-delta">
  361. δ = ${metrics.delta.toFixed(2)}
  362. </div>
  363. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-phi">
  364. ϕ = ${metrics.phi.toFixed(2)}°
  365. </div>
  366. </div>
  367. ${stats.kMeans.map((data, index) => renderCluster({
  368. index,
  369. ...kMeanInfo,
  370. pi: stats.kWeights[index],
  371. ...kMeanResults[index],
  372. hex: data.hex,
  373. vector: data.vector,
  374. })).join("\n")}
  375. </div>
  376. `;
  377. targetList.appendChild(li);
  378. };
  379. // Update Search Results
  380. const renderSearch = () => {
  381. const resultsNode = getSearchListNode();
  382. const append = getPokemonRenderer(resultsNode);
  383. clearNodeContents(resultsNode);
  384. const argMapper = state.searchSpace === "RGB"
  385. ? pkmn => [pkmn.rgbStats, state.targetColor?.rgbData, state.currentScores?.[pkmn.name]?.rgb ?? null]
  386. : pkmn => [pkmn.jabStats, state.targetColor?.jabData, state.currentScores?.[pkmn.name]?.jab ?? null]
  387. state.searchResults?.forEach(pkmn => append(
  388. pkmn.name, ...argMapper(pkmn), "search"
  389. ));
  390. };
  391. // Scoring
  392. const renderScored = () => {
  393. const jabList = getScoreListJABNode();
  394. const appendJAB = getPokemonRenderer(jabList);
  395. const rgbList = getScoreListRGBNode();
  396. const appendRGB = getPokemonRenderer(rgbList);
  397. // extract best CIECAM02 results
  398. const bestJAB = pokemonColorData
  399. .sort((a, b) => state.currentScores[a.name].jab - state.currentScores[b.name].jab)
  400. .slice(0, state.numPoke);
  401. clearNodeContents(jabList);
  402. bestJAB.forEach(data => appendJAB(
  403. data.name, data.jabStats, state.targetColor.jabData, state.currentScores[data.name].jab, "jab"
  404. ));
  405. // extract best RGB results
  406. const bestRGB = pokemonColorData
  407. .sort((a, b) => state.currentScores[a.name].rgb - state.currentScores[b.name].rgb)
  408. .slice(0, state.numPoke);
  409. clearNodeContents(rgbList);
  410. bestRGB.forEach(data => appendRGB(
  411. data.name, data.rgbStats, state.targetColor.rgbData, state.currentScores[data.name].rgb, "rgb"
  412. ));
  413. };
  414. const rescore = () => {
  415. if (!state.targetColor) {
  416. return;
  417. }
  418. state.currentScores = {};
  419. pokemonColorData.forEach(data => {
  420. state.currentScores[data.name] = scorePokemon(data);
  421. });
  422. // update displays
  423. renderScored();
  424. // update the rendered search results as well
  425. renderSearch();
  426. };
  427. // Listeners
  428. const onColorChanged = skipScore => {
  429. const readColor = readColorInput();
  430. if (readColor) {
  431. state.targetColor = readColor;
  432. renderQVec(state.targetColor.jabData.vector.map(c => c.toFixed(3)), getQJABDisplay(), "Jab");
  433. renderQVec(state.targetColor.rgbData.vector.map(c => c.toFixed()), getQRGBDisplay(), "RGB");
  434. const rootElem = document.querySelector(":root");
  435. rootElem.style.setProperty("--background", state.targetColor.rgbData.hex);
  436. rootElem.style.setProperty("--highlight", getContrastingTextColor(state.targetColor.rgbData.vector));
  437. if (!skipScore) {
  438. rescore();
  439. }
  440. }
  441. };
  442. const onRandomColor = () => {
  443. const color = [Math.random(), Math.random(), Math.random()].map(c => c * 255);
  444. getColorInputNode().value = d3.rgb(...color).formatHex();
  445. onColorChanged(); // triggers rescore
  446. };
  447. const onCustomControlsChanged = skipScore => {
  448. state.includeX = getIncludeXToggleNode()?.checked ?? false;
  449. state.normQY = getNormQYToggleNode()?.checked ?? false;
  450. state.closeCoeff = parseFloat(getCloseCoeffSliderNode()?.value ?? 2);
  451. getCloseCoeffDisplayNode().innerHTML = state.closeCoeff;
  452. updateObjective();
  453. if (!skipScore) {
  454. rescore();
  455. }
  456. }
  457. const checkClusterMeanWarning = () => {
  458. const warning = getClusterMeanWarning();
  459. const unhidden = warning.getAttribute("class").replaceAll("hide", "");
  460. if (state.clusterChoice !== 0 && (state.metric === 0 || state.metric === 4)) {
  461. warning.setAttribute("class", unhidden);
  462. } else {
  463. warning.setAttribute("class", unhidden + " hide");
  464. }
  465. }
  466. const checkScaleByClusterToggle = () => {
  467. const toggle = getClusterScaleToggleNode()?.parentNode;
  468. const unhidden = toggle.getAttribute("class").replaceAll("hide", "");
  469. if (state.clusterChoice !== 0) {
  470. toggle.setAttribute("class", unhidden);
  471. } else {
  472. toggle.setAttribute("class", unhidden + " hide");
  473. }
  474. }
  475. const onScaleByClusterChanged = skipScore => {
  476. state.includeScale = getClusterScaleToggleNode()?.checked ?? true;
  477. updateObjective();
  478. if (!skipScore) {
  479. rescore();
  480. }
  481. }
  482. const onClusterChoiceChanged = skipScore => {
  483. const clusterChoice = getClusterChoiceDropdownNode()?.selectedIndex ?? 0;
  484. if (clusterChoice === state.clusterChoice) {
  485. return;
  486. }
  487. state.clusterChoice = clusterChoice;
  488. checkClusterMeanWarning();
  489. checkScaleByClusterToggle();
  490. updateObjective();
  491. if (!skipScore) {
  492. rescore();
  493. }
  494. }
  495. const onMetricChanged = skipScore => {
  496. const metric = getMetricDropdownNode()?.selectedIndex ?? 0;
  497. if (metric === state.metric) {
  498. return;
  499. }
  500. state.metric = metric;
  501. checkClusterMeanWarning();
  502. checkScaleByClusterToggle();
  503. if (state.metric === 5) { // Custom
  504. showCustomControls();
  505. onCustomControlsChanged(skipScore); // triggers rescore
  506. } else {
  507. hideCustomControls();
  508. updateObjective();
  509. if (!skipScore) {
  510. rescore();
  511. }
  512. }
  513. };
  514. const onLimitChanged = skipRenderScore => {
  515. state.numPoke = parseInt(getLimitSliderNode()?.value ?? 10);
  516. getLimitDisplayNode().textContent = state.numPoke;
  517. if (!skipRenderScore) {
  518. renderScored();
  519. }
  520. };
  521. const onSearchChanged = () => {
  522. state.searchTerm = getNameInputNode()?.value?.toLowerCase() ?? "";
  523. if (state.searchTerm.length === 0) {
  524. state.searchResults = [];
  525. } else {
  526. state.searchResults = pokemonLookup
  527. .search(state.searchTerm, { limit: 10 })
  528. .map(({ item }) => item);
  529. }
  530. renderSearch();
  531. };
  532. const onSearchSpaceChanged = () => {
  533. const old = state.searchSpace ?? "Jab";
  534. state.searchSpace = old === "RGB" ? "Jab" : "RGB";
  535. getSearchSpaceDisplayNode().textContent = old;
  536. renderSearch();
  537. };
  538. const onRandomPokemon = () => {
  539. getNameInputNode().value = "";
  540. state.searchResults = Array.from({ length: 10 }, () => pokemonColorData[Math.floor(Math.random() * pokemonColorData.length)]);
  541. renderSearch();
  542. };
  543. const onPageLoad = () => {
  544. // render static explanations
  545. Object.entries(mathDefinitions).forEach(([id, tex]) => {
  546. document.getElementById(id)?.appendChild(TeXZilla.toMathML(tex));
  547. });
  548. // fake some events but don't do any scoring
  549. onColorChanged(true);
  550. onMetricChanged(true);
  551. onClusterChoiceChanged(true);
  552. onScaleByClusterChanged(true);
  553. onLimitChanged(true);
  554. // then do a rescore directly, which will do nothing unless old data was loaded
  555. rescore();
  556. // finally render search in case rescore didn't
  557. onSearchChanged();
  558. };