nearest.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 getSearchListNode = () => document.getElementById("search-list");
  17. const getHideableControlNodes = () => document.querySelectorAll(".hideable_control");
  18. const getQJABDisplay = () => document.getElementById("q-vec-jab");
  19. const getQRGBDisplay = () => document.getElementById("q-vec-rgb");
  20. const getObjFnDisplay = () => document.getElementById("obj-fn");
  21. const clearNodeContents = node => { node.innerHTML = ""; };
  22. const hideCustomControls = () => getHideableControlNodes()
  23. .forEach(n => n.setAttribute("class", "hideable_control hideable_control--hidden"));
  24. const showCustomControls = () => getHideableControlNodes()
  25. .forEach(n => n.setAttribute("class", "hideable_control"));
  26. // Vector Math
  27. const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
  28. const vectorSqMag = v => vectorDot(v, v);
  29. const vectorMag = v => Math.sqrt(vectorSqMag(v));
  30. const vectorSqDist = (u, v) => vectorSqMag(u.map((x, i) => x - v[i]));
  31. const vectorDist = (u, v) => Math.sqrt(vectorSqDist(u, v));
  32. const vectorNorm = v => { const n = vectorMag(v); return [ n, v.map(c => c / n) ]; };
  33. // Angle Math
  34. const angleDiff = (a, b) => { const raw = Math.abs(a - b); return raw < 180 ? raw : (360 - raw); };
  35. const rad2deg = 180 / Math.PI;
  36. // Conversions
  37. const jab2hex = jab => d3.jab(...jab).formatHex();
  38. const rgb2hex = rgb => d3.rgb(...rgb).formatHex();
  39. const jab2hue = ([, a, b]) => rad2deg * Math.atan2(b, a);
  40. const rgb2hue = rgb => d3.hsl(d3.rgb(...rgb)).h || 0;
  41. // Arg Compare
  42. const argComp = comp => ra => ra.map((x, i) => [x, i]).reduce((a, b) => comp(a[0], b[0]) > 0 ? b : a)[1];
  43. const argMin = argComp((a, b) => a - b);
  44. const argMax = argComp((a, b) => b - a);
  45. // Pre-Compute Data
  46. const computeVectorData = (vector, toHex, toHue) => {
  47. const [ magnitude, unit ] = vectorNorm(vector);
  48. return {
  49. vector,
  50. magnitude,
  51. magSq: magnitude * magnitude,
  52. unit,
  53. hex: toHex(vector),
  54. hue: toHue(vector),
  55. };
  56. };
  57. const computeStats = (varFromZero, trueMeanVec, kMeanStruct, toHex, toHue) => ({
  58. varFromZero,
  59. trueMean: computeVectorData(trueMeanVec, toHex, toHue),
  60. kMeans: kMeanStruct.slice(0, 3).map(z => computeVectorData(z, toHex, toHue)),
  61. kWeights: kMeanStruct[3],
  62. largestCluster: argMax(kMeanStruct[3]),
  63. smallestCluster: argMin(kMeanStruct[3]),
  64. });
  65. const pokemonColorData = database.map(({
  66. name, xJAB, xRGB, yJAB, yRGB, zJAB, zRGB,
  67. }) => ({
  68. name,
  69. jabStats: computeStats(xJAB, yJAB, zJAB, jab2hex, jab2hue),
  70. rgbStats: computeStats(xRGB, yRGB, zRGB, rgb2hex, rgb2hue),
  71. }));
  72. const pokemonLookup = new Fuse(pokemonColorData, { keys: [ "name" ] });
  73. // Color Calculations
  74. const getContrastingTextColor = rgb => vectorDot(rgb, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  75. const readColorInput = () => {
  76. const colorInput = "#" + (getColorInputNode()?.value?.replace("#", "") ?? "FFFFFF");
  77. if (colorInput.length !== 7) {
  78. return;
  79. }
  80. const rgb = d3.color(colorInput);
  81. const { J, a, b } = d3.jab(rgb);
  82. return {
  83. jabData: computeVectorData([ J, a, b ], jab2hex, jab2hue),
  84. rgbData: computeVectorData([ rgb.r, rgb.g, rgb.b ], rgb2hex, rgb2hue),
  85. };
  86. };
  87. // State
  88. const state = {
  89. metric: null,
  90. meanArgument: null,
  91. includeScaleInDist: null,
  92. includeX: null,
  93. normQY: null,
  94. closeCoeff: null,
  95. numPoke: null,
  96. searchTerm: null,
  97. targetColor: null,
  98. searchResults: null,
  99. };
  100. // Metrics
  101. const summarySelectors = [
  102. // true mean
  103. stats => [stats.trueMean, 1],
  104. // largest cluster
  105. stats => [stats.kMeans[stats.largestCluster], stats.kWeights[stats.largestCluster]],
  106. // smallest cluster
  107. stats => [stats.kMeans[stats.smallestCluster], stats.kWeights[stats.smallestCluster]],
  108. // best fit cluster
  109. (stats, q) => {
  110. const best = argMin(stats.kMeans.map((z, i) => vectorSqDist(z.vector, q.vector) / stats.kWeights[i]));
  111. return [stats.kMeans[best], stats.kWeights[best]];
  112. },
  113. // worst fit cluster
  114. (stats, q) => {
  115. const worst = argMax(stats.kMeans.map((z, i) => vectorSqDist(z.vector, q.vector) / stats.kWeights[i]));
  116. return [stats.kMeans[worst], stats.kWeights[worst]];
  117. },
  118. ];
  119. const selectedSummary = (stats, q) => summarySelectors[state.meanArgument](stats, q);
  120. const metrics = [
  121. // RMS
  122. (stats, q) => stats.varFromZero - 2 * vectorDot(selectedSummary(stats, q)[0].vector, q.vector),
  123. // mean angle
  124. (stats, q) => -vectorDot(selectedSummary(stats, q)[0].unit, q.unit),
  125. // mean dist
  126. (stats, q) => {
  127. // TODO I know there's some way to avoid recalculation here but I'm just too lazy right now
  128. const [data, scale] = selectedSummary(stats, q);
  129. return vectorSqDist(data.vector, q.vector) / (state.includeScaleInDist ? scale : 1);
  130. },
  131. // hue angle
  132. (stats, q) => angleDiff(selectedSummary(stats, q)[0].hue, q.hue),
  133. // custom
  134. (stats, q) => (state.includeX ? stats.varFromZero : 0) - state.closeCoeff * vectorDot(
  135. selectedSummary(stats, q)[0][state.normQY ? "unit" : "vector"],
  136. state.normQY ? q.unit : q.vector,
  137. ),
  138. ];
  139. const scorePokemon = pkmn => ({
  140. jab: metrics[state.metric](pkmn.jabStats, state.targetColor.jabData),
  141. rgb: metrics[state.metric](pkmn.rgbStats, state.targetColor.rgbData),
  142. });
  143. const calcDisplayMetrics = ({ jabStats, rgbStats }) => {
  144. // TODO - case on metric and meanArgument to avoid recalculation
  145. // TODO - is there ever any value to computing these around the selected summary instead?
  146. // obviously that has no mathematical value, and screws up the sqrts, but maybe?
  147. const cosAngleJAB = vectorDot(state.targetColor.jabData.unit, jabStats.trueMean.unit);
  148. const yTermJAB = cosAngleJAB * jabStats.trueMean.magnitude * state.targetColor.jabData.magnitude;
  149. const cosAngleRGB = vectorDot(state.targetColor.rgbData.unit, rgbStats.trueMean.unit);
  150. const yTermRGB = cosAngleRGB * rgbStats.trueMean.magnitude * state.targetColor.rgbData.magnitude;
  151. return {
  152. stdDevJAB: Math.sqrt(jabStats.varFromZero - 2 * yTermJAB + state.targetColor.jabData.magSq),
  153. stdDevRGB: Math.sqrt(rgbStats.varFromZero - 2 * yTermRGB + state.targetColor.rgbData.magSq),
  154. angleJAB: rad2deg * Math.acos(cosAngleJAB),
  155. angleRGB: rad2deg * Math.acos(cosAngleRGB),
  156. meanDistJAB: vectorDist(state.targetColor.jabData.vector, jabStats.trueMean.vector),
  157. meanDistRGB: vectorDist(state.targetColor.rgbData.vector, rgbStats.trueMean.vector),
  158. hueAngleJAB: angleDiff(state.targetColor.jabData.hue, jabStats.trueMean.hue),
  159. hueAngleRGB: angleDiff(state.targetColor.rgbData.hue, rgbStats.trueMean.hue),
  160. };
  161. };
  162. // Math Rendering
  163. const renderQVec = (q, node, sub) => {
  164. node.innerHTML = TeXZilla.toMathMLString(String.raw`\vec{q}_{\text{${sub}}} = \left(\text{${q.join(", ")}}\right)`);
  165. };
  166. const mathArgBest = (mxn, arg) => `\\underset{${arg}}{\\arg\\${mxn}}`;
  167. const mathDefinitions = {
  168. "main-definition": String.raw`
  169. \begin{aligned}
  170. \vec{\mu}\left(P\right) &= \frac{1}{\left|P\right|}\sum_{p\in P}{\vec{p}} \\
  171. I\left(P\right) &= \frac{1}{\left|P\right|}\sum_{p\in P}{\left|\left|\vec{p}\right|\right|^2} \\
  172. \vec{x}_{\perp} &= \text{oproj}_{\left\{\vec{J}, \vec{L}\right\}}{\vec{x}} \\
  173. \Delta{\theta}\left(P\right) &= \angle \left(\vec{q}_{\perp}, \vec{\mu}\left(P\right)_{\perp} \right)
  174. \end{aligned}
  175. `,
  176. "k-definition": String.raw`
  177. \begin{aligned}
  178. M\left(P\right) &= ${mathArgBest("max", "P_i")} \frac{\left|P_i\right|}{\left|P\right|} \\
  179. m\left(P\right) &= ${mathArgBest("min", "P_i")} \frac{\left|P_i\right|}{\left|P\right|} \\
  180. \alpha\left(P\right) &= ${mathArgBest("min", "P_i")} \frac{\left|P\right|}{\left|P_i\right|} \left|\left| \vec{q} - \vec{\mu}\left(P_i\right) \right|\right| \\
  181. \omega\left(P\right) &= ${mathArgBest("max", "P_i")} \frac{\left|P\right|}{\left|P_i\right|} \left|\left| \vec{q} - \vec{\mu}\left(P_i\right) \right|\right|
  182. \end{aligned}
  183. `,
  184. "cluster-definition": String.raw`
  185. \begin{aligned}
  186. \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
  187. \end{aligned}
  188. `,
  189. "rms-definition": String.raw`
  190. \text{RMS}_{P}\left(q\right) = \sqrt{E\left[\left|\left|\vec{q} - \vec{p}\right|\right|^2\right]} = \sqrt{\frac{1}{|P|}\sum_{p \in P}{\left|\left|\vec{p} - \vec{q}\right|\right|^2}}
  191. `,
  192. "result-definition": String.raw`
  193. \left(
  194. \text{RMS}_P\left(q\right),
  195. \angle \left(\vec{q}, \vec{\mu}\left(P\right)\right),
  196. \left|\left| \vec{q} - \vec{\mu}\left(P\right) \right|\right|,
  197. \Delta{\theta}\left(P\right)
  198. \right)
  199. `,
  200. };
  201. const metricText = [
  202. muArg => String.raw`${mathArgBest("min", "P")}\left[I\left(P\right) - 2\vec{q}\cdot \vec{\mu}\left(${muArg}\right)\right]`,
  203. muArg => String.raw`${mathArgBest("max", "P")}\left[\cos\left(\angle \left(\vec{q}, \vec{\mu}\left(${muArg}\right)\right)\right)\right]`,
  204. muArg => String.raw`${mathArgBest("min", "P")}\left[ ${state.includeScaleInDist ? String.raw`\frac{\left|P\right|}{\left|${muArg}\right|}` : ""} \left|\left| \vec{q} - \vec{\mu}\left(${muArg}\right) \right|\right|^2\right]`,
  205. muArg => String.raw`${mathArgBest("min", "P")} \left[\angle \left(\vec{q}_{\perp}, \vec{\mu}\left(${muArg}\right)_{\perp} \right)\right]`,
  206. ].map(s => muArg => TeXZilla.toMathML(s(muArg)));
  207. const muArgs = [
  208. "P",
  209. String.raw`M\left(P\right)`,
  210. String.raw`m\left(P\right)`,
  211. String.raw`\alpha\left(P\right)`,
  212. String.raw`\omega\left(P\right)`,
  213. ];
  214. const renderVec = math => String.raw`\vec{${math.charAt(0)}}${math.substr(1)}`;
  215. const renderNorm = vec => String.raw`\frac{${vec}}{\left|\left|${vec}\right|\right|}`;
  216. const updateObjective = () => {
  217. const muArg = muArgs[state.meanArgument];
  218. let tex = metricText?.[state.metric]?.(muArg);
  219. if (!tex) {
  220. const { includeX, normQY, closeCoeff } = state;
  221. if (!includeX && closeCoeff === 0) {
  222. tex = TeXZilla.toMathML(String.raw`\text{Empty Metric}`);
  223. } else {
  224. const qyMod = normQY ? renderNorm : c => c;
  225. tex = TeXZilla.toMathML(String.raw`
  226. ${mathArgBest(includeX ? "min" : "max", "P")}
  227. \left[
  228. ${includeX ? String.raw`I\left(P\right)` : ""}
  229. ${closeCoeff === 0 ? "" : String.raw`
  230. ${includeX ? "-" : ""}
  231. ${(includeX && closeCoeff !== 1) ? closeCoeff : ""}
  232. ${qyMod("\\vec{q}")}
  233. \cdot
  234. ${qyMod(String.raw`\vec{\mu}\left(${muArg}\right)`)}
  235. `}
  236. \right]
  237. `);
  238. }
  239. }
  240. const objFnNode = getObjFnDisplay();
  241. clearNodeContents(objFnNode);
  242. objFnNode.appendChild(tex);
  243. };
  244. // Pokemon Rendering
  245. const stripForm = ["flabebe", "floette", "florges", "vivillon", "basculin", "furfrou", "magearna"];
  246. const getSprite = pokemon => {
  247. pokemon = pokemon
  248. .replace("-alola", "-alolan")
  249. .replace("-galar", "-galarian")
  250. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  251. if (stripForm.find(s => pokemon.includes(s))) {
  252. pokemon = pokemon.replace(/-.*$/, "");
  253. }
  254. return `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`;
  255. };
  256. const renderPokemon = (data, classes = {}) => {
  257. const { name, jabStats, rgbStats, scores } = data;
  258. const { labelClass = "", rgbClass = "", jabClass = "", tileClass = "" } = classes;
  259. let { resultsClass = "" } = classes;
  260. let displayMetrics = {};
  261. if (!state.targetColor) {
  262. // no color selected need to skip scores
  263. resultsClass = "hide";
  264. } else {
  265. displayMetrics = calcDisplayMetrics(data);
  266. }
  267. const {
  268. stdDevJAB = 0, stdDevRGB = 0,
  269. angleJAB = 0, angleRGB = 0,
  270. meanDistJAB = 0, meanDistRGB = 0,
  271. hueAngleJAB = 0, hueAngleRGB = 0,
  272. } = displayMetrics;
  273. const titleName = name.split("-").map(part => part.charAt(0).toUpperCase() + part.substr(1)).join(" ");
  274. const textHex = getContrastingTextColor(rgbStats.trueMean.vector);
  275. const rgbVec = rgbStats.trueMean.vector.map(c => c.toFixed()).join(", ");
  276. const jabVec = jabStats.trueMean.vector.map(c => c.toFixed(1)).join(", ");
  277. // TODO Z dists, Z colors
  278. const pkmn = document.createElement("div");
  279. pkmn.setAttribute("class", `pokemon_tile ${tileClass}`);
  280. pkmn.innerHTML = `
  281. <div class="pokemon_tile-image-wrapper">
  282. <img src="${getSprite(name)}" />
  283. </div>
  284. <div class="pokemon_tile-info_panel">
  285. <span class="pokemon_tile-pokemon_name">
  286. ${titleName} ${scores?.jab?.toFixed(2) ?? ""} ${scores?.rgb?.toFixed(2) ?? ""}
  287. </span>
  288. <div class="pokemon_tile-results">
  289. <div class="pokemon_tile-labels ${labelClass}">
  290. <span class="${jabClass}">Jab: </span>
  291. <span class="${rgbClass}">RGB: </span>
  292. </div>
  293. <div class="pokemon_tile-score_column ${resultsClass}">
  294. <span class="${jabClass}">
  295. (${stdDevJAB.toFixed(2)}, ${angleJAB.toFixed(2)}&deg;, ${meanDistJAB.toFixed(2)}, ${hueAngleJAB.toFixed(2)}&deg;)
  296. </span>
  297. <span class="${rgbClass}">
  298. (${stdDevRGB.toFixed(2)}, ${angleRGB.toFixed(2)}&deg;, ${meanDistRGB.toFixed(2)}, ${hueAngleRGB.toFixed(2)}&deg;)
  299. </span>
  300. </div>
  301. <div class="pokemon_tile-hex_column">
  302. <div class="pokemon_tile-hex_color ${jabClass}" style="background-color: ${jabStats.trueMean.hex}; color: ${textHex}">
  303. <span>${jabStats.trueMean.hex}</span><span class="pokemon_tile-vector">(${jabVec})</span>
  304. </div>
  305. <div class="pokemon_tile-hex_color ${rgbClass}" style="background-color: ${rgbStats.trueMean.hex}; color: ${textHex}">
  306. <span>${rgbStats.trueMean.hex}</span><span class="pokemon_tile-vector">(${rgbVec})</span>
  307. </div>
  308. </div>
  309. </div>
  310. </div>
  311. `;
  312. return pkmn;
  313. };
  314. const getPokemonAppender = targetList => (pokemonData, classes) => {
  315. const li = document.createElement("li");
  316. li.appendChild(renderPokemon(pokemonData, classes));
  317. targetList.appendChild(li);
  318. };
  319. // Update Search Results
  320. const renderSearch = () => {
  321. const resultsNode = getSearchListNode();
  322. const append = getPokemonAppender(resultsNode);
  323. clearNodeContents(resultsNode);
  324. state.searchResults?.forEach(pkmn => append(pkmn));
  325. };
  326. // Scoring
  327. const rescore = () => {
  328. if (!state.targetColor) {
  329. return;
  330. }
  331. // TODO might like to save this somewhere instead of recomputing when limit changes
  332. const scores = pokemonColorData.map(data => ({ ...data, scores: scorePokemon(data) }));
  333. const jabList = getScoreListJABNode();
  334. const appendJAB = getPokemonAppender(jabList);
  335. const rgbList = getScoreListRGBNode();
  336. const appendRGB = getPokemonAppender(rgbList);
  337. // extract best CIECAM02 results
  338. const bestJAB = scores
  339. .sort((a, b) => a.scores.jab - b.scores.jab)
  340. .slice(0, state.numPoke);
  341. clearNodeContents(jabList);
  342. bestJAB.forEach(data => appendJAB(data, { labelClass: "hide", rgbClass: "hide", tileClass: "pokemon_tile--smaller" }));
  343. // extract best RGB results
  344. const bestRGB = scores
  345. .sort((a, b) => a.scores.rgb - b.scores.rgb)
  346. .slice(0, state.numPoke);
  347. clearNodeContents(rgbList);
  348. bestRGB.forEach(data => appendRGB(data, { labelClass: "hide", jabClass: "hide", tileClass: "pokemon_tile--smaller" }));
  349. // update the rendered search results as well
  350. renderSearch();
  351. };
  352. // Listeners
  353. const onColorChanged = skipScore => {
  354. const readColor = readColorInput();
  355. if (readColor) {
  356. state.targetColor = readColor;
  357. renderQVec(state.targetColor.jabData.vector.map(c => c.toFixed(2)), getQJABDisplay(), "Jab");
  358. renderQVec(state.targetColor.rgbData.vector.map(c => c.toFixed()), getQRGBDisplay(), "RGB");
  359. const textColor = getContrastingTextColor(state.targetColor.rgbData.vector);
  360. document.querySelector("body").setAttribute("style", `background: ${state.targetColor.rgbData.hex}; color: ${textColor}`);
  361. state.targetColor
  362. if (!skipScore) {
  363. rescore();
  364. }
  365. }
  366. };
  367. const onRandomColor = () => {
  368. const color = [Math.random(), Math.random(), Math.random()].map(c => c * 255);
  369. getColorInputNode().value = d3.rgb(...color).formatHex();
  370. onColorChanged(); // triggers rescore
  371. };
  372. const onCustomControlsChanged = skipScore => {
  373. state.includeX = getIncludeXToggleNode()?.checked ?? false;
  374. state.normQY = getNormQYToggleNode()?.checked ?? false;
  375. state.closeCoeff = parseFloat(getCloseCoeffSliderNode()?.value ?? 2);
  376. getCloseCoeffDisplayNode().innerHTML = state.closeCoeff;
  377. updateObjective();
  378. if (!skipScore) {
  379. rescore();
  380. }
  381. }
  382. const checkClusterMeanWarning = () => {
  383. const warning = getClusterMeanWarning();
  384. const unhidden = warning.getAttribute("class").replaceAll("hide", "");
  385. if (state.meanArgument !== 0 && state.metric === 0) {
  386. warning.setAttribute("class", unhidden);
  387. } else {
  388. warning.setAttribute("class", unhidden + " hide");
  389. }
  390. }
  391. const checkScaleByClusterToggle = () => {
  392. const toggle = getClusterScaleToggleNode()?.parentNode;
  393. const unhidden = toggle.getAttribute("class").replaceAll("hide", "");
  394. if (state.meanArgument !== 0 && state.metric === 2) {
  395. toggle.setAttribute("class", unhidden);
  396. } else {
  397. toggle.setAttribute("class", unhidden + " hide");
  398. }
  399. }
  400. const onScaleByClusterChanged = skipScore => {
  401. state.includeScaleInDist = getClusterScaleToggleNode()?.checked ?? true;
  402. updateObjective();
  403. if (!skipScore) {
  404. rescore();
  405. }
  406. }
  407. const onMeanArgumentChanged = skipScore => {
  408. const meanArgument = getMeanArgumentDropdownNode()?.selectedIndex ?? 0;
  409. if (meanArgument === state.meanArgument) {
  410. return;
  411. }
  412. state.meanArgument = meanArgument;
  413. checkClusterMeanWarning();
  414. checkScaleByClusterToggle();
  415. updateObjective();
  416. if (!skipScore) {
  417. rescore();
  418. }
  419. }
  420. const onMetricChanged = skipScore => {
  421. const metric = getMetricDropdownNode()?.selectedIndex ?? 0;
  422. if (metric === state.metric) {
  423. return;
  424. }
  425. state.metric = metric;
  426. checkClusterMeanWarning();
  427. checkScaleByClusterToggle();
  428. if (state.metric === 4) { // Custom
  429. showCustomControls();
  430. onCustomControlsChanged(skipScore); // triggers rescore
  431. } else {
  432. hideCustomControls();
  433. updateObjective();
  434. if (!skipScore) {
  435. rescore();
  436. }
  437. }
  438. };
  439. const onLimitChanged = skipScore => {
  440. state.numPoke = parseInt(getLimitSliderNode()?.value ?? 10);
  441. getLimitDisplayNode().textContent = state.numPoke;
  442. if (!skipScore) {
  443. // TODO don't need to rescore just need to expand
  444. rescore();
  445. }
  446. };
  447. const onSearchChanged = () => {
  448. state.searchTerm = getNameInputNode()?.value?.toLowerCase() ?? "";
  449. if (state.searchTerm.length === 0) {
  450. state.searchResults = [];
  451. } else {
  452. state.searchResults = pokemonLookup
  453. .search(state.searchTerm, { limit: 10 })
  454. .map(({ item }) => item);
  455. }
  456. renderSearch();
  457. };
  458. const onRandomPokemon = () => {
  459. getNameInputNode().value = "";
  460. state.searchResults = Array.from({ length: 10 }, () => pokemonColorData[Math.floor(Math.random() * pokemonColorData.length)]);
  461. renderSearch();
  462. };
  463. const onPageLoad = () => {
  464. // render static explanations
  465. Object.entries(mathDefinitions).forEach(([id, tex]) => {
  466. document.getElementById(id)?.appendChild(TeXZilla.toMathML(tex));
  467. });
  468. // fake some events but don't do any scoring
  469. onColorChanged(true);
  470. onMetricChanged(true);
  471. onMeanArgumentChanged(true);
  472. onScaleByClusterChanged(true);
  473. onLimitChanged(true);
  474. // then do a rescore directly, which will do nothing unless old data was loaded
  475. rescore();
  476. // finally render search in case rescore didn't
  477. onSearchChanged();
  478. };