nearest.js 22 KB

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