script.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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, minmaxLabel, metricSymbol, metricSymbolCls, clusterName, clusterNameInv }) => {
  128. form.name = "sortFunction";
  129. const toggle = U.field(form.elements.sortOrder);
  130. U.reactive(() => {
  131. toggle.value = sortOrder.value === "max";
  132. });
  133. U.reactive(() => {
  134. sortOrder.value = toggle.value ? "max" : "min";
  135. });
  136. U.reactive(() => {
  137. minmaxLabel.innerText = sortOrder.value;
  138. });
  139. U.field(form.elements.useWholeImage, { obs: sortUseWholeImage });
  140. U.field(form.elements.useBestCluster, { obs: sortUseBestCluster });
  141. U.field(form.elements.clusterSize, { obs: sortUseClusterSize });
  142. U.field(form.elements.invClusterSize, { obs: sortUseInverseClusterSize });
  143. U.field(form.elements.totalSize, { obs: sortUseTotalSize });
  144. U.field(form.elements.invTotalSize, { obs: sortUseInverseTotalSize });
  145. U.reactive(() => {
  146. const symbol = getMetricSymbol(sortMetric.value);
  147. metricSymbol.innerText = symbol;
  148. metricSymbolCls.innerText = `${symbol}(B)`;
  149. });
  150. clusterName.innerText = clusterNameInv.innerText = "B";
  151. U.form(form);
  152. return "sort-fn-mount";
  153. }
  154. );
  155. U.template(
  156. "function-template",
  157. ({
  158. form,
  159. minmaxLabel,
  160. useWholeImageLabel,
  161. metricSymbolCls,
  162. clusterName,
  163. clusterNameInv,
  164. }) => {
  165. form.name = "clsFunction";
  166. form.elements.sortOrder.checked = true;
  167. const toggle = U.field(form.elements.sortOrder);
  168. U.reactive(() => {
  169. toggle.value = clusterOrder.value === "max";
  170. minmaxLabel.innerText = `(Arg) ${clusterOrder.value}`;
  171. });
  172. U.reactive(() => {
  173. clusterOrder.value = toggle.value ? "max" : "min";
  174. });
  175. U.field(form.elements.clusterSize, { obs: clusterUseClusterSize });
  176. U.field(form.elements.invClusterSize, { obs: clusterUseInverseClusterSize });
  177. U.field(form.elements.totalSize, { obs: clusterUseTotalSize });
  178. U.field(form.elements.invTotalSize, { obs: clusterUseInverseTotalSize });
  179. // not needed for cluster function
  180. useWholeImageLabel.nextSibling.remove();
  181. useWholeImageLabel.remove();
  182. // and this can't be disabled so just replace the field with the span
  183. metricSymbolCls.parentElement.replaceWith(metricSymbolCls);
  184. U.reactive(() => {
  185. metricSymbolCls.innerText = `${getMetricSymbol(clusterMetric.value)}(K)`;
  186. });
  187. clusterName.innerText = clusterNameInv.innerText = "K";
  188. U.form(form);
  189. return "cls-fn-mount";
  190. }
  191. );
  192. U.reactive(() => {
  193. document.getElementById("cls-title").dataset.faded =
  194. document.forms.clsMetric.dataset.faded =
  195. document.forms.clsFunction.dataset.faded =
  196. sortIgnoresCluster.value;
  197. });
  198. // ---- Score Calculation ----
  199. const currentScores = U.obs(() => {
  200. const rgb = d3.rgb(targetColor.value);
  201. const { J, a, b } = d3.jab(rgb);
  202. const targetJab = buildVectorData([J, a, b], jab2hue, jab2lit, jab2chroma, jab2hex);
  203. const targetRgb = buildVectorData(
  204. [rgb.r, rgb.g, rgb.b],
  205. rgb2hue,
  206. rgb2lit,
  207. rgb2chroma,
  208. rgb2hex
  209. );
  210. const scores = {};
  211. pokemonData.forEach(({ name, jab, rgb }) => {
  212. scores[name] = {
  213. jab: {
  214. total: calcScores(jab.total, targetJab),
  215. clusters: jab.clusters.map((c) => calcScores(c, targetJab)),
  216. },
  217. rgb: {
  218. total: calcScores(rgb.total, targetRgb),
  219. clusters: rgb.clusters.map((c) => calcScores(c, targetRgb)),
  220. },
  221. };
  222. });
  223. return scores;
  224. });
  225. const sortOrders = {
  226. max: (a, b) => b - a,
  227. min: (a, b) => a - b,
  228. };
  229. const getClusterRankingValue = U.obs(() => {
  230. const metric = clusterMetric.value;
  231. const factors = [(cluster) => cluster[metric]];
  232. if (clusterUseClusterSize.value) {
  233. factors.push((cluster) => cluster.size);
  234. }
  235. if (clusterUseInverseClusterSize.value) {
  236. factors.push((cluster) => cluster.inverseSize);
  237. }
  238. if (clusterUseTotalSize.value) {
  239. factors.push((_, total) => total.size);
  240. }
  241. if (clusterUseInverseTotalSize.value) {
  242. factors.push((_, total) => total.inverseSize);
  243. }
  244. return (cluster, total) =>
  245. factors.map((fn) => fn(cluster, total)).reduce((x, y) => x * y);
  246. });
  247. const getBestClusterIndex = U.obs(() => {
  248. const rank = getClusterRankingValue.value;
  249. const clsSort = sortOrders[clusterOrder.value];
  250. return (scores) => {
  251. return scores.clusters
  252. .map((c, i) => [rank(c, scores.total), i])
  253. .reduce((a, b) => (clsSort(a[0], b[0]) > 0 ? b : a))[1];
  254. };
  255. });
  256. const getRankingValue = U.obs(() => {
  257. const metric = sortMetric.value;
  258. const factors = [];
  259. if (sortUseWholeImage.value) {
  260. factors.push((scores) => scores.total[metric]);
  261. }
  262. if (sortUseBestCluster.value) {
  263. factors.push((scores, index) => scores.clusters[index][metric]);
  264. }
  265. if (sortUseClusterSize.value) {
  266. factors.push((scores, index) => scores.clusters[index].size);
  267. }
  268. if (sortUseInverseClusterSize.value) {
  269. factors.push((scores, index) => scores.clusters[index].inverseSize);
  270. }
  271. if (sortUseTotalSize.value) {
  272. factors.push((scores) => scores.total.size);
  273. }
  274. if (sortUseInverseTotalSize.value) {
  275. factors.push((scores) => scores.total.inverseSize);
  276. }
  277. return (scores, bestClusterIndex) =>
  278. factors.map((fn) => fn(scores, bestClusterIndex)).reduce((x, y) => x * y, 1);
  279. });
  280. const currentResults = U.obs(() => {
  281. console.log("Recalculating");
  282. const bestClusterIndices = {};
  283. const rankingValues = {};
  284. pokemonData.forEach(({ name }) => {
  285. const { jab, rgb } = currentScores.value[name];
  286. const bestJab = getBestClusterIndex.value(jab);
  287. const bestRgb = getBestClusterIndex.value(rgb);
  288. bestClusterIndices[name] = { jab: bestJab, rgb: bestRgb };
  289. rankingValues[name] = {
  290. jab: getRankingValue.value(jab, bestJab),
  291. rgb: getRankingValue.value(rgb, bestRgb),
  292. };
  293. });
  294. return { bestClusterIndices, rankingValues };
  295. });
  296. const sortedResults = U.obs(() => {
  297. console.log("Resorting");
  298. const { rankingValues } = currentResults.value;
  299. const sort = sortOrders[sortOrder.value];
  300. const space = colorSpace.value;
  301. return pokemonData
  302. .map(({ name }) => name)
  303. .sort(
  304. (a, b) =>
  305. sort(rankingValues[a][space], rankingValues[b][space]) || a.localeCompare(b)
  306. );
  307. });
  308. const colorSearchResults = U.obs(() =>
  309. sortedResults.value.slice(0, resultsToDisplay.value)
  310. );
  311. // ---- Pokemon Display ----
  312. const getSpriteName = (() => {
  313. const stripForm = [
  314. "flabebe",
  315. "floette",
  316. "florges",
  317. "vivillon",
  318. "basculin",
  319. "furfrou",
  320. "magearna",
  321. "alcremie",
  322. ];
  323. return (pokemon) => {
  324. pokemon = pokemon
  325. .replace("-alola", "-alolan")
  326. .replace("-galar", "-galarian")
  327. .replace("-hisui", "-hisuian")
  328. .replace("-paldea", "-paldean")
  329. .replace("-paldeanfire", "-paldean-fire") // tauros
  330. .replace("-paldeanwater", "-paldean-water") // tauros
  331. .replace("-phony", "") // sinistea and polteageist
  332. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  333. if (stripForm.find((s) => pokemon.includes(s))) {
  334. pokemon = pokemon.replace(/-.*$/, "");
  335. }
  336. return pokemon;
  337. };
  338. })();
  339. const displayPokemon = (pkmnName, target) => {
  340. const spriteName = getSpriteName(pkmnName);
  341. const formattedName = pkmnName
  342. .split("-")
  343. .map((part) => part.charAt(0).toUpperCase() + part.substr(1))
  344. .join(" ");
  345. // TODO this will need to be reactive when we start actually pulling stats
  346. const { total, clusters } = currentScores.value[pkmnName][colorSpace.value];
  347. U.template(
  348. "pkmn-template",
  349. ({ image, name, score, totalBtn, cls1Btn, cls2Btn, cls3Btn, cls4Btn }) => {
  350. const imageErrHandler = () => {
  351. image.removeEventListener("error", imageErrHandler);
  352. image.src = `https://img.pokemondb.net/sprites/sword-shield/icon/${spriteName}.png`;
  353. };
  354. image.addEventListener("error", imageErrHandler);
  355. image.src = `https://img.pokemondb.net/sprites/scarlet-violet/icon/${spriteName}.png`;
  356. name.innerText = name.title = image.alt = formattedName;
  357. U.reactive(() => {
  358. const { rankingValues } = currentResults.value;
  359. score.innerText = rankingValues[pkmnName][colorSpace.value].toFixed(2);
  360. });
  361. totalBtn.innerText = total.muHex;
  362. totalBtn.style = getColorButtonStyle(total.muHex);
  363. totalBtn.addEventListener("click", () => {
  364. targetColor.value = total.muHex;
  365. });
  366. totalBtn.dataset.best =
  367. sortUseWholeImage.value ||
  368. sortUseTotalSize.value ||
  369. sortUseInverseTotalSize.value;
  370. [cls1Btn, cls2Btn, cls3Btn, cls4Btn].forEach((button, index) => {
  371. if (index >= clusters.length) {
  372. button.remove();
  373. return;
  374. }
  375. const { muHex } = clusters[index];
  376. button.innerText = muHex;
  377. button.style = getColorButtonStyle(muHex);
  378. button.addEventListener("click", () => {
  379. targetColor.value = muHex;
  380. });
  381. U.reactive(() => {
  382. const { bestClusterIndices } = currentResults.value;
  383. const bestCluster = bestClusterIndices[pkmnName][colorSpace.value];
  384. button.dataset.best = !sortIgnoresCluster.value && index === bestCluster;
  385. });
  386. });
  387. // TODO stat dialog
  388. // TODO click name to copy?
  389. return target;
  390. }
  391. );
  392. };
  393. // ---- Display Logic ----
  394. const colorSearchResultsTarget = document.getElementById("color-results");
  395. colorSearchResults.subscribe(() => {
  396. colorSearchResultsTarget.innerHTML = "";
  397. colorSearchResults.value.forEach((name) =>
  398. displayPokemon(name, colorSearchResultsTarget)
  399. );
  400. });
  401. // ---- Name Search ----
  402. U.element("nameSearch", ({ input, button }) => {
  403. const nameSearchInput = U.field(input);
  404. const lookupLimit = 24;
  405. const pokemonLookup = new Fuse(pokemonData, { keys: ["name"] });
  406. const nameSearchResults = U.obs(() =>
  407. pokemonLookup
  408. .search(nameSearchInput.value, { limit: lookupLimit })
  409. .map(({ item: { name } }) => name)
  410. );
  411. button.addEventListener("click", () => {
  412. nameSearchResults.value = Array.from(
  413. { length: lookupLimit },
  414. () => pokemonData[Math.floor(Math.random() * pokemonData.length)].name
  415. );
  416. });
  417. const nameResultsTarget = document.getElementById("name-results");
  418. nameSearchResults.subscribe(() => {
  419. nameResultsTarget.innerHTML = "";
  420. nameSearchResults.value.forEach((name) => displayPokemon(name, nameResultsTarget));
  421. });
  422. });
  423. // ---- Initial Target ----
  424. randomizeTargetColor();