script.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. style.setProperty("--highlight", getContrastingTextColor(hex));
  75. if (previous) {
  76. const prevButton = document.createElement("button");
  77. prevButton.innerText = previous;
  78. prevButton.classList = "color-select";
  79. prevButton.style = getColorButtonStyle(previous);
  80. prevButton.addEventListener("click", () => (targetColor.value = previous));
  81. document.getElementById("prevColors").prepend(prevButton);
  82. }
  83. });
  84. // ---- Metric Controls ----
  85. function addMetricForm(formName, legendText, initialKind, initialMetric, mountPoint) {
  86. const metricKind = U.obs(initialKind);
  87. let metric;
  88. U.template("metric-select-template", ({ form, legend }) => {
  89. form.name = formName;
  90. legend.innerText = legendText;
  91. form.elements[initialKind].disabled = false;
  92. form.elements[initialKind].value = initialMetric;
  93. form.elements.metricKind.value = initialKind;
  94. U.reactive(() => {
  95. form.elements.whole.disabled = metricKind.value !== "whole";
  96. form.elements.mean.disabled = metricKind.value !== "mean";
  97. form.elements.stat.disabled = metricKind.value !== "stat";
  98. });
  99. const metrics = U.obs([
  100. U.field(form.elements.whole),
  101. U.field(form.elements.mean),
  102. U.field(form.elements.stat),
  103. ]);
  104. U.form(form, {
  105. onChange: {
  106. metricKind(kind) {
  107. metricKind.value = kind;
  108. },
  109. },
  110. });
  111. metric = U.obs(() => {
  112. const [whole, mean, stat] = metrics.value;
  113. return { whole, mean, stat }[metricKind.value];
  114. });
  115. return mountPoint;
  116. });
  117. return metric;
  118. }
  119. // ---- Sorting Function Controls ----
  120. const getMetricSymbol = (metric) =>
  121. // terrible hack
  122. document.querySelector(`option[value=${metric}]`).textContent.at(-2);
  123. U.template(
  124. "function-template",
  125. ({ form, minmaxLabel, metricSymbol, metricSymbolCls, clusterName, clusterNameInv }) => {
  126. form.name = "sortFunction";
  127. const toggle = U.field(form.elements.sortOrder);
  128. U.reactive(() => {
  129. toggle.value = sortOrder.value === "max";
  130. });
  131. U.reactive(() => {
  132. sortOrder.value = toggle.value ? "max" : "min";
  133. });
  134. U.reactive(() => {
  135. minmaxLabel.innerText = sortOrder.value;
  136. });
  137. U.field(form.elements.useWholeImage, { obs: sortUseWholeImage });
  138. U.field(form.elements.useBestCluster, { obs: sortUseBestCluster });
  139. U.field(form.elements.clusterSize, { obs: sortUseClusterSize });
  140. U.field(form.elements.invClusterSize, { obs: sortUseInverseClusterSize });
  141. U.field(form.elements.totalSize, { obs: sortUseTotalSize });
  142. U.field(form.elements.invTotalSize, { obs: sortUseInverseTotalSize });
  143. U.reactive(() => {
  144. const symbol = getMetricSymbol(sortMetric.value);
  145. metricSymbol.innerText = symbol;
  146. metricSymbolCls.innerText = `${symbol}(B)`;
  147. });
  148. clusterName.innerText = clusterNameInv.innerText = "B";
  149. U.form(form);
  150. return "sort-fn-mount";
  151. }
  152. );
  153. U.template(
  154. "function-template",
  155. ({
  156. form,
  157. minmaxLabel,
  158. useWholeImageLabel,
  159. metricSymbolCls,
  160. clusterName,
  161. clusterNameInv,
  162. }) => {
  163. form.name = "clsFunction";
  164. form.elements.sortOrder.checked = true;
  165. const toggle = U.field(form.elements.sortOrder);
  166. U.reactive(() => {
  167. toggle.value = clusterOrder.value === "max";
  168. minmaxLabel.innerText = `arg${clusterOrder.value}`;
  169. });
  170. U.reactive(() => {
  171. clusterOrder.value = toggle.value ? "max" : "min";
  172. });
  173. U.field(form.elements.clusterSize, { obs: clusterUseClusterSize });
  174. U.field(form.elements.invClusterSize, { obs: clusterUseInverseClusterSize });
  175. U.field(form.elements.totalSize, { obs: clusterUseTotalSize });
  176. U.field(form.elements.invTotalSize, { obs: clusterUseInverseTotalSize });
  177. // not needed for cluster function
  178. useWholeImageLabel.nextSibling.remove();
  179. useWholeImageLabel.remove();
  180. // and this can't be disabled so just replace the field with the span
  181. metricSymbolCls.parentElement.replaceWith(metricSymbolCls);
  182. U.reactive(() => {
  183. metricSymbolCls.innerText = `${getMetricSymbol(clusterMetric.value)}(K)`;
  184. });
  185. clusterName.innerText = clusterNameInv.innerText = "K";
  186. U.form(form);
  187. return "cls-fn-mount";
  188. }
  189. );
  190. U.reactive(() => {
  191. document.forms.clsMetric.dataset.faded = document.forms.clsFunction.dataset.faded =
  192. sortIgnoresCluster.value;
  193. });
  194. // ---- Score Calculation ----
  195. const currentScores = U.obs(() => {
  196. const rgb = d3.rgb(targetColor.value);
  197. const { J, a, b } = d3.jab(rgb);
  198. const targetJab = buildVectorData([J, a, b], jab2hue, jab2lit, jab2chroma, jab2hex);
  199. const targetRgb = buildVectorData(
  200. [rgb.r, rgb.g, rgb.b],
  201. rgb2hue,
  202. rgb2lit,
  203. rgb2chroma,
  204. rgb2hex
  205. );
  206. const scores = {};
  207. pokemonData.forEach(({ name, jab, rgb }) => {
  208. scores[name] = {
  209. jab: {
  210. total: calcScores(jab.total, targetJab),
  211. clusters: jab.clusters.map((c) => calcScores(c, targetJab)),
  212. },
  213. rgb: {
  214. total: calcScores(rgb.total, targetRgb),
  215. clusters: rgb.clusters.map((c) => calcScores(c, targetRgb)),
  216. },
  217. };
  218. });
  219. return scores;
  220. });
  221. const sortOrders = {
  222. max: (a, b) => b - a,
  223. min: (a, b) => a - b,
  224. };
  225. const getClusterRankingValue = U.obs(() => {
  226. const metric = clusterMetric.value;
  227. const factors = [(cluster) => cluster[metric]];
  228. if (clusterUseClusterSize.value) {
  229. factors.push((cluster) => cluster.size);
  230. }
  231. if (clusterUseInverseClusterSize.value) {
  232. factors.push((cluster) => cluster.inverseSize);
  233. }
  234. if (clusterUseTotalSize.value) {
  235. factors.push((_, total) => total.size);
  236. }
  237. if (clusterUseInverseTotalSize.value) {
  238. factors.push((_, total) => total.inverseSize);
  239. }
  240. return (cluster, total) =>
  241. factors.map((fn) => fn(cluster, total)).reduce((x, y) => x * y);
  242. });
  243. const getBestClusterIndex = U.obs(() => {
  244. const rank = getClusterRankingValue.value;
  245. const clsSort = sortOrders[clusterOrder.value];
  246. return (scores) => {
  247. return scores.clusters
  248. .map((c, i) => [rank(c, scores.total), i])
  249. .reduce((a, b) => (clsSort(a[0], b[0]) > 0 ? b : a))[1];
  250. };
  251. });
  252. const getRankingValue = U.obs(() => {
  253. const metric = sortMetric.value;
  254. const factors = [];
  255. if (sortUseWholeImage.value) {
  256. factors.push((scores) => scores.total[metric]);
  257. }
  258. if (sortUseBestCluster.value) {
  259. factors.push((scores, index) => scores.clusters[index][metric]);
  260. }
  261. if (sortUseClusterSize.value) {
  262. factors.push((scores, index) => scores.clusters[index].size);
  263. }
  264. if (sortUseInverseClusterSize.value) {
  265. factors.push((scores, index) => scores.clusters[index].inverseSize);
  266. }
  267. if (sortUseTotalSize.value) {
  268. factors.push((scores) => scores.total.size);
  269. }
  270. if (sortUseInverseTotalSize.value) {
  271. factors.push((scores) => scores.total.inverseSize);
  272. }
  273. return (scores, bestClusterIndex) =>
  274. factors.map((fn) => fn(scores, bestClusterIndex)).reduce((x, y) => x * y, 1);
  275. });
  276. const currentResults = U.obs(() => {
  277. console.log("Recalculating");
  278. const bestClusterIndices = {};
  279. const rankingValues = {};
  280. pokemonData.forEach(({ name }) => {
  281. const { jab, rgb } = currentScores.value[name];
  282. const bestJab = getBestClusterIndex.value(jab);
  283. const bestRgb = getBestClusterIndex.value(rgb);
  284. bestClusterIndices[name] = { jab: bestJab, rgb: bestRgb };
  285. rankingValues[name] = {
  286. jab: getRankingValue.value(jab, bestJab),
  287. rgb: getRankingValue.value(rgb, bestRgb),
  288. };
  289. });
  290. return { bestClusterIndices, rankingValues };
  291. });
  292. const sortedResults = U.obs(() => {
  293. console.log("Resorting");
  294. const { rankingValues } = currentResults.value;
  295. const sort = sortOrders[sortOrder.value];
  296. const space = colorSpace.value;
  297. return pokemonData
  298. .map(({ name }) => name)
  299. .sort(
  300. (a, b) =>
  301. sort(rankingValues[a][space], rankingValues[b][space]) || a.localeCompare(b)
  302. );
  303. });
  304. const colorSearchResults = U.obs(() =>
  305. sortedResults.value.slice(0, resultsToDisplay.value)
  306. );
  307. randomizeTargetColor();