nearest.js 23 KB

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