script.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // ---- Observables ----
  2. const targetColor = U.obs();
  3. const resultsToDisplay = U.obs(6);
  4. const colorSpace = U.obs("jab");
  5. const sortOrder = U.obs("min");
  6. const sortUseWholeImage = U.obs(true);
  7. const sortUseBestCluster = U.obs(true);
  8. const sortUseClusterSize = U.obs(false);
  9. const sortUseInverseClusterSize = U.obs(true);
  10. const sortUseTotalSize = U.obs(true);
  11. const sortUseInverseTotalSize = U.obs(false);
  12. const sortMetric = addMetricForm(
  13. "sortMetric",
  14. "Sort Metric",
  15. "whole",
  16. "alpha",
  17. "sort-metric-mount"
  18. );
  19. const clusterOrder = U.obs("max");
  20. const clusterUseClusterSize = U.obs(false);
  21. const clusterUseInverseClusterSize = U.obs(false);
  22. const clusterUseTotalSize = U.obs(false);
  23. const clusterUseInverseTotalSize = U.obs(false);
  24. const clusterMetric = addMetricForm(
  25. "clsMetric",
  26. "Cluster Metric",
  27. "stat",
  28. "importance",
  29. "cls-metric-mount"
  30. );
  31. const sortIgnoresCluster = U.obs(() =>
  32. [
  33. // ensure dep on all three
  34. sortUseBestCluster.value,
  35. sortUseClusterSize.value,
  36. sortUseInverseClusterSize.value,
  37. ].every((v) => !v)
  38. );
  39. // ---- Color Controls ----
  40. const randomizeTargetColor = () => {
  41. targetColor.value = d3
  42. .hsl(Math.random() * 360, Math.random(), Math.random())
  43. .formatHex();
  44. };
  45. U.element("targetSelect", ({ randomButton }, form) => {
  46. U.field(form.elements.colorText, { obs: targetColor });
  47. U.field(form.elements.colorPicker, { obs: targetColor });
  48. U.field(form.elements.resultsToDisplay, { obs: resultsToDisplay });
  49. U.reactive(() => {
  50. form.elements.resultsToDisplayOutput.value = resultsToDisplay.value;
  51. });
  52. // non-reactive since the form onchange updates it
  53. form.elements.colorSpace.value = colorSpace.value;
  54. U.form(form, {
  55. onChange: {
  56. colorSpace(value) {
  57. colorSpace.value = value;
  58. },
  59. },
  60. });
  61. randomButton.addEventListener("click", randomizeTargetColor);
  62. });
  63. const getColorButtonStyle = (hex) => {
  64. const { h, s, l } = d3.hsl(hex);
  65. return `
  66. color: ${getContrastingTextColor(hex)};
  67. --button-bg: ${hex};
  68. --button-bg-hover: ${d3.hsl(h, s, clamp(0.25, l * 1.25, 0.9)).formatHex()};
  69. `;
  70. };
  71. targetColor.subscribe((hex, { previous }) => {
  72. const style = document.querySelector(":root").style;
  73. style.setProperty("--background", hex);
  74. const highlight = getContrastingTextColor(hex);
  75. style.setProperty("--highlight", highlight);
  76. style.setProperty("--shadow-component", highlight.includes("light") ? "255" : "0");
  77. if (previous) {
  78. const prevButton = document.createElement("button");
  79. prevButton.innerText = previous;
  80. prevButton.classList = "color-select";
  81. prevButton.style = getColorButtonStyle(previous);
  82. prevButton.addEventListener("click", () => (targetColor.value = previous));
  83. document.getElementById("prevColors").prepend(prevButton);
  84. }
  85. });
  86. // ---- Metric Controls ----
  87. function addMetricForm(formName, legendText, initialKind, initialMetric, mountPoint) {
  88. const metricKind = U.obs(initialKind);
  89. let metric;
  90. U.template("metric-select-template", ({ form, legend }) => {
  91. form.name = formName;
  92. legend.innerText = legendText;
  93. form.elements[initialKind].disabled = false;
  94. form.elements[initialKind].value = initialMetric;
  95. form.elements.metricKind.value = initialKind;
  96. U.reactive(() => {
  97. form.elements.whole.disabled = metricKind.value !== "whole";
  98. form.elements.mean.disabled = metricKind.value !== "mean";
  99. form.elements.stat.disabled = metricKind.value !== "stat";
  100. });
  101. const metrics = U.obs([
  102. U.field(form.elements.whole),
  103. U.field(form.elements.mean),
  104. U.field(form.elements.stat),
  105. ]);
  106. U.form(form, {
  107. onChange: {
  108. metricKind(kind) {
  109. metricKind.value = kind;
  110. },
  111. },
  112. });
  113. metric = U.obs(() => {
  114. const [whole, mean, stat] = metrics.value;
  115. return { whole, mean, stat }[metricKind.value];
  116. });
  117. return mountPoint;
  118. });
  119. return metric;
  120. }
  121. // ---- Sorting Function Controls ----
  122. const getMetricSymbol = (metric) =>
  123. // terrible hack
  124. document.querySelector(`option[value=${metric}]`).textContent.at(-2);
  125. U.template(
  126. "function-template",
  127. ({ form, metricSymbol, metricSymbolCls, clusterName, clusterNameInv }) => {
  128. form.name = "sortFunction";
  129. U.field(form.elements.useWholeImage, { obs: sortUseWholeImage });
  130. U.field(form.elements.useBestCluster, { obs: sortUseBestCluster });
  131. U.field(form.elements.clusterSize, { obs: sortUseClusterSize });
  132. U.field(form.elements.invClusterSize, { obs: sortUseInverseClusterSize });
  133. U.field(form.elements.totalSize, { obs: sortUseTotalSize });
  134. U.field(form.elements.invTotalSize, { obs: sortUseInverseTotalSize });
  135. U.reactive(() => {
  136. const symbol = getMetricSymbol(sortMetric.value);
  137. metricSymbol.innerText = symbol;
  138. metricSymbolCls.innerText = `${symbol}(B)`;
  139. });
  140. clusterName.innerText = clusterNameInv.innerText = "B";
  141. form.elements.sortOrder.value = sortOrder.value;
  142. U.form(form, {
  143. onChange: {
  144. sortOrder(value) {
  145. sortOrder.value = value;
  146. },
  147. },
  148. });
  149. return "sort-fn-mount";
  150. }
  151. );
  152. U.template(
  153. "function-template",
  154. ({ form, useWholeImageLabel, metricSymbolCls, clusterName, clusterNameInv }) => {
  155. form.name = "clsFunction";
  156. form.elements.sortOrder.checked = true;
  157. U.field(form.elements.clusterSize, { obs: clusterUseClusterSize });
  158. U.field(form.elements.invClusterSize, { obs: clusterUseInverseClusterSize });
  159. U.field(form.elements.totalSize, { obs: clusterUseTotalSize });
  160. U.field(form.elements.invTotalSize, { obs: clusterUseInverseTotalSize });
  161. // not needed for cluster function
  162. useWholeImageLabel.nextSibling.remove();
  163. useWholeImageLabel.remove();
  164. // and this can't be disabled so just replace the field with the span
  165. metricSymbolCls.parentElement.replaceWith(metricSymbolCls);
  166. U.reactive(() => {
  167. metricSymbolCls.innerText = `${getMetricSymbol(clusterMetric.value)}(K)`;
  168. });
  169. clusterName.innerText = clusterNameInv.innerText = "K";
  170. form.elements.sortOrder.value = clusterOrder.value;
  171. U.form(form, {
  172. onChange: {
  173. sortOrder(value) {
  174. clusterOrder.value = value;
  175. },
  176. },
  177. });
  178. return "cls-fn-mount";
  179. }
  180. );
  181. U.reactive(() => {
  182. document.getElementById("cls-title").dataset.faded =
  183. document.forms.clsMetric.dataset.faded =
  184. document.forms.clsFunction.dataset.faded =
  185. sortIgnoresCluster.value;
  186. });
  187. // ---- Score Calculation ----
  188. const currentScores = U.obs(() => {
  189. const rgb = d3.rgb(targetColor.value);
  190. const { J, a, b } = d3.jab(rgb);
  191. const targetJab = buildVectorData([J, a, b], jab2hue, jab2lit, jab2chroma, jab2hex);
  192. const targetRgb = buildVectorData(
  193. [rgb.r, rgb.g, rgb.b],
  194. rgb2hue,
  195. rgb2lit,
  196. rgb2chroma,
  197. rgb2hex
  198. );
  199. const scores = {};
  200. pokemonData.forEach(({ name, jab, rgb }) => {
  201. scores[name] = {
  202. jab: {
  203. total: calcScores(jab.total, targetJab),
  204. clusters: jab.clusters.map((c) => calcScores(c, targetJab)),
  205. },
  206. rgb: {
  207. total: calcScores(rgb.total, targetRgb),
  208. clusters: rgb.clusters.map((c) => calcScores(c, targetRgb)),
  209. },
  210. };
  211. });
  212. return scores;
  213. });
  214. const sortOrders = {
  215. max: (a, b) => b - a,
  216. min: (a, b) => a - b,
  217. };
  218. const getClusterRankingValue = U.obs(() => {
  219. const metric = clusterMetric.value;
  220. const factors = [(cluster) => cluster[metric]];
  221. if (clusterUseClusterSize.value) {
  222. factors.push((cluster) => cluster.size);
  223. }
  224. if (clusterUseInverseClusterSize.value) {
  225. factors.push((cluster) => cluster.inverseSize);
  226. }
  227. if (clusterUseTotalSize.value) {
  228. factors.push((_, total) => total.size);
  229. }
  230. if (clusterUseInverseTotalSize.value) {
  231. factors.push((_, total) => total.inverseSize);
  232. }
  233. return (cluster, total) =>
  234. factors.map((fn) => fn(cluster, total)).reduce((x, y) => x * y);
  235. });
  236. const getBestClusterIndex = U.obs(() => {
  237. const rank = getClusterRankingValue.value;
  238. const clsSort = sortOrders[clusterOrder.value];
  239. return (scores) => {
  240. return scores.clusters
  241. .map((c, i) => [rank(c, scores.total), i])
  242. .reduce((a, b) => (clsSort(a[0], b[0]) > 0 ? b : a))[1];
  243. };
  244. });
  245. const getRankingValue = U.obs(() => {
  246. const metric = sortMetric.value;
  247. const factors = [];
  248. if (sortUseWholeImage.value) {
  249. factors.push((scores) => scores.total[metric]);
  250. }
  251. if (sortUseBestCluster.value) {
  252. factors.push((scores, index) => scores.clusters[index][metric]);
  253. }
  254. if (sortUseClusterSize.value) {
  255. factors.push((scores, index) => scores.clusters[index].size);
  256. }
  257. if (sortUseInverseClusterSize.value) {
  258. factors.push((scores, index) => scores.clusters[index].inverseSize);
  259. }
  260. if (sortUseTotalSize.value) {
  261. factors.push((scores) => scores.total.size);
  262. }
  263. if (sortUseInverseTotalSize.value) {
  264. factors.push((scores) => scores.total.inverseSize);
  265. }
  266. return (scores, bestClusterIndex) =>
  267. factors.map((fn) => fn(scores, bestClusterIndex)).reduce((x, y) => x * y, 1);
  268. });
  269. const currentResults = U.obs(() => {
  270. console.log("Recalculating");
  271. const bestClusterIndices = {};
  272. const rankingValues = {};
  273. pokemonData.forEach(({ name }) => {
  274. const { jab, rgb } = currentScores.value[name];
  275. const bestJab = getBestClusterIndex.value(jab);
  276. const bestRgb = getBestClusterIndex.value(rgb);
  277. bestClusterIndices[name] = { jab: bestJab, rgb: bestRgb };
  278. rankingValues[name] = {
  279. jab: getRankingValue.value(jab, bestJab),
  280. rgb: getRankingValue.value(rgb, bestRgb),
  281. };
  282. });
  283. return { bestClusterIndices, rankingValues };
  284. });
  285. const sortedResults = U.obs(() => {
  286. console.log("Resorting");
  287. const { rankingValues } = currentResults.value;
  288. const sort = sortOrders[sortOrder.value];
  289. const space = colorSpace.value;
  290. return pokemonData
  291. .map(({ name }) => name)
  292. .sort(
  293. (a, b) =>
  294. sort(rankingValues[a][space], rankingValues[b][space]) || a.localeCompare(b)
  295. );
  296. });
  297. const colorSearchResults = U.obs(() =>
  298. sortedResults.value.slice(0, resultsToDisplay.value)
  299. );
  300. // ---- Pokemon Display ----
  301. const getSpriteName = (() => {
  302. const stripForm = [
  303. "flabebe",
  304. "floette",
  305. "florges",
  306. "vivillon",
  307. "basculin",
  308. "furfrou",
  309. "magearna",
  310. "alcremie",
  311. ];
  312. return (pokemon) => {
  313. pokemon = pokemon
  314. .replace("-alola", "-alolan")
  315. .replace("-galar", "-galarian")
  316. .replace("-hisui", "-hisuian")
  317. .replace("-paldea", "-paldean")
  318. .replace("-paldeanfire", "-paldean-fire") // tauros
  319. .replace("-paldeanwater", "-paldean-water") // tauros
  320. .replace("-phony", "") // sinistea and polteageist
  321. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  322. if (stripForm.find((s) => pokemon.includes(s))) {
  323. pokemon = pokemon.replace(/-.*$/, "");
  324. }
  325. return pokemon;
  326. };
  327. })();
  328. const displayPokemon = (pkmnName, target) => {
  329. const spriteName = getSpriteName(pkmnName);
  330. const formattedName = pkmnName
  331. .split("-")
  332. .map((part) => part.charAt(0).toUpperCase() + part.substr(1))
  333. .join(" ");
  334. U.template(
  335. "pkmn-template",
  336. ({ image, name, score, totalBtn, cls1Btn, cls2Btn, cls3Btn, cls4Btn }) => {
  337. const imageErrHandler = () => {
  338. image.removeEventListener("error", imageErrHandler);
  339. image.src = `https://img.pokemondb.net/sprites/sword-shield/icon/${spriteName}.png`;
  340. };
  341. image.addEventListener("error", imageErrHandler);
  342. image.src = `https://img.pokemondb.net/sprites/scarlet-violet/icon/${spriteName}.png`;
  343. name.innerText = name.title = image.alt = formattedName;
  344. U.reactive(() => {
  345. const { rankingValues } = currentResults.value;
  346. score.innerText = rankingValues[pkmnName][colorSpace.value].toFixed(2);
  347. });
  348. U.reactive(() => {
  349. const { total } = currentScores.value[pkmnName][colorSpace.value];
  350. totalBtn.innerText = total.muHex;
  351. totalBtn.style = getColorButtonStyle(total.muHex);
  352. });
  353. U.reactive(() => {
  354. totalBtn.dataset.best = [
  355. sortUseWholeImage.value,
  356. sortUseTotalSize.value,
  357. sortUseInverseTotalSize.value,
  358. ].reduce((x, y) => x || y);
  359. });
  360. totalBtn.addEventListener("click", () => {
  361. targetColor.value = currentScores.value[pkmnName][colorSpace.value].total.muHex;
  362. });
  363. // TODO this will need to be reactive when we start actually pulling stats
  364. const { clusters } = currentScores.value[pkmnName][colorSpace.value];
  365. [cls1Btn, cls2Btn, cls3Btn, cls4Btn].forEach((button, index) => {
  366. if (index >= clusters.length) {
  367. return;
  368. }
  369. button.hidden = false;
  370. const { muHex } = clusters[index];
  371. button.innerText = muHex;
  372. button.style = getColorButtonStyle(muHex);
  373. button.addEventListener("click", () => {
  374. targetColor.value = muHex;
  375. });
  376. U.reactive(() => {
  377. const { bestClusterIndices } = currentResults.value;
  378. const bestCluster = bestClusterIndices[pkmnName][colorSpace.value];
  379. button.dataset.best = !sortIgnoresCluster.value && index === bestCluster;
  380. });
  381. });
  382. // TODO stat dialog
  383. return target;
  384. }
  385. );
  386. };
  387. // ---- Display Logic ----
  388. const colorSearchResultsTarget = document.getElementById("color-results");
  389. colorSearchResults.subscribe(() => {
  390. colorSearchResultsTarget.innerHTML = "";
  391. colorSearchResults.value.forEach((name) =>
  392. displayPokemon(name, colorSearchResultsTarget)
  393. );
  394. });
  395. // ---- Name Search ----
  396. U.element("nameSearch", ({ input, randomBtn, clearBtn }) => {
  397. const nameSearchInput = U.field(input);
  398. const lookupLimit = 24;
  399. const pokemonLookup = new Fuse(pokemonData, { keys: ["name"] });
  400. const nameSearchResults = U.obs(() =>
  401. pokemonLookup
  402. .search(nameSearchInput.value, { limit: lookupLimit })
  403. .map(({ item: { name } }) => name)
  404. );
  405. randomBtn.addEventListener("click", () => {
  406. nameSearchResults.value = Array.from(
  407. { length: lookupLimit },
  408. () => pokemonData[Math.floor(Math.random() * pokemonData.length)].name
  409. );
  410. });
  411. clearBtn.addEventListener("click", () => {
  412. nameSearchResults.value = [];
  413. nameSearchInput.value = "";
  414. });
  415. const nameResultsTarget = document.getElementById("name-results");
  416. nameSearchResults.subscribe(() => {
  417. nameResultsTarget.innerHTML = "";
  418. nameSearchResults.value.forEach((name) => displayPokemon(name, nameResultsTarget));
  419. });
  420. });
  421. // ---- Initial Target ----
  422. randomizeTargetColor();