nearest.js 20 KB

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