nearest.js 20 KB

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