@wordpress/theme 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +69 -9
  2. package/bin/generate-default-ramps/index.ts +49 -0
  3. package/bin/generate-primitive-tokens/index.ts +14 -9
  4. package/bin/terrazzo-plugin-ds-tokens-docs/index.ts +5 -24
  5. package/bin/terrazzo-plugin-figma-ds-token-manager/index.ts +11 -4
  6. package/bin/terrazzo-plugin-inline-alias-values/index.ts +84 -0
  7. package/bin/terrazzo-plugin-known-wpds-css-variables/index.ts +19 -39
  8. package/build/color-ramps/index.js +21 -39
  9. package/build/color-ramps/index.js.map +3 -3
  10. package/build/color-ramps/lib/color-utils.js +39 -0
  11. package/build/color-ramps/lib/color-utils.js.map +7 -0
  12. package/build/color-ramps/lib/constants.js +20 -27
  13. package/build/color-ramps/lib/constants.js.map +3 -3
  14. package/build/color-ramps/lib/default-ramps.js +220 -0
  15. package/build/color-ramps/lib/default-ramps.js.map +7 -0
  16. package/build/color-ramps/lib/find-color-with-constraints.js +60 -91
  17. package/build/color-ramps/lib/find-color-with-constraints.js.map +3 -3
  18. package/build/color-ramps/lib/index.js +77 -119
  19. package/build/color-ramps/lib/index.js.map +3 -3
  20. package/build/color-ramps/lib/ramp-configs.js +15 -14
  21. package/build/color-ramps/lib/ramp-configs.js.map +2 -2
  22. package/build/color-ramps/lib/register-color-spaces.js +7 -0
  23. package/build/color-ramps/lib/register-color-spaces.js.map +7 -0
  24. package/build/color-ramps/lib/taper-chroma.js +35 -27
  25. package/build/color-ramps/lib/taper-chroma.js.map +3 -3
  26. package/build/color-ramps/lib/types.js +2 -1
  27. package/build/color-ramps/lib/types.js.map +1 -1
  28. package/build/color-ramps/lib/utils.js +75 -11
  29. package/build/color-ramps/lib/utils.js.map +2 -2
  30. package/build/context.js +3 -2
  31. package/build/context.js.map +1 -1
  32. package/build/index.js +2 -1
  33. package/build/index.js.map +1 -1
  34. package/build/lock-unlock.js +3 -2
  35. package/build/lock-unlock.js.map +1 -1
  36. package/build/prebuilt/js/design-tokens.js +19 -11
  37. package/build/prebuilt/js/design-tokens.js.map +2 -2
  38. package/build/prebuilt/json/figma.json +165 -783
  39. package/build/prebuilt/ts/color-tokens.js +137 -0
  40. package/build/prebuilt/ts/color-tokens.js.map +7 -0
  41. package/build/private-apis.js +3 -2
  42. package/build/private-apis.js.map +1 -1
  43. package/build/theme-provider.js +19 -17
  44. package/build/theme-provider.js.map +4 -4
  45. package/build/token-id.js +30 -0
  46. package/build/token-id.js.map +7 -0
  47. package/build/types/css-modules.d.js +0 -1
  48. package/build/types.js +2 -1
  49. package/build/types.js.map +1 -1
  50. package/build/use-theme-provider-styles.js +67 -62
  51. package/build/use-theme-provider-styles.js.map +3 -3
  52. package/build-module/color-ramps/index.js +20 -28
  53. package/build-module/color-ramps/index.js.map +2 -2
  54. package/build-module/color-ramps/lib/color-utils.js +19 -0
  55. package/build-module/color-ramps/lib/color-utils.js.map +7 -0
  56. package/build-module/color-ramps/lib/constants.js +14 -11
  57. package/build-module/color-ramps/lib/constants.js.map +2 -2
  58. package/build-module/color-ramps/lib/default-ramps.js +196 -0
  59. package/build-module/color-ramps/lib/default-ramps.js.map +7 -0
  60. package/build-module/color-ramps/lib/find-color-with-constraints.js +61 -87
  61. package/build-module/color-ramps/lib/find-color-with-constraints.js.map +2 -2
  62. package/build-module/color-ramps/lib/index.js +85 -109
  63. package/build-module/color-ramps/lib/index.js.map +3 -3
  64. package/build-module/color-ramps/lib/ramp-configs.js +14 -13
  65. package/build-module/color-ramps/lib/ramp-configs.js.map +2 -2
  66. package/build-module/color-ramps/lib/register-color-spaces.js +7 -0
  67. package/build-module/color-ramps/lib/register-color-spaces.js.map +7 -0
  68. package/build-module/color-ramps/lib/taper-chroma.js +40 -16
  69. package/build-module/color-ramps/lib/taper-chroma.js.map +2 -2
  70. package/build-module/color-ramps/lib/utils.js +70 -6
  71. package/build-module/color-ramps/lib/utils.js.map +2 -2
  72. package/build-module/context.js +2 -1
  73. package/build-module/context.js.map +1 -1
  74. package/build-module/index.js +1 -0
  75. package/build-module/index.js.map +1 -1
  76. package/build-module/lock-unlock.js +2 -1
  77. package/build-module/lock-unlock.js.map +1 -1
  78. package/build-module/prebuilt/js/design-tokens.js +18 -10
  79. package/build-module/prebuilt/js/design-tokens.js.map +2 -2
  80. package/build-module/prebuilt/json/figma.json +165 -783
  81. package/build-module/prebuilt/ts/color-tokens.js +117 -0
  82. package/build-module/prebuilt/ts/color-tokens.js.map +7 -0
  83. package/build-module/private-apis.js +2 -1
  84. package/build-module/private-apis.js.map +1 -1
  85. package/build-module/theme-provider.js +18 -6
  86. package/build-module/theme-provider.js.map +3 -3
  87. package/build-module/token-id.js +6 -0
  88. package/build-module/token-id.js.map +7 -0
  89. package/build-module/use-theme-provider-styles.js +69 -57
  90. package/build-module/use-theme-provider-styles.js.map +2 -2
  91. package/build-types/color-ramps/index.d.ts +9 -16
  92. package/build-types/color-ramps/index.d.ts.map +1 -1
  93. package/build-types/color-ramps/lib/color-utils.d.ts +22 -0
  94. package/build-types/color-ramps/lib/color-utils.d.ts.map +1 -0
  95. package/build-types/color-ramps/lib/constants.d.ts +7 -9
  96. package/build-types/color-ramps/lib/constants.d.ts.map +1 -1
  97. package/build-types/color-ramps/lib/default-ramps.d.ts +7 -0
  98. package/build-types/color-ramps/lib/default-ramps.d.ts.map +1 -0
  99. package/build-types/color-ramps/lib/find-color-with-constraints.d.ts +8 -7
  100. package/build-types/color-ramps/lib/find-color-with-constraints.d.ts.map +1 -1
  101. package/build-types/color-ramps/lib/index.d.ts +5 -2
  102. package/build-types/color-ramps/lib/index.d.ts.map +1 -1
  103. package/build-types/color-ramps/lib/register-color-spaces.d.ts +2 -0
  104. package/build-types/color-ramps/lib/register-color-spaces.d.ts.map +1 -0
  105. package/build-types/color-ramps/lib/taper-chroma.d.ts +7 -3
  106. package/build-types/color-ramps/lib/taper-chroma.d.ts.map +1 -1
  107. package/build-types/color-ramps/lib/utils.d.ts +28 -5
  108. package/build-types/color-ramps/lib/utils.d.ts.map +1 -1
  109. package/build-types/color-ramps/stories/index.story.d.ts.map +1 -1
  110. package/build-types/prebuilt/ts/color-tokens.d.ts +7 -0
  111. package/build-types/prebuilt/ts/color-tokens.d.ts.map +1 -0
  112. package/build-types/stories/index.story.d.ts.map +1 -1
  113. package/build-types/theme-provider.d.ts.map +1 -1
  114. package/build-types/token-id.d.ts +9 -0
  115. package/build-types/token-id.d.ts.map +1 -0
  116. package/build-types/use-theme-provider-styles.d.ts +4 -0
  117. package/build-types/use-theme-provider-styles.d.ts.map +1 -1
  118. package/docs/ds-tokens.md +22 -156
  119. package/package.json +19 -9
  120. package/src/color-ramps/index.ts +24 -41
  121. package/src/color-ramps/lib/color-utils.ts +34 -0
  122. package/src/color-ramps/lib/constants.ts +13 -9
  123. package/src/color-ramps/lib/default-ramps.ts +200 -0
  124. package/src/color-ramps/lib/find-color-with-constraints.ts +83 -116
  125. package/src/color-ramps/lib/index.ts +107 -145
  126. package/src/color-ramps/lib/ramp-configs.ts +3 -3
  127. package/src/color-ramps/lib/register-color-spaces.ts +13 -0
  128. package/src/color-ramps/lib/taper-chroma.ts +47 -19
  129. package/src/color-ramps/lib/utils.ts +117 -14
  130. package/src/color-ramps/stories/index.story.tsx +16 -22
  131. package/src/color-ramps/test/__snapshots__/index.test.ts.snap +45722 -376
  132. package/src/color-ramps/test/index.test.ts +68 -29
  133. package/src/prebuilt/css/design-tokens.css +88 -355
  134. package/src/prebuilt/js/design-tokens.js +17 -10
  135. package/src/prebuilt/json/figma.json +165 -783
  136. package/src/prebuilt/ts/color-tokens.ts +117 -0
  137. package/src/stories/index.story.tsx +4 -18
  138. package/src/test/token-id.test.ts +12 -0
  139. package/src/token-id.ts +9 -0
  140. package/src/use-theme-provider-styles.ts +67 -60
  141. package/terrazzo.config.ts +15 -12
  142. package/tokens/color.json +221 -69
  143. package/tokens/dimension.json +75 -0
  144. package/tsconfig.bin.json +13 -0
  145. package/tsconfig.bin.tsbuildinfo +1 -0
  146. package/tsconfig.json +6 -4
  147. package/tsconfig.src.json +9 -0
  148. package/tsconfig.src.tsbuildinfo +1 -0
  149. package/bin/build-tokens.js +0 -83
  150. package/build/color-ramps/lib/cache-utils.js +0 -57
  151. package/build/color-ramps/lib/cache-utils.js.map +0 -7
  152. package/build/prebuilt/ts/design-tokens.js +0 -354
  153. package/build/prebuilt/ts/design-tokens.js.map +0 -7
  154. package/build/style.module.css.js +0 -2
  155. package/build-module/color-ramps/lib/cache-utils.js +0 -31
  156. package/build-module/color-ramps/lib/cache-utils.js.map +0 -7
  157. package/build-module/prebuilt/ts/design-tokens.js +0 -334
  158. package/build-module/prebuilt/ts/design-tokens.js.map +0 -7
  159. package/build-module/style.module.css.js +0 -1
  160. package/build-style/style.css +0 -3
  161. package/build-types/color-ramps/lib/cache-utils.d.ts +0 -22
  162. package/build-types/color-ramps/lib/cache-utils.d.ts.map +0 -1
  163. package/build-types/prebuilt/ts/design-tokens.d.ts +0 -7
  164. package/build-types/prebuilt/ts/design-tokens.d.ts.map +0 -1
  165. package/src/color-ramps/lib/cache-utils.ts +0 -56
  166. package/src/prebuilt/ts/design-tokens.ts +0 -335
  167. package/tokens/spacing.json +0 -45
  168. package/tsconfig.tsbuildinfo +0 -1
@@ -1,109 +1,83 @@
1
- import Color from "colorjs.io";
2
- import { clampToGamut } from "./utils";
3
- import {
4
- WHITE,
5
- BLACK,
6
- LIGHTNESS_EPSILON,
7
- MAX_BISECTION_ITERATIONS
8
- } from "./constants";
9
- import { getCachedContrast } from "./cache-utils";
1
+ // packages/theme/src/color-ramps/lib/find-color-with-constraints.ts
2
+ import { get, OKLCH } from "colorjs.io/fn";
3
+ import "./register-color-spaces";
4
+ import { clampToGamut, solveWithBisect } from "./utils";
5
+ import { WHITE, BLACK, CONTRAST_EPSILON } from "./constants";
6
+ import { getContrast } from "./color-utils";
10
7
  import { taperChroma } from "./taper-chroma";
8
+ function cdiff(c1, c2) {
9
+ return Math.log(c1 / c2);
10
+ }
11
11
  function findColorMeetingRequirements(reference, seed, target, direction, {
12
12
  lightnessConstraint,
13
- taperChromaOptions,
14
- strict = true,
15
- debug = false
13
+ taperChromaOptions
16
14
  } = {}) {
17
15
  if (target <= 1) {
18
- return { color: seed.clone(), reached: true, achieved: 1 };
16
+ return {
17
+ color: reference,
18
+ reached: true,
19
+ achieved: 1
20
+ };
19
21
  }
20
- if (lightnessConstraint) {
21
- let newL = lightnessConstraint.value;
22
- let newC = seed.oklch.c;
22
+ function getColorForL(l) {
23
+ let newL = l;
24
+ let newC = get(seed, [OKLCH, "c"]);
23
25
  if (taperChromaOptions) {
24
- ({ l: newL, c: newC } = taperChroma(
25
- seed,
26
- newL,
27
- taperChromaOptions
28
- ));
29
- }
30
- const colorWithExactL = clampToGamut(
31
- new Color("oklch", [newL, newC, seed.oklch.h])
32
- );
33
- const exactLContrast = getCachedContrast(reference, colorWithExactL);
34
- if (debug) {
35
- console.log(
36
- `Succeeded with ${lightnessConstraint.type} lightness`,
37
- lightnessConstraint.value,
38
- colorWithExactL.oklch.l
39
- );
26
+ const tapered = taperChroma(seed, newL, taperChromaOptions);
27
+ if ("l" in tapered && "c" in tapered) {
28
+ newL = tapered.l;
29
+ newC = tapered.c;
30
+ } else {
31
+ return tapered;
32
+ }
40
33
  }
41
- if (lightnessConstraint.type === "force" || exactLContrast >= target) {
34
+ return clampToGamut({
35
+ spaceId: "oklch",
36
+ coords: [newL, newC, get(seed, [OKLCH, "h"])]
37
+ });
38
+ }
39
+ const mostContrastingL = direction === "lighter" ? 1 : 0;
40
+ const mostContrastingColor = direction === "lighter" ? WHITE : BLACK;
41
+ const highestContrast = getContrast(reference, mostContrastingColor);
42
+ if (lightnessConstraint) {
43
+ const colorWithExactL = getColorForL(lightnessConstraint.value);
44
+ const exactLContrast = getContrast(reference, colorWithExactL);
45
+ const exactLContrastMeetsTarget = cdiff(exactLContrast, target) >= -CONTRAST_EPSILON;
46
+ if (exactLContrastMeetsTarget || lightnessConstraint.type === "force") {
42
47
  return {
43
48
  color: colorWithExactL,
44
- reached: exactLContrast >= target,
45
- achieved: exactLContrast
49
+ reached: exactLContrastMeetsTarget,
50
+ achieved: exactLContrast,
51
+ deficit: exactLContrastMeetsTarget ? cdiff(exactLContrast, highestContrast) : cdiff(target, exactLContrast)
46
52
  };
47
53
  }
48
54
  }
49
- const mostContrastingL = direction === "lighter" ? 1 : 0;
50
- const mostContrastingColor = direction === "lighter" ? WHITE : BLACK;
51
- const highestPossibleContrast = getCachedContrast(
52
- reference,
53
- mostContrastingColor
54
- );
55
- if (highestPossibleContrast < target) {
56
- if (strict) {
57
- throw new Error(
58
- `Contrast target ${target.toFixed(
59
- 2
60
- )}:1 unreachable in ${direction} direction against ${mostContrastingColor.toString()}(boundary achieves ${highestPossibleContrast.toFixed(
61
- 3
62
- )}:1).`
63
- );
64
- }
65
- if (debug) {
66
- console.log(
67
- "Did not succeeded because it reached the limit",
68
- mostContrastingL
69
- );
70
- }
55
+ if (cdiff(highestContrast, target) <= CONTRAST_EPSILON) {
71
56
  return {
72
57
  color: mostContrastingColor,
73
- reached: false,
74
- achieved: highestPossibleContrast
58
+ reached: cdiff(highestContrast, target) >= -CONTRAST_EPSILON,
59
+ achieved: highestContrast,
60
+ deficit: cdiff(target, highestContrast)
75
61
  };
76
62
  }
77
- let worseL = reference.oklch.l;
78
- let betterL = mostContrastingL;
79
- let bestContrastFound = highestPossibleContrast;
80
- let resultingColor = mostContrastingColor;
81
- for (let i = 0; i < MAX_BISECTION_ITERATIONS && Math.abs(betterL - worseL) > LIGHTNESS_EPSILON; i++) {
82
- let newL = (worseL + betterL) / 2;
83
- let newC = seed.oklch.c;
84
- if (taperChromaOptions) {
85
- ({ l: newL, c: newC } = taperChroma(
86
- seed,
87
- newL,
88
- taperChromaOptions
89
- ));
90
- }
91
- const newColor = clampToGamut(
92
- new Color("oklch", [newL, newC, seed.oklch.h])
93
- );
94
- const newContrast = getCachedContrast(reference, newColor);
95
- if (newContrast >= target) {
96
- betterL = newL;
97
- bestContrastFound = newContrast;
98
- resultingColor = newColor;
99
- } else {
100
- worseL = newL;
101
- }
102
- }
63
+ const lowerL = get(reference, [OKLCH, "l"]);
64
+ const lowerContrast = cdiff(1, target);
65
+ const upperL = mostContrastingL;
66
+ const upperContrast = cdiff(highestContrast, target);
67
+ const bestColor = solveWithBisect(
68
+ getColorForL,
69
+ (c) => cdiff(getContrast(reference, c), target),
70
+ lowerL,
71
+ lowerContrast,
72
+ upperL,
73
+ upperContrast
74
+ );
103
75
  return {
104
- color: resultingColor,
76
+ color: bestColor,
105
77
  reached: true,
106
- achieved: bestContrastFound
78
+ achieved: target,
79
+ // Negative number that specifies how much room we have.
80
+ deficit: cdiff(target, highestContrast)
107
81
  };
108
82
  }
109
83
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/color-ramps/lib/find-color-with-constraints.ts"],
4
- "sourcesContent": ["/**\n * External dependencies\n */\nimport Color from 'colorjs.io';\n\n/**\n * Internal dependencies\n */\nimport { clampToGamut } from './utils';\nimport {\n\tWHITE,\n\tBLACK,\n\tLIGHTNESS_EPSILON,\n\tMAX_BISECTION_ITERATIONS,\n} from './constants';\nimport { getCachedContrast } from './cache-utils';\nimport { type TaperChromaOptions, taperChroma } from './taper-chroma';\n\n/**\n * Solve for L such that:\n * - the L applied to the seed meets the contrast target against the reference\n * - the search is performed in one direction (ie lighter / darker)\n * - more constraints can be applied around lightness\n * - chroma could be tapered\n * @param reference\n * @param seed\n * @param target\n * @param direction\n * @param options\n * @param options.strict\n * @param options.debug\n * @param options.lightnessConstraint\n * @param options.lightnessConstraint.type\n * @param options.lightnessConstraint.value\n * @param options.taperChromaOptions\n */\nexport function findColorMeetingRequirements(\n\treference: Color,\n\tseed: Color,\n\ttarget: number,\n\tdirection: 'lighter' | 'darker',\n\t{\n\t\tlightnessConstraint,\n\t\ttaperChromaOptions,\n\t\tstrict = true,\n\t\tdebug = false,\n\t}: {\n\t\tlightnessConstraint?: {\n\t\t\ttype: 'force' | 'onlyIfSucceeds';\n\t\t\tvalue: number;\n\t\t};\n\t\ttaperChromaOptions?: TaperChromaOptions;\n\t\tstrict?: boolean;\n\t\tdebug?: boolean;\n\t} = {}\n): { color: Color; reached: boolean; achieved: number } {\n\t// A target of 1 means same color.\n\t// A target lower than 1 doesn't make sense.\n\tif ( target <= 1 ) {\n\t\treturn { color: seed.clone(), reached: true, achieved: 1 };\n\t}\n\n\tif ( lightnessConstraint ) {\n\t\t// Apply a specific L value.\n\t\t// Useful when pinning a step to a specific lightness, of to specify\n\t\t// min/max L values.\n\t\tlet newL = lightnessConstraint.value;\n\t\tlet newC = seed.oklch.c;\n\n\t\tif ( taperChromaOptions ) {\n\t\t\t( { l: newL, c: newC } = taperChroma(\n\t\t\t\tseed,\n\t\t\t\tnewL,\n\t\t\t\ttaperChromaOptions\n\t\t\t) );\n\t\t}\n\n\t\tconst colorWithExactL = clampToGamut(\n\t\t\tnew Color( 'oklch', [ newL, newC, seed.oklch.h ] )\n\t\t);\n\t\tconst exactLContrast = getCachedContrast( reference, colorWithExactL );\n\n\t\tif ( debug ) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(\n\t\t\t\t`Succeeded with ${ lightnessConstraint.type } lightness`,\n\t\t\t\tlightnessConstraint.value,\n\t\t\t\tcolorWithExactL.oklch.l\n\t\t\t);\n\t\t}\n\n\t\t// If the L constraint is of \"force\" type, apply it even when it doesn't\n\t\t// meet the contrast target.\n\t\tif (\n\t\t\tlightnessConstraint.type === 'force' ||\n\t\t\texactLContrast >= target\n\t\t) {\n\t\t\treturn {\n\t\t\t\tcolor: colorWithExactL,\n\t\t\t\treached: exactLContrast >= target,\n\t\t\t\tachieved: exactLContrast,\n\t\t\t};\n\t\t}\n\t}\n\n\t// Set the boundary based on the direction.\n\tconst mostContrastingL = direction === 'lighter' ? 1 : 0;\n\tconst mostContrastingColor = direction === 'lighter' ? WHITE : BLACK;\n\tconst highestPossibleContrast = getCachedContrast(\n\t\treference,\n\t\tmostContrastingColor\n\t);\n\n\t// If even the most contrasting color can't reach the target,\n\t// the target is unreachable.\n\tif ( highestPossibleContrast < target ) {\n\t\tif ( strict ) {\n\t\t\tthrow new Error(\n\t\t\t\t`Contrast target ${ target.toFixed(\n\t\t\t\t\t2\n\t\t\t\t) }:1 unreachable in ${ direction } direction against ${ mostContrastingColor.toString() }` +\n\t\t\t\t\t`(boundary achieves ${ highestPossibleContrast.toFixed(\n\t\t\t\t\t\t3\n\t\t\t\t\t) }:1).`\n\t\t\t);\n\t\t}\n\n\t\tif ( debug ) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(\n\t\t\t\t'Did not succeeded because it reached the limit',\n\t\t\t\tmostContrastingL\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tcolor: mostContrastingColor,\n\t\t\treached: false,\n\t\t\tachieved: highestPossibleContrast,\n\t\t};\n\t}\n\n\t// Bracket: low fails, high meets.\n\t// Originally this was seed.oklch.l \u2014 although it's an assumption that works\n\t// only when we know for sure the direction of the search.\n\t// TODO: can we bring this back to seed.oklch.l ?\n\tlet worseL = reference.oklch.l;\n\tlet betterL = mostContrastingL;\n\n\tlet bestContrastFound = highestPossibleContrast;\n\tlet resultingColor = mostContrastingColor;\n\n\tfor (\n\t\tlet i = 0;\n\t\ti < MAX_BISECTION_ITERATIONS &&\n\t\tMath.abs( betterL - worseL ) > LIGHTNESS_EPSILON;\n\t\ti++\n\t) {\n\t\tlet newL = ( worseL + betterL ) / 2;\n\t\tlet newC = seed.oklch.c;\n\n\t\tif ( taperChromaOptions ) {\n\t\t\t( { l: newL, c: newC } = taperChroma(\n\t\t\t\tseed,\n\t\t\t\tnewL,\n\t\t\t\ttaperChromaOptions\n\t\t\t) );\n\t\t}\n\n\t\tconst newColor = clampToGamut(\n\t\t\tnew Color( 'oklch', [ newL, newC, seed.oklch.h ] )\n\t\t);\n\t\tconst newContrast = getCachedContrast( reference, newColor );\n\n\t\tif ( newContrast >= target ) {\n\t\t\tbetterL = newL;\n\t\t\t// Only update the resulting color when the target is met, this ensuring\n\t\t\t// at the end of the search the target is always met.\n\t\t\tbestContrastFound = newContrast;\n\t\t\tresultingColor = newColor;\n\t\t} else {\n\t\t\tworseL = newL;\n\t\t}\n\t}\n\n\treturn {\n\t\tcolor: resultingColor,\n\t\treached: true,\n\t\tachieved: bestContrastFound,\n\t};\n}\n"],
5
- "mappings": "AAGA,OAAO,WAAW;AAKlB,SAAS,oBAAoB;AAC7B;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,yBAAyB;AAClC,SAAkC,mBAAmB;AAoB9C,SAAS,6BACf,WACA,MACA,QACA,WACA;AAAA,EACC;AAAA,EACA;AAAA,EACA,SAAS;AAAA,EACT,QAAQ;AACT,IAQI,CAAC,GACkD;AAGvD,MAAK,UAAU,GAAI;AAClB,WAAO,EAAE,OAAO,KAAK,MAAM,GAAG,SAAS,MAAM,UAAU,EAAE;AAAA,EAC1D;AAEA,MAAK,qBAAsB;AAI1B,QAAI,OAAO,oBAAoB;AAC/B,QAAI,OAAO,KAAK,MAAM;AAEtB,QAAK,oBAAqB;AACzB,OAAE,EAAE,GAAG,MAAM,GAAG,KAAK,IAAI;AAAA,QACxB;AAAA,QACA;AAAA,QACA;AAAA,MACD;AAAA,IACD;AAEA,UAAM,kBAAkB;AAAA,MACvB,IAAI,MAAO,SAAS,CAAE,MAAM,MAAM,KAAK,MAAM,CAAE,CAAE;AAAA,IAClD;AACA,UAAM,iBAAiB,kBAAmB,WAAW,eAAgB;AAErE,QAAK,OAAQ;AAEZ,cAAQ;AAAA,QACP,kBAAmB,oBAAoB,IAAK;AAAA,QAC5C,oBAAoB;AAAA,QACpB,gBAAgB,MAAM;AAAA,MACvB;AAAA,IACD;AAIA,QACC,oBAAoB,SAAS,WAC7B,kBAAkB,QACjB;AACD,aAAO;AAAA,QACN,OAAO;AAAA,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O;AAAA,IACP,SAAS;AAAA,IACT,UAAU;AAAA,EACX;AACD;",
4
+ "sourcesContent": ["/**\n * External dependencies\n */\nimport { get, OKLCH, type ColorTypes } from 'colorjs.io/fn';\n\n/**\n * Internal dependencies\n */\nimport './register-color-spaces';\nimport { clampToGamut, solveWithBisect } from './utils';\nimport { WHITE, BLACK, CONTRAST_EPSILON } from './constants';\nimport { getContrast } from './color-utils';\nimport { type TaperChromaOptions, taperChroma } from './taper-chroma';\n\n/**\n * Difference of contrast values that grows linearly with the Y luminance.\n * We get more precise linear interpolations when we use this.\n * @param c1 First contrast.\n * @param c2 Second contrast.\n * @return Difference of logarithms.\n */\nfunction cdiff( c1: number, c2: number ) {\n\treturn Math.log( c1 / c2 );\n}\n\n/**\n * Solve for L such that:\n * - the L applied to the seed meets the contrast target against the reference\n * - the search is performed in one direction (ie lighter / darker)\n * - more constraints can be applied around lightness\n * - chroma could be tapered\n * @param reference\n * @param seed\n * @param target\n * @param direction\n * @param options\n * @param options.lightnessConstraint\n * @param options.lightnessConstraint.type\n * @param options.lightnessConstraint.value\n * @param options.taperChromaOptions\n */\nexport function findColorMeetingRequirements(\n\treference: ColorTypes,\n\tseed: ColorTypes,\n\ttarget: number,\n\tdirection: 'lighter' | 'darker',\n\t{\n\t\tlightnessConstraint,\n\t\ttaperChromaOptions,\n\t}: {\n\t\tlightnessConstraint?: {\n\t\t\ttype: 'force' | 'onlyIfSucceeds';\n\t\t\tvalue: number;\n\t\t};\n\t\ttaperChromaOptions?: TaperChromaOptions;\n\t} = {}\n): { color: ColorTypes; reached: boolean; achieved: number; deficit?: number } {\n\t// A target of 1 means same color.\n\t// A target lower than 1 doesn't make sense.\n\tif ( target <= 1 ) {\n\t\treturn {\n\t\t\tcolor: reference,\n\t\t\treached: true,\n\t\t\tachieved: 1,\n\t\t};\n\t}\n\n\tfunction getColorForL( l: number ): ColorTypes {\n\t\tlet newL = l;\n\t\tlet newC = get( seed, [ OKLCH, 'c' ] );\n\n\t\tif ( taperChromaOptions ) {\n\t\t\tconst tapered = taperChroma( seed, newL, taperChromaOptions );\n\t\t\t// taperChroma returns either { l, c } or a ColorObject\n\t\t\tif ( 'l' in tapered && 'c' in tapered ) {\n\t\t\t\tnewL = tapered.l;\n\t\t\t\tnewC = tapered.c;\n\t\t\t} else {\n\t\t\t\t// It's already a ColorObject, return it directly\n\t\t\t\treturn tapered;\n\t\t\t}\n\t\t}\n\n\t\treturn clampToGamut( {\n\t\t\tspaceId: 'oklch',\n\t\t\tcoords: [ newL, newC, get( seed, [ OKLCH, 'h' ] ) ],\n\t\t} );\n\t}\n\n\t// Set the boundary based on the direction.\n\tconst mostContrastingL = direction === 'lighter' ? 1 : 0;\n\tconst mostContrastingColor = direction === 'lighter' ? WHITE : BLACK;\n\tconst highestContrast = getContrast( reference, mostContrastingColor );\n\n\tif ( lightnessConstraint ) {\n\t\t// Apply a specific L value.\n\t\t// Useful when pinning a step to a specific lightness, of to specify\n\t\t// min/max L values.\n\t\tconst colorWithExactL = getColorForL( lightnessConstraint.value );\n\t\tconst exactLContrast = getContrast( reference, colorWithExactL );\n\t\tconst exactLContrastMeetsTarget =\n\t\t\tcdiff( exactLContrast, target ) >= -CONTRAST_EPSILON;\n\n\t\t// If the L constraint is of \"force\" type, apply it even when it doesn't\n\t\t// meet the contrast target.\n\t\tif (\n\t\t\texactLContrastMeetsTarget ||\n\t\t\tlightnessConstraint.type === 'force'\n\t\t) {\n\t\t\treturn {\n\t\t\t\tcolor: colorWithExactL,\n\t\t\t\treached: exactLContrastMeetsTarget,\n\t\t\t\tachieved: exactLContrast,\n\t\t\t\tdeficit: exactLContrastMeetsTarget\n\t\t\t\t\t? cdiff( exactLContrast, highestContrast )\n\t\t\t\t\t: cdiff( target, exactLContrast ),\n\t\t\t};\n\t\t}\n\t}\n\n\t// If even the most contrasting color can't reach the target, the target is unreachable.\n\t// On the other hand, if the contrast is very close to the target, we consider it reached.\n\tif ( cdiff( highestContrast, target ) <= CONTRAST_EPSILON ) {\n\t\treturn {\n\t\t\tcolor: mostContrastingColor,\n\t\t\treached: cdiff( highestContrast, target ) >= -CONTRAST_EPSILON,\n\t\t\tachieved: highestContrast,\n\t\t\tdeficit: cdiff( target, highestContrast ),\n\t\t};\n\t}\n\n\t// Bracket: low fails, high meets.\n\t// Originally this was seed.oklch.l \u2014 although it's an assumption that works\n\t// only when we know for sure the direction of the search.\n\t// TODO: can we bring this back to seed.oklch.l ?\n\tconst lowerL = get( reference, [ OKLCH, 'l' ] );\n\tconst lowerContrast = cdiff( 1, target );\n\tconst upperL = mostContrastingL;\n\tconst upperContrast = cdiff( highestContrast, target );\n\n\tconst bestColor = solveWithBisect(\n\t\tgetColorForL,\n\t\t( c: ColorTypes ) => cdiff( getContrast( reference, c ), target ),\n\t\tlowerL,\n\t\tlowerContrast,\n\t\tupperL,\n\t\tupperContrast\n\t);\n\n\treturn {\n\t\tcolor: bestColor,\n\t\treached: true,\n\t\tachieved: target,\n\t\t// Negative number that specifies how much room we have.\n\t\tdeficit: cdiff( target, highestContrast ),\n\t};\n}\n"],
5
+ "mappings": ";AAGA,SAAS,KAAK,aAA8B;AAK5C,OAAO;AACP,SAAS,cAAc,uBAAuB;AAC9C,SAAS,OAAO,OAAO,wBAAwB;AAC/C,SAAS,mBAAmB;AAC5B,SAAkC,mBAAmB;AASrD,SAAS,MAAO,IAAY,IAAa;AACxC,SAAO,KAAK,IAAK,KAAK,EAAG;AAC1B;AAkBO,SAAS,6BACf,WACA,MACA,QACA,WACA;AAAA,EACC;AAAA,EACA;AACD,IAMI,CAAC,GACyE;AAG9E,MAAK,UAAU,GAAI;AAClB,WAAO;AAAA,MACN,OAAO;AAAA,MACP,SAAS;AAAA,MACT,UAAU;AAAA,IACX;AAAA,EACD;AAEA,WAAS,aAAc,GAAwB;AAC9C,QAAI,OAAO;AACX,QAAI,OAAO,IAAK,MAAM,CAAE,OAAO,GAAI,CAAE;AAErC,QAAK,oBAAqB;AACzB,YAAM,UAAU,YAAa,MAAM,MAAM,kB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ACA;AAAA,IACA;AAAA,EACD;AAEA,SAAO;AAAA,IACN,OAAO;AAAA,IACP,SAAS;AAAA,IACT,UAAU;AAAA;AAAA,IAEV,SAAS,MAAO,QAAQ,eAAgB;AAAA,EACzC;AACD;",
6
6
  "names": []
7
7
  }
@@ -1,30 +1,39 @@
1
- import Color from "colorjs.io";
2
- import { getCachedContrast, getColorString } from "./cache-utils";
1
+ // packages/theme/src/color-ramps/lib/index.ts
2
+ import {
3
+ clone,
4
+ get,
5
+ OKLCH,
6
+ parse,
7
+ set
8
+ } from "colorjs.io/fn";
9
+ import "./register-color-spaces";
10
+ import { getContrast, getColorString } from "./color-utils";
3
11
  import { findColorMeetingRequirements } from "./find-color-with-constraints";
4
12
  import {
5
13
  clampToGamut,
6
14
  sortByDependency,
7
15
  computeBetterFgColorDirection,
8
- adjustContrastTarget
16
+ adjustContrastTarget,
17
+ stepsForStep,
18
+ solveWithBisect
9
19
  } from "./utils";
10
- import { LIGHTNESS_EPSILON, MAX_BISECTION_ITERATIONS } from "./constants";
20
+ import { CONTRAST_EPSILON } from "./constants";
11
21
  function calculateRamp({
12
22
  seed,
13
23
  sortedSteps,
14
24
  config,
15
25
  mainDir,
16
26
  oppDir,
17
- pinLightness,
18
- debug = false
27
+ pinLightness
19
28
  }) {
20
29
  const rampResults = {};
21
- let SATISFIED_ALL_CONTRAST_REQUIREMENTS = true;
22
- let UNSATISFIED_DIRECTION = "lighter";
23
- let MAX_WEIGHTED_DEFICIT = 0;
30
+ let maxDeficit = -Infinity;
31
+ let maxDeficitDirection = "lighter";
32
+ let maxDeficitStep;
24
33
  const calculatedColors = /* @__PURE__ */ new Map();
25
34
  calculatedColors.set("seed", seed);
26
35
  for (const stepName of sortedSteps) {
27
- let computeDirection2 = function(color, followDirection) {
36
+ let computeDirection = function(color, followDirection) {
28
37
  if (followDirection === "main") {
29
38
  return mainDir;
30
39
  }
@@ -39,7 +48,6 @@ function calculateRamp({
39
48
  }
40
49
  return followDirection;
41
50
  };
42
- var computeDirection = computeDirection2;
43
51
  const {
44
52
  contrast,
45
53
  lightness: stepLightnessConstraint,
@@ -54,23 +62,26 @@ function calculateRamp({
54
62
  }
55
63
  if (sameAsIfPossible) {
56
64
  const candidateColor = calculatedColors.get(sameAsIfPossible);
57
- if (candidateColor) {
58
- const candidateContrast = getCachedContrast(
59
- referenceColor,
60
- candidateColor
65
+ if (!candidateColor) {
66
+ throw new Error(
67
+ `Same-as color for step ${stepName} not found: ${sameAsIfPossible}`
61
68
  );
62
- const adjustedTarget2 = adjustContrastTarget(contrast.target);
63
- if (candidateContrast >= adjustedTarget2) {
64
- calculatedColors.set(stepName, candidateColor);
65
- rampResults[stepName] = {
66
- color: getColorString(candidateColor),
67
- warning: false
68
- };
69
- continue;
70
- }
69
+ }
70
+ const candidateContrast = getContrast(
71
+ referenceColor,
72
+ candidateColor
73
+ );
74
+ const adjustedTarget2 = adjustContrastTarget(contrast.target);
75
+ if (candidateContrast >= adjustedTarget2) {
76
+ calculatedColors.set(stepName, candidateColor);
77
+ rampResults[stepName] = {
78
+ color: getColorString(candidateColor),
79
+ warning: false
80
+ };
81
+ continue;
71
82
  }
72
83
  }
73
- const computedDir = computeDirection2(
84
+ const computedDir = computeDirection(
74
85
  referenceColor,
75
86
  contrast.followDirection
76
87
  );
@@ -93,21 +104,14 @@ function calculateRamp({
93
104
  adjustedTarget,
94
105
  computedDir,
95
106
  {
96
- strict: false,
97
107
  lightnessConstraint,
98
- taperChromaOptions,
99
- debug
108
+ taperChromaOptions
100
109
  }
101
110
  );
102
- if (!searchResults.reached && !contrast.ignoreWhenAdjustingSeed) {
103
- SATISFIED_ALL_CONTRAST_REQUIREMENTS = false;
104
- const deficitVsTarget = adjustedTarget - searchResults.achieved;
105
- const impactWeight = 1 / getCachedContrast(seed, referenceColor);
106
- const weightedDeficit = deficitVsTarget * impactWeight;
107
- if (weightedDeficit > MAX_WEIGHTED_DEFICIT) {
108
- MAX_WEIGHTED_DEFICIT = weightedDeficit;
109
- UNSATISFIED_DIRECTION = computedDir;
110
- }
111
+ if (!contrast.ignoreWhenAdjustingSeed && searchResults.deficit && searchResults.deficit > maxDeficit) {
112
+ maxDeficit = searchResults.deficit;
113
+ maxDeficitDirection = computedDir;
114
+ maxDeficitStep = stepName;
111
115
  }
112
116
  calculatedColors.set(stepName, searchResults.color);
113
117
  rampResults[stepName] = {
@@ -117,19 +121,19 @@ function calculateRamp({
117
121
  }
118
122
  return {
119
123
  rampResults,
120
- SATISFIED_ALL_CONTRAST_REQUIREMENTS,
121
- UNSATISFIED_DIRECTION
124
+ maxDeficit,
125
+ maxDeficitDirection,
126
+ maxDeficitStep
122
127
  };
123
128
  }
124
129
  function buildRamp(seedArg, config, {
125
130
  mainDirection,
126
131
  pinLightness,
127
- debug = false,
128
132
  rescaleToFitContrastTargets = true
129
133
  } = {}) {
130
134
  let seed;
131
135
  try {
132
- seed = clampToGamut(new Color(seedArg));
136
+ seed = clampToGamut(parse(seedArg));
133
137
  } catch (error) {
134
138
  throw new Error(
135
139
  `Invalid seed color "${seedArg}": ${error instanceof Error ? error.message : "Unknown error"}`
@@ -146,88 +150,60 @@ function buildRamp(seedArg, config, {
146
150
  oppDir = worse;
147
151
  }
148
152
  const sortedSteps = sortByDependency(config);
149
- const {
150
- rampResults,
151
- SATISFIED_ALL_CONTRAST_REQUIREMENTS,
152
- UNSATISFIED_DIRECTION
153
- } = calculateRamp({
153
+ const { rampResults, maxDeficit, maxDeficitDirection, maxDeficitStep } = calculateRamp({
154
154
  seed,
155
155
  sortedSteps,
156
156
  config,
157
157
  mainDir,
158
158
  oppDir,
159
- pinLightness,
160
- debug
159
+ pinLightness
161
160
  });
162
- const toReturn = {
163
- ramp: rampResults,
164
- direction: mainDir
165
- };
166
- if (debug) {
167
- console.log(`First run`, {
168
- SATISFIED_ALL_CONTRAST_REQUIREMENTS,
169
- UNSATISFIED_DIRECTION,
170
- seed: seed.toString(),
171
- sortedSteps,
172
- config,
173
- mainDir,
174
- oppDir,
175
- pinLightness
176
- });
177
- }
178
- if (!SATISFIED_ALL_CONTRAST_REQUIREMENTS && rescaleToFitContrastTargets) {
179
- let worseSeedL = seed.oklch.l;
180
- let betterSeedL = UNSATISFIED_DIRECTION === "lighter" ? 0 : 1;
181
- for (let i = 0; i < MAX_BISECTION_ITERATIONS && Math.abs(betterSeedL - worseSeedL) > LIGHTNESS_EPSILON; i++) {
182
- const newSeed = clampToGamut(
183
- seed.clone().set({
184
- l: (worseSeedL + betterSeedL) / 2
185
- })
186
- );
187
- if (debug) {
188
- console.log(`Iteration ${i}`, {
189
- worseSeedL,
190
- newSeedL: (worseSeedL + betterSeedL) / 2,
191
- betterSeedL
192
- });
193
- }
161
+ let bestRamp = rampResults;
162
+ if (maxDeficit > CONTRAST_EPSILON && rescaleToFitContrastTargets) {
163
+ let getSeedForL = function(l) {
164
+ return clampToGamut(set(clone(seed), [OKLCH, "l"], l));
165
+ }, getDeficitForSeed = function(s) {
194
166
  const iterationResults = calculateRamp({
195
- seed: newSeed,
196
- sortedSteps,
167
+ seed: s,
168
+ sortedSteps: iterSteps,
197
169
  config,
198
170
  mainDir,
199
171
  oppDir,
200
- pinLightness,
201
- debug
172
+ pinLightness
202
173
  });
203
- if (iterationResults.SATISFIED_ALL_CONTRAST_REQUIREMENTS) {
204
- betterSeedL = newSeed.oklch.l;
205
- toReturn.ramp = iterationResults.rampResults;
206
- } else if (UNSATISFIED_DIRECTION !== mainDir) {
207
- betterSeedL = newSeed.oklch.l;
208
- } else {
209
- worseSeedL = newSeed.oklch.l;
210
- }
211
- if (debug) {
212
- console.log(`Retry #${i}`, {
213
- SATISFIED_ALL_CONTRAST_REQUIREMENTS,
214
- UNSATISFIED_DIRECTION,
215
- seed: newSeed.toString(),
216
- sortedSteps,
217
- config,
218
- mainDir,
219
- oppDir,
220
- pinLightness
221
- });
222
- }
223
- }
174
+ return iterationResults.maxDeficitDirection === maxDeficitDirection ? iterationResults.maxDeficit : -maxDeficit;
175
+ };
176
+ const iterSteps = stepsForStep(maxDeficitStep, config);
177
+ const lowerSeedL = maxDeficitDirection === "lighter" ? 0 : 1;
178
+ const lowerDeficit = -maxDeficit;
179
+ const upperSeedL = get(seed, [OKLCH, "l"]);
180
+ const upperDeficit = maxDeficit;
181
+ const bestSeed = solveWithBisect(
182
+ getSeedForL,
183
+ getDeficitForSeed,
184
+ lowerSeedL,
185
+ lowerDeficit,
186
+ upperSeedL,
187
+ upperDeficit
188
+ );
189
+ bestRamp = calculateRamp({
190
+ seed: bestSeed,
191
+ sortedSteps,
192
+ config,
193
+ mainDir,
194
+ oppDir,
195
+ pinLightness
196
+ }).rampResults;
224
197
  }
225
198
  if (mainDir === "darker") {
226
- const tmpSurface1 = toReturn.ramp.surface1;
227
- toReturn.ramp.surface1 = toReturn.ramp.surface3;
228
- toReturn.ramp.surface3 = tmpSurface1;
199
+ const tmpSurface1 = bestRamp.surface1;
200
+ bestRamp.surface1 = bestRamp.surface3;
201
+ bestRamp.surface3 = tmpSurface1;
229
202
  }
230
- return toReturn;
203
+ return {
204
+ ramp: bestRamp,
205
+ direction: mainDir
206
+ };
231
207
  }
232
208
  export {
233
209
  buildRamp
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/color-ramps/lib/index.ts"],
4
- "sourcesContent": ["/**\n * External dependencies\n */\nimport Color from 'colorjs.io';\n\n/**\n * Internal dependencies\n */\nimport { getCachedContrast, getColorString } from './cache-utils';\nimport { findColorMeetingRequirements } from './find-color-with-constraints';\nimport {\n\tclampToGamut,\n\tsortByDependency,\n\tcomputeBetterFgColorDirection,\n\tadjustContrastTarget,\n} from './utils';\n\nimport type {\n\tFollowDirection,\n\tRamp,\n\tRampDirection,\n\tRampConfig,\n\tRampResult,\n} from './types';\nimport { LIGHTNESS_EPSILON, MAX_BISECTION_ITERATIONS } from './constants';\n\n/**\n * Calculate a complete color ramp based on the provided configuration.\n *\n * @param params - The calculation parameters\n * @param params.seed - The base color to build the ramp from\n * @param params.sortedSteps - Steps sorted in dependency order\n * @param params.config - Ramp configuration defining contrast requirements\n * @param params.mainDir - Primary direction for the ramp (lighter/darker)\n * @param params.oppDir - Opposite direction from mainDir\n * @param params.pinLightness - Optional lightness override for a given step\n * @param params.pinLightness.stepName\n * @param params.pinLightness.value\n * @param params.debug\n * @return Object containing ramp results and satisfaction status\n */\nfunction calculateRamp( {\n\tseed,\n\tsortedSteps,\n\tconfig,\n\tmainDir,\n\toppDir,\n\tpinLightness,\n\tdebug = false,\n}: {\n\tseed: Color;\n\tsortedSteps: ( keyof Ramp )[];\n\tconfig: RampConfig;\n\tmainDir: RampDirection;\n\toppDir: RampDirection;\n\tpinLightness?: {\n\t\tstepName: keyof Ramp;\n\t\tvalue: number;\n\t};\n\tdebug?: boolean;\n} ) {\n\tconst rampResults = {} as Record<\n\t\tkeyof Ramp,\n\t\t{ color: string; warning: boolean }\n\t>;\n\tlet SATISFIED_ALL_CONTRAST_REQUIREMENTS = true;\n\tlet UNSATISFIED_DIRECTION: RampDirection = 'lighter';\n\tlet MAX_WEIGHTED_DEFICIT = 0;\n\n\t// Keep track of the calculated colors, as they are going to be useful\n\t// when other colors reference them.\n\tconst calculatedColors = new Map< keyof Ramp | 'seed', Color >();\n\tcalculatedColors.set( 'seed', seed );\n\n\tfor ( const stepName of sortedSteps ) {\n\t\tconst {\n\t\t\tcontrast,\n\t\t\tlightness: stepLightnessConstraint,\n\t\t\ttaperChromaOptions,\n\t\t\tsameAsIfPossible,\n\t\t} = config[ stepName ];\n\t\tconst referenceColor = calculatedColors.get( contrast.reference );\n\n\t\tif ( ! referenceColor ) {\n\t\t\tthrow new Error(\n\t\t\t\t`Reference color for step ${ stepName } not found: ${ contrast.reference }`\n\t\t\t);\n\t\t}\n\n\t\t// Check if we can reuse color from the `sameAsIfPossible` config option\n\t\tif ( sameAsIfPossible ) {\n\t\t\tconst candidateColor = calculatedColors.get( sameAsIfPossible );\n\t\t\tif ( candidateColor ) {\n\t\t\t\tconst candidateContrast = getCachedContrast(\n\t\t\t\t\treferenceColor,\n\t\t\t\t\tcandidateColor\n\t\t\t\t);\n\t\t\t\tconst adjustedTarget = adjustContrastTarget( contrast.target );\n\t\t\t\t// If the candidate meets the contrast requirement, use it\n\t\t\t\tif ( candidateContrast >= adjustedTarget ) {\n\t\t\t\t\t// Store the reused color\n\t\t\t\t\tcalculatedColors.set( stepName, candidateColor );\n\t\t\t\t\trampResults[ stepName ] = {\n\t\t\t\t\t\tcolor: getColorString( candidateColor ),\n\t\t\t\t\t\twarning: false,\n\t\t\t\t\t};\n\n\t\t\t\t\tcontinue; // Skip to next step\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfunction computeDirection(\n\t\t\tcolor: Color,\n\t\t\tfollowDirection: FollowDirection\n\t\t): RampDirection {\n\t\t\tif ( followDirection === 'main' ) {\n\t\t\t\treturn mainDir;\n\t\t\t}\n\n\t\t\tif ( followDirection === 'opposite' ) {\n\t\t\t\treturn oppDir;\n\t\t\t}\n\n\t\t\tif ( followDirection === 'best' ) {\n\t\t\t\treturn computeBetterFgColorDirection(\n\t\t\t\t\tcolor,\n\t\t\t\t\tcontrast.preferLighter\n\t\t\t\t).better;\n\t\t\t}\n\n\t\t\treturn followDirection;\n\t\t}\n\n\t\tconst computedDir = computeDirection(\n\t\t\treferenceColor,\n\t\t\tcontrast.followDirection\n\t\t);\n\n\t\tconst adjustedTarget = adjustContrastTarget( contrast.target );\n\n\t\t// Define the lightness constraint, if needed.\n\t\tlet lightnessConstraint;\n\t\tif ( pinLightness?.stepName === stepName ) {\n\t\t\tlightnessConstraint = {\n\t\t\t\tvalue: pinLightness.value,\n\t\t\t\ttype: 'force',\n\t\t\t} as const;\n\t\t} else if ( stepLightnessConstraint ) {\n\t\t\tlightnessConstraint = {\n\t\t\t\tvalue: stepLightnessConstraint( computedDir ),\n\t\t\t\ttype: 'onlyIfSucceeds',\n\t\t\t} as const;\n\t\t}\n\n\t\t// Calculate the color meeting the requirements\n\t\tconst searchResults = findColorMeetingRequirements(\n\t\t\treferenceColor,\n\t\t\tseed,\n\t\t\tadjustedTarget,\n\t\t\tcomputedDir,\n\t\t\t{\n\t\t\t\tstrict: false,\n\t\t\t\tlightnessConstraint,\n\t\t\t\ttaperChromaOptions,\n\t\t\t\tdebug,\n\t\t\t}\n\t\t);\n\n\t\t// When the target contrast is not met, take note of it and use\n\t\t// that information to guide the ramp calculation bisection.\n\t\tif ( ! searchResults.reached && ! contrast.ignoreWhenAdjustingSeed ) {\n\t\t\tSATISFIED_ALL_CONTRAST_REQUIREMENTS = false;\n\n\t\t\t// Calculate constraint failure severity for seed optimization\n\t\t\t// Use the relative deficit size, weighted by how changing the seed would impact this constraint\n\t\t\tconst deficitVsTarget = adjustedTarget - searchResults.achieved;\n\n\t\t\t// Weight the deficit by how much seed adjustment would help this constraint\n\t\t\t// If seed has low contrast vs reference, adjusting seed has high impact\n\t\t\t// If seed has high contrast vs reference, adjusting seed has low impact\n\t\t\tconst impactWeight = 1 / getCachedContrast( seed, referenceColor );\n\t\t\tconst weightedDeficit = deficitVsTarget * impactWeight;\n\n\t\t\t// Track the most impactful failure for seed optimization\n\t\t\tif ( weightedDeficit > MAX_WEIGHTED_DEFICIT ) {\n\t\t\t\tMAX_WEIGHTED_DEFICIT = weightedDeficit;\n\t\t\t\tUNSATISFIED_DIRECTION = computedDir;\n\t\t\t}\n\t\t}\n\n\t\t// Store calculated color for future dependencies\n\t\tcalculatedColors.set( stepName, searchResults.color );\n\n\t\t// Add to results\n\t\trampResults[ stepName ] = {\n\t\t\tcolor: getColorString( searchResults.color ),\n\t\t\twarning:\n\t\t\t\t! contrast.ignoreWhenAdjustingSeed && ! searchResults.reached,\n\t\t};\n\t}\n\n\treturn {\n\t\trampResults,\n\t\tSATISFIED_ALL_CONTRAST_REQUIREMENTS,\n\t\tUNSATISFIED_DIRECTION,\n\t};\n}\n\nexport function buildRamp(\n\tseedArg: string,\n\tconfig: RampConfig,\n\t{\n\t\tmainDirection,\n\t\tpinLightness,\n\t\tdebug = false,\n\t\trescaleToFitContrastTargets = true,\n\t}: {\n\t\tmainDirection?: RampDirection;\n\t\tpinLightness?: {\n\t\t\tstepName: keyof Ramp;\n\t\t\tvalue: number;\n\t\t};\n\t\trescaleToFitContrastTargets?: boolean;\n\t\tdebug?: boolean;\n\t} = {}\n): RampResult {\n\tlet seed: Color;\n\ttry {\n\t\tseed = clampToGamut( new Color( seedArg ) );\n\t} catch ( error ) {\n\t\tthrow new Error(\n\t\t\t`Invalid seed color \"${ seedArg }\": ${\n\t\t\t\terror instanceof Error ? error.message : 'Unknown error'\n\t\t\t}`\n\t\t);\n\t}\n\n\tlet mainDir: RampDirection = 'lighter';\n\tlet oppDir: RampDirection = 'darker';\n\n\tif ( mainDirection ) {\n\t\tmainDir = mainDirection;\n\t\toppDir = mainDirection === 'darker' ? 'lighter' : 'darker';\n\t} else {\n\t\tconst { better, worse } = computeBetterFgColorDirection( seed );\n\t\tmainDir = better;\n\t\toppDir = worse;\n\t}\n\n\t// Get the correct calculation order based on dependencies\n\tconst sortedSteps = sortByDependency( config );\n\n\t// Calculate the ramp with the initial seed.\n\tconst {\n\t\trampResults,\n\t\tSATISFIED_ALL_CONTRAST_REQUIREMENTS,\n\t\tUNSATISFIED_DIRECTION,\n\t} = calculateRamp( {\n\t\tseed,\n\t\tsortedSteps,\n\t\tconfig,\n\t\tmainDir,\n\t\toppDir,\n\t\tpinLightness,\n\t\tdebug,\n\t} );\n\tconst toReturn = {\n\t\tramp: rampResults,\n\t\tdirection: mainDir,\n\t} as RampResult;\n\n\tif ( debug ) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.log( `First run`, {\n\t\t\tSATISFIED_ALL_CONTRAST_REQUIREMENTS,\n\t\t\tUNSATISFIED_DIRECTION,\n\t\t\tseed: seed.toString(),\n\t\t\tsortedSteps,\n\t\t\tconfig,\n\t\t\tmainDir,\n\t\t\toppDir,\n\t\t\tpinLightness,\n\t\t} );\n\t}\n\n\tif (\n\t\t! SATISFIED_ALL_CONTRAST_REQUIREMENTS &&\n\t\trescaleToFitContrastTargets\n\t) {\n\t\tlet worseSeedL = seed.oklch.l;\n\t\t// For a scale with the \"lighter\" direction, the contrast can be improved\n\t\t// by darkening the seed. For \"darker\" direction, by lightening the seed.\n\t\tlet betterSeedL = UNSATISFIED_DIRECTION === 'lighter' ? 0 : 1;\n\n\t\t// Binary search: try a new seed and recompute the whole ramp\n\t\t// (TODO: try a smarter approach?)\n\t\tfor (\n\t\t\tlet i = 0;\n\t\t\ti < MAX_BISECTION_ITERATIONS &&\n\t\t\tMath.abs( betterSeedL - worseSeedL ) > LIGHTNESS_EPSILON;\n\t\t\ti++\n\t\t) {\n\t\t\tconst newSeed = clampToGamut(\n\t\t\t\tseed.clone().set( {\n\t\t\t\t\tl: ( worseSeedL + betterSeedL ) / 2,\n\t\t\t\t} )\n\t\t\t);\n\n\t\t\tif ( debug ) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.log( `Iteration ${ i }`, {\n\t\t\t\t\tworseSeedL,\n\t\t\t\t\tnewSeedL: ( worseSeedL + betterSeedL ) / 2,\n\t\t\t\t\tbetterSeedL,\n\t\t\t\t} );\n\t\t\t}\n\n\t\t\tconst iterationResults = calculateRamp( {\n\t\t\t\tseed: newSeed,\n\t\t\t\tsortedSteps,\n\t\t\t\tconfig,\n\t\t\t\tmainDir,\n\t\t\t\toppDir,\n\t\t\t\tpinLightness,\n\t\t\t\tdebug,\n\t\t\t} );\n\n\t\t\tif ( iterationResults.SATISFIED_ALL_CONTRAST_REQUIREMENTS ) {\n\t\t\t\tbetterSeedL = newSeed.oklch.l;\n\t\t\t\t// Only update toReturn when the ramp satisfies all constraints.\n\t\t\t\ttoReturn.ramp = iterationResults.rampResults;\n\t\t\t} else if ( UNSATISFIED_DIRECTION !== mainDir ) {\n\t\t\t\t// Failing constraint is in opposite direction to main ramp direction\n\t\t\t\t// We've moved too far in mainDir, constrain the search\n\t\t\t\tbetterSeedL = newSeed.oklch.l;\n\t\t\t} else {\n\t\t\t\t// Failing constraint is in same direction as main ramp direction\n\t\t\t\t// We haven't moved far enough in mainDir, continue searching\n\t\t\t\tworseSeedL = newSeed.oklch.l;\n\t\t\t}\n\n\t\t\tif ( debug ) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.log( `Retry #${ i }`, {\n\t\t\t\t\tSATISFIED_ALL_CONTRAST_REQUIREMENTS,\n\t\t\t\t\tUNSATISFIED_DIRECTION,\n\t\t\t\t\tseed: newSeed.toString(),\n\t\t\t\t\tsortedSteps,\n\t\t\t\t\tconfig,\n\t\t\t\t\tmainDir,\n\t\t\t\t\toppDir,\n\t\t\t\t\tpinLightness,\n\t\t\t\t} );\n\t\t\t}\n\t\t}\n\t}\n\n\t// Swap surface1 and surface3 for darker ramps to maintain visual elevation hierarchy.\n\t// This ensures surface1 appears \"behind\" surface2, and surface3 appears \"in front\",\n\t// regardless of the ramp's main direction.\n\tif ( mainDir === 'darker' ) {\n\t\tconst tmpSurface1 = toReturn.ramp.surface1;\n\t\ttoReturn.ramp.surface1 = toReturn.ramp.surface3;\n\t\ttoReturn.ramp.surface3 = tmpSurface1;\n\t}\n\n\treturn toReturn;\n}\n"],
5
- "mappings": "AAGA,OAAO,WAAW;AAKlB,SAAS,mBAAmB,sBAAsB;AAClD,SAAS,oCAAoC;AAC7C;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AASP,SAAS,mBAAmB,gCAAgC;AAiB5D,SAAS,cAAe;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ;AACT,GAWI;AACH,QAAM,cAAc,CAAC;AAIrB,MAAI,sCAAsC;AAC1C,MAAI,wBAAuC;AAC3C,MAAI,uBAAuB;AAI3B,QAAM,mBAAmB,oBAAI,IAAkC;AAC/D,mBAAiB,IAAK,QAAQ,IAAK;AAEnC,aAAY,YAAY,aAAc;AAsCrC,QAASA,oBAAT,SACC,O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AA,UACA;AAAA,UACA;AAAA,QACD,CAAE;AAAA,MACH;AAAA,IACD;AAAA,EACD;AAKA,MAAK,YAAY,UAAW;AAC3B,UAAM,cAAc,SAAS,KAAK;AAClC,aAAS,KAAK,WAAW,SAAS,KAAK;AACvC,aAAS,KAAK,WAAW;AAAA,EAC1B;AAEA,SAAO;AACR;",
6
- "names": ["computeDirection", "adjustedTarget"]
4
+ "sourcesContent": ["/**\n * External dependencies\n */\nimport {\n\tclone,\n\tget,\n\tOKLCH,\n\tparse,\n\tset,\n\ttype ColorTypes,\n\ttype PlainColorObject,\n} from 'colorjs.io/fn';\n\n/**\n * Internal dependencies\n */\nimport './register-color-spaces';\nimport { getContrast, getColorString } from './color-utils';\nimport { findColorMeetingRequirements } from './find-color-with-constraints';\nimport {\n\tclampToGamut,\n\tsortByDependency,\n\tcomputeBetterFgColorDirection,\n\tadjustContrastTarget,\n\tstepsForStep,\n\tsolveWithBisect,\n} from './utils';\n\nimport type {\n\tFollowDirection,\n\tRamp,\n\tRampDirection,\n\tRampConfig,\n\tRampResult,\n} from './types';\nimport { CONTRAST_EPSILON } from './constants';\n\n/**\n * Calculate a complete color ramp based on the provided configuration.\n *\n * @param params - The calculation parameters\n * @param params.seed - The base color to build the ramp from\n * @param params.sortedSteps - Steps sorted in dependency order\n * @param params.config - Ramp configuration defining contrast requirements\n * @param params.mainDir - Primary direction for the ramp (lighter/darker)\n * @param params.oppDir - Opposite direction from mainDir\n * @param params.pinLightness - Optional lightness override for a given step\n * @param params.pinLightness.stepName\n * @param params.pinLightness.value\n * @return Object containing ramp results and satisfaction status\n */\nfunction calculateRamp( {\n\tseed,\n\tsortedSteps,\n\tconfig,\n\tmainDir,\n\toppDir,\n\tpinLightness,\n}: {\n\tseed: ColorTypes;\n\tsortedSteps: ( keyof Ramp )[];\n\tconfig: RampConfig;\n\tmainDir: RampDirection;\n\toppDir: RampDirection;\n\tpinLightness?: {\n\t\tstepName: keyof Ramp;\n\t\tvalue: number;\n\t};\n} ) {\n\tconst rampResults = {} as Record<\n\t\tkeyof Ramp,\n\t\t{ color: string; warning: boolean }\n\t>;\n\tlet maxDeficit = -Infinity;\n\tlet maxDeficitDirection: RampDirection = 'lighter';\n\tlet maxDeficitStep;\n\n\t// Keep track of the calculated colors, as they are going to be useful\n\t// when other colors reference them.\n\tconst calculatedColors = new Map< keyof Ramp | 'seed', ColorTypes >();\n\tcalculatedColors.set( 'seed', seed );\n\n\tfor ( const stepName of sortedSteps ) {\n\t\tconst {\n\t\t\tcontrast,\n\t\t\tlightness: stepLightnessConstraint,\n\t\t\ttaperChromaOptions,\n\t\t\tsameAsIfPossible,\n\t\t} = config[ stepName ];\n\n\t\tconst referenceColor = calculatedColors.get( contrast.reference );\n\t\tif ( ! referenceColor ) {\n\t\t\tthrow new Error(\n\t\t\t\t`Reference color for step ${ stepName } not found: ${ contrast.reference }`\n\t\t\t);\n\t\t}\n\n\t\t// Check if we can reuse color from the `sameAsIfPossible` config option\n\t\tif ( sameAsIfPossible ) {\n\t\t\tconst candidateColor = calculatedColors.get( sameAsIfPossible );\n\t\t\tif ( ! candidateColor ) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Same-as color for step ${ stepName } not found: ${ sameAsIfPossible }`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst candidateContrast = getContrast(\n\t\t\t\treferenceColor,\n\t\t\t\tcandidateColor\n\t\t\t);\n\t\t\tconst adjustedTarget = adjustContrastTarget( contrast.target );\n\t\t\t// If the candidate meets the contrast requirement, use it\n\t\t\tif ( candidateContrast >= adjustedTarget ) {\n\t\t\t\t// Store the reused color\n\t\t\t\tcalculatedColors.set( stepName, candidateColor );\n\t\t\t\trampResults[ stepName ] = {\n\t\t\t\t\tcolor: getColorString( candidateColor ),\n\t\t\t\t\twarning: false,\n\t\t\t\t};\n\n\t\t\t\tcontinue; // Skip to next step\n\t\t\t}\n\t\t}\n\n\t\tfunction computeDirection(\n\t\t\tcolor: ColorTypes,\n\t\t\tfollowDirection: FollowDirection\n\t\t): RampDirection {\n\t\t\tif ( followDirection === 'main' ) {\n\t\t\t\treturn mainDir;\n\t\t\t}\n\n\t\t\tif ( followDirection === 'opposite' ) {\n\t\t\t\treturn oppDir;\n\t\t\t}\n\n\t\t\tif ( followDirection === 'best' ) {\n\t\t\t\treturn computeBetterFgColorDirection(\n\t\t\t\t\tcolor,\n\t\t\t\t\tcontrast.preferLighter\n\t\t\t\t).better;\n\t\t\t}\n\n\t\t\treturn followDirection;\n\t\t}\n\n\t\tconst computedDir = computeDirection(\n\t\t\treferenceColor,\n\t\t\tcontrast.followDirection\n\t\t);\n\n\t\tconst adjustedTarget = adjustContrastTarget( contrast.target );\n\n\t\t// Define the lightness constraint, if needed.\n\t\tlet lightnessConstraint;\n\t\tif ( pinLightness?.stepName === stepName ) {\n\t\t\tlightnessConstraint = {\n\t\t\t\tvalue: pinLightness.value,\n\t\t\t\ttype: 'force',\n\t\t\t} as const;\n\t\t} else if ( stepLightnessConstraint ) {\n\t\t\tlightnessConstraint = {\n\t\t\t\tvalue: stepLightnessConstraint( computedDir ),\n\t\t\t\ttype: 'onlyIfSucceeds',\n\t\t\t} as const;\n\t\t}\n\n\t\t// Calculate the color meeting the requirements\n\t\tconst searchResults = findColorMeetingRequirements(\n\t\t\treferenceColor,\n\t\t\tseed,\n\t\t\tadjustedTarget,\n\t\t\tcomputedDir,\n\t\t\t{\n\t\t\t\tlightnessConstraint,\n\t\t\t\ttaperChromaOptions,\n\t\t\t}\n\t\t);\n\n\t\t// When the target contrast is not met, take note of it and use\n\t\t// that information to guide the ramp calculation bisection.\n\t\tif (\n\t\t\t! contrast.ignoreWhenAdjustingSeed &&\n\t\t\tsearchResults.deficit &&\n\t\t\tsearchResults.deficit > maxDeficit\n\t\t) {\n\t\t\tmaxDeficit = searchResults.deficit;\n\t\t\tmaxDeficitDirection = computedDir;\n\t\t\tmaxDeficitStep = stepName;\n\t\t}\n\n\t\t// Store calculated color for future dependencies\n\t\tcalculatedColors.set( stepName, searchResults.color );\n\n\t\t// Add to results\n\t\trampResults[ stepName ] = {\n\t\t\tcolor: getColorString( searchResults.color ),\n\t\t\twarning:\n\t\t\t\t! contrast.ignoreWhenAdjustingSeed && ! searchResults.reached,\n\t\t};\n\t}\n\treturn {\n\t\trampResults,\n\t\tmaxDeficit,\n\t\tmaxDeficitDirection,\n\t\tmaxDeficitStep,\n\t};\n}\n\nexport function buildRamp(\n\tseedArg: string,\n\tconfig: RampConfig,\n\t{\n\t\tmainDirection,\n\t\tpinLightness,\n\t\trescaleToFitContrastTargets = true,\n\t}: {\n\t\tmainDirection?: RampDirection;\n\t\tpinLightness?: {\n\t\t\tstepName: keyof Ramp;\n\t\t\tvalue: number;\n\t\t};\n\t\trescaleToFitContrastTargets?: boolean;\n\t} = {}\n): RampResult {\n\tlet seed: PlainColorObject;\n\ttry {\n\t\tseed = clampToGamut( parse( seedArg ) );\n\t} catch ( error ) {\n\t\tthrow new Error(\n\t\t\t`Invalid seed color \"${ seedArg }\": ${\n\t\t\t\terror instanceof Error ? error.message : 'Unknown error'\n\t\t\t}`\n\t\t);\n\t}\n\n\tlet mainDir: RampDirection = 'lighter';\n\tlet oppDir: RampDirection = 'darker';\n\n\tif ( mainDirection ) {\n\t\tmainDir = mainDirection;\n\t\toppDir = mainDirection === 'darker' ? 'lighter' : 'darker';\n\t} else {\n\t\tconst { better, worse } = computeBetterFgColorDirection( seed );\n\t\tmainDir = better;\n\t\toppDir = worse;\n\t}\n\n\t// Get the correct calculation order based on dependencies\n\tconst sortedSteps = sortByDependency( config );\n\n\t// Calculate the ramp with the initial seed.\n\tconst { rampResults, maxDeficit, maxDeficitDirection, maxDeficitStep } =\n\t\tcalculateRamp( {\n\t\t\tseed,\n\t\t\tsortedSteps,\n\t\t\tconfig,\n\t\t\tmainDir,\n\t\t\toppDir,\n\t\t\tpinLightness,\n\t\t} );\n\n\tlet bestRamp = rampResults;\n\n\tif ( maxDeficit > CONTRAST_EPSILON && rescaleToFitContrastTargets ) {\n\t\tconst iterSteps = stepsForStep( maxDeficitStep!, config );\n\n\t\tfunction getSeedForL( l: number ): ColorTypes {\n\t\t\treturn clampToGamut( set( clone( seed ), [ OKLCH, 'l' ], l ) );\n\t\t}\n\n\t\tfunction getDeficitForSeed( s: ColorTypes ): number {\n\t\t\tconst iterationResults = calculateRamp( {\n\t\t\t\tseed: s,\n\t\t\t\tsortedSteps: iterSteps,\n\t\t\t\tconfig,\n\t\t\t\tmainDir,\n\t\t\t\toppDir,\n\t\t\t\tpinLightness,\n\t\t\t} );\n\n\t\t\t// If the constraints start failing in the opposite direction to the original\n\t\t\t// iteration's direction, that means we've moved too far away from the target.\n\t\t\t// Don't use the `maxDeficit` value because it's not related to our search,\n\t\t\t// and might even be positive, which would confuse the bisection algorithm.\n\t\t\treturn iterationResults.maxDeficitDirection === maxDeficitDirection\n\t\t\t\t? iterationResults.maxDeficit\n\t\t\t\t: -maxDeficit;\n\t\t}\n\n\t\t// For a scale with the \"lighter\" direction, the contrast can be improved\n\t\t// by darkening the seed. For \"darker\" direction, by lightening the seed.\n\t\tconst lowerSeedL = maxDeficitDirection === 'lighter' ? 0 : 1;\n\t\tconst lowerDeficit = -maxDeficit;\n\t\tconst upperSeedL = get( seed, [ OKLCH, 'l' ] );\n\t\tconst upperDeficit = maxDeficit;\n\n\t\tconst bestSeed = solveWithBisect(\n\t\t\tgetSeedForL,\n\t\t\tgetDeficitForSeed,\n\t\t\tlowerSeedL,\n\t\t\tlowerDeficit,\n\t\t\tupperSeedL,\n\t\t\tupperDeficit\n\t\t);\n\n\t\t// Calculate the final ramp with adjusted seed.\n\t\tbestRamp = calculateRamp( {\n\t\t\tseed: bestSeed,\n\t\t\tsortedSteps,\n\t\t\tconfig,\n\t\t\tmainDir,\n\t\t\toppDir,\n\t\t\tpinLightness,\n\t\t} ).rampResults;\n\t}\n\n\t// Swap surface1 and surface3 for darker ramps to maintain visual elevation hierarchy.\n\t// This ensures surface1 appears \"behind\" surface2, and surface3 appears \"in front\",\n\t// regardless of the ramp's main direction.\n\tif ( mainDir === 'darker' ) {\n\t\tconst tmpSurface1 = bestRamp.surface1;\n\t\tbestRamp.surface1 = bestRamp.surface3;\n\t\tbestRamp.surface3 = tmpSurface1;\n\t}\n\n\treturn {\n\t\tramp: bestRamp,\n\t\tdirection: mainDir,\n\t};\n}\n"],
5
+ "mappings": ";AAGA;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGM;AAKP,OAAO;AACP,SAAS,aAAa,sBAAsB;AAC5C,SAAS,oCAAoC;AAC7C;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AASP,SAAS,wBAAwB;AAgBjC,SAAS,cAAe;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,GAUI;AACH,QAAM,cAAc,CAAC;AAIrB,MAAI,aAAa;AACjB,MAAI,sBAAqC;AACzC,MAAI;AAIJ,QAAM,mBAAmB,oBAAI,IAAuC;AACpE,mBAAiB,IAAK,QAAQ,IAAK;AAEnC,aAAY,YAAY,aAAc;AA0CrC,QAAS,mBAAT,SACC,OACA,iBACgB;AAChB,UAAK,oBAAoB,QAAS;AACjC,eAAO;AAAA,MACR;AAEA,UAAK,oBAAoB,YAAa;AACrC,eAAO;AAAA,MACR;AAEA,UAAK,oBAAoB,QAAS;AACjC,eAAO;AAAA,UACN;AAAA,UACA,SAAS;AAAA,QACV,EAAE;AAAA,MACH;AAEA,aAAO;AAAA,IACR;AA7DA,UAAM;AAAA,MACL;AAAA,MACA,WAAW;AAAA,MACX;AAAA,MACA;AAAA,IACD,IAAI,OAAQ,QAAS;AAErB,UAAM,iBAAiB,iBAAiB,IAAK,SAAS,SAAU;AAChE,QAAK,CAAE,gBAAiB;AACvB,YAAM,IAAI;AAAA,QACT,4BAA6B,QAAS,eAAgB,SAAS,SAAU;AAAA,MAC1E;AAAA,IACD;AAGA,QAA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