nearest.js 19 KB

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