@dicebear/core 11.0.0 → 11.1.0-rc.1

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.
@@ -24,6 +24,7 @@ interface ColorField {
24
24
  readonly list?: true;
25
25
  readonly contrastTo?: string;
26
26
  readonly notEqualTo?: readonly string[];
27
+ readonly minContrast?: Readonly<Record<string, number>>;
27
28
  }
28
29
  interface RangeField {
29
30
  readonly type: 'range';
@@ -73,6 +73,7 @@ _a = OptionsDescriptor, _OptionsDescriptor_descriptor = new WeakMap(), _OptionsD
73
73
  const color = __classPrivateFieldGet(this, _OptionsDescriptor_style, "f").colors().get(name);
74
74
  const contrastTo = color?.contrastTo();
75
75
  const notEqualTo = color?.notEqualTo() ?? [];
76
+ const minContrast = color?.minContrast() ?? {};
76
77
  result[`${name}Color`] = {
77
78
  type: 'color',
78
79
  list: true,
@@ -80,6 +81,9 @@ _a = OptionsDescriptor, _OptionsDescriptor_descriptor = new WeakMap(), _OptionsD
80
81
  ...(notEqualTo.length > 0
81
82
  ? { notEqualTo: Array.from(notEqualTo) }
82
83
  : {}),
84
+ ...(Object.keys(minContrast).length > 0
85
+ ? { minContrast: { ...minContrast } }
86
+ : {}),
83
87
  };
84
88
  result[`${name}ColorFill`] = {
85
89
  type: 'enum',
package/lib/Resolver.js CHANGED
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Resolver_instances, _Resolver_style, _Resolver_options, _Resolver_prng, _Resolver_colorResolving, _Resolver_result, _Resolver_tagFilterCache, _Resolver_probability, _Resolver_isVisible, _Resolver_variantWeights, _Resolver_tagFilter, _Resolver_tagFilteredNames, _Resolver_resolveColor, _Resolver_order, _Resolver_colorFillStops, _Resolver_memoFloat, _Resolver_memo;
12
+ var _Resolver_instances, _Resolver_style, _Resolver_options, _Resolver_prng, _Resolver_colorResolving, _Resolver_result, _Resolver_tagFilterCache, _Resolver_probability, _Resolver_isVisible, _Resolver_variantWeights, _Resolver_tagFilter, _Resolver_tagFilteredNames, _Resolver_resolveColor, _Resolver_minContrastReferences, _Resolver_order, _Resolver_colorFillStops, _Resolver_memoFloat, _Resolver_memo;
13
13
  import { Prng } from './Prng.js';
14
14
  import { Color } from './Utils/Color.js';
15
15
  import { CircularColorReferenceError } from './Error/CircularColorReferenceError.js';
@@ -311,15 +311,21 @@ _Resolver_style = new WeakMap(), _Resolver_options = new WeakMap(), _Resolver_pr
311
311
  }
312
312
  candidates = Color.filterNotEqualTo(candidates, excluded);
313
313
  }
314
+ // Skip shuffle when sorted by contrast to preserve the ordering
315
+ const ordered = contrastTo
316
+ ? candidates
317
+ : __classPrivateFieldGet(this, _Resolver_instances, "m", _Resolver_order).call(this, name, candidates, fixed);
318
+ // Filtered after the shuffle, so that a color only changes where it
319
+ // broke the rule: a shorter list would be shuffled differently.
320
+ return Color.filterMinContrast(ordered, __classPrivateFieldGet(this, _Resolver_instances, "m", _Resolver_minContrastReferences).call(this, styleColor.minContrast())).slice(0, stops);
314
321
  }
315
322
  finally {
316
323
  __classPrivateFieldGet(this, _Resolver_colorResolving, "f").pop();
317
324
  }
318
- // Skip shuffle when sorted by contrast to preserve the ordering
319
- const ordered = contrastTo
320
- ? candidates
321
- : __classPrivateFieldGet(this, _Resolver_instances, "m", _Resolver_order).call(this, name, candidates, fixed);
322
- return ordered.slice(0, stops);
325
+ }, _Resolver_minContrastReferences = function _Resolver_minContrastReferences(minContrast) {
326
+ return Object.keys(minContrast)
327
+ .sort()
328
+ .flatMap((ref) => this.color(ref).map((color) => ({ color, ratio: minContrast[ref] })));
323
329
  }, _Resolver_order = function _Resolver_order(name, candidates, fixed) {
324
330
  return fixed ? candidates : __classPrivateFieldGet(this, _Resolver_prng, "f").shuffle(`${name}Color`, candidates);
325
331
  }, _Resolver_colorFillStops = function _Resolver_colorFillStops(name, fallback) {
@@ -19,4 +19,9 @@ export declare class Color {
19
19
  * or `undefined` when no contrast constraint is defined.
20
20
  */
21
21
  contrastTo(): string | undefined;
22
+ /**
23
+ * Returns the minimum contrast ratio this color should keep to other colors,
24
+ * keyed by their names, or an empty object when the field is unset.
25
+ */
26
+ minContrast(): Readonly<Record<string, number>>;
22
27
  }
@@ -38,5 +38,12 @@ export class Color {
38
38
  contrastTo() {
39
39
  return __classPrivateFieldGet(this, _Color_data, "f").contrastTo;
40
40
  }
41
+ /**
42
+ * Returns the minimum contrast ratio this color should keep to other colors,
43
+ * keyed by their names, or an empty object when the field is unset.
44
+ */
45
+ minContrast() {
46
+ return __classPrivateFieldGet(this, _Color_data, "f").minContrast ?? {};
47
+ }
41
48
  }
42
49
  _Color_data = new WeakMap();
package/lib/Style.d.ts CHANGED
@@ -7,9 +7,10 @@ export type { StyleDefinition } from './StyleDefinition.js';
7
7
  /** Key of the type-only member that carries the definition type. */
8
8
  declare const definitionType: unique symbol;
9
9
  /**
10
- * Validated, lazily-decomposed wrapper around a style definition. Construction
11
- * runs the JSON Schema validator and stores a deep clone of the input so that
12
- * later mutation of the source object cannot leak into the rendered avatar.
10
+ * Lazily-decomposed wrapper around a style definition. Construction stores a
11
+ * deep clone of the input so that later mutation of the source object cannot
12
+ * leak into the rendered avatar. It validates nothing: the package root runs
13
+ * {@link StyleValidator} first, the lite entry trusts its input.
13
14
  */
14
15
  export declare class Style<D = unknown> {
15
16
  #private;
package/lib/Style.js CHANGED
@@ -9,16 +9,16 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Style_instances, _a, _Style_data, _Style_meta, _Style_canvas, _Style_components, _Style_colors, _Style_hasAnimations, _Style_animationNames, _Style_validateAliases, _Style_isAlias, _Style_validateAnimations, _Style_visitElements;
13
- import { StyleValidationError } from './Error/StyleValidationError.js';
12
+ var _Style_instances, _a, _Style_data, _Style_meta, _Style_canvas, _Style_components, _Style_colors, _Style_hasAnimations, _Style_animationNames, _Style_isAlias, _Style_visitElements;
14
13
  import { Meta } from './Style/Meta.js';
15
14
  import { Canvas } from './Style/Canvas.js';
16
15
  import { Component } from './Style/Component.js';
17
16
  import { Color } from './Style/Color.js';
18
17
  /**
19
- * Validated, lazily-decomposed wrapper around a style definition. Construction
20
- * runs the JSON Schema validator and stores a deep clone of the input so that
21
- * later mutation of the source object cannot leak into the rendered avatar.
18
+ * Lazily-decomposed wrapper around a style definition. Construction stores a
19
+ * deep clone of the input so that later mutation of the source object cannot
20
+ * leak into the rendered avatar. It validates nothing: the package root runs
21
+ * {@link StyleValidator} first, the lite entry trusts its input.
22
22
  */
23
23
  export class Style {
24
24
  constructor(data) {
@@ -31,8 +31,6 @@ export class Style {
31
31
  _Style_hasAnimations.set(this, void 0);
32
32
  _Style_animationNames.set(this, void 0);
33
33
  __classPrivateFieldSet(this, _Style_data, structuredClone(data), "f");
34
- __classPrivateFieldGet(this, _Style_instances, "m", _Style_validateAliases).call(this);
35
- __classPrivateFieldGet(this, _Style_instances, "m", _Style_validateAnimations).call(this);
36
34
  }
37
35
  /**
38
36
  * Returns the definition's `$id`, or `undefined` when not set.
@@ -153,57 +151,8 @@ export class Style {
153
151
  return __classPrivateFieldGet(this, _Style_colors, "f");
154
152
  }
155
153
  }
156
- _a = Style, _Style_data = new WeakMap(), _Style_meta = new WeakMap(), _Style_canvas = new WeakMap(), _Style_components = new WeakMap(), _Style_colors = new WeakMap(), _Style_hasAnimations = new WeakMap(), _Style_animationNames = new WeakMap(), _Style_instances = new WeakSet(), _Style_validateAliases = function _Style_validateAliases() {
157
- const components = __classPrivateFieldGet(this, _Style_data, "f").components;
158
- if (!components) {
159
- return;
160
- }
161
- const errors = [];
162
- for (const [name, data] of Object.entries(components)) {
163
- if (!__classPrivateFieldGet(_a, _a, "m", _Style_isAlias).call(_a, data)) {
164
- continue;
165
- }
166
- const target = data.extends;
167
- const targetData = components[target];
168
- if (!targetData) {
169
- errors.push({
170
- instancePath: `/components/${name}/extends`,
171
- message: `references unknown component "${target}"`,
172
- });
173
- continue;
174
- }
175
- if (__classPrivateFieldGet(_a, _a, "m", _Style_isAlias).call(_a, targetData)) {
176
- errors.push({
177
- instancePath: `/components/${name}/extends`,
178
- message: `references alias "${target}" — alias chains are not allowed`,
179
- });
180
- }
181
- }
182
- if (errors.length > 0) {
183
- throw new StyleValidationError(errors);
184
- }
185
- }, _Style_isAlias = function _Style_isAlias(data) {
154
+ _a = Style, _Style_data = new WeakMap(), _Style_meta = new WeakMap(), _Style_canvas = new WeakMap(), _Style_components = new WeakMap(), _Style_colors = new WeakMap(), _Style_hasAnimations = new WeakMap(), _Style_animationNames = new WeakMap(), _Style_instances = new WeakSet(), _Style_isAlias = function _Style_isAlias(data) {
186
155
  return 'extends' in data;
187
- }, _Style_validateAnimations = function _Style_validateAnimations() {
188
- const errors = [];
189
- __classPrivateFieldGet(this, _Style_instances, "m", _Style_visitElements).call(this, (element, path) => {
190
- element.animations?.forEach((animation, animationIndex) => {
191
- for (const [trackName, track] of Object.entries(animation.tracks)) {
192
- const keyframes = track.keyframes;
193
- for (let i = 1; i < keyframes.length; i++) {
194
- if (keyframes[i].at <= keyframes[i - 1].at) {
195
- errors.push({
196
- instancePath: `${path}/animations/${animationIndex}/tracks/${trackName}/keyframes/${i}/at`,
197
- message: 'must be greater than the previous keyframe',
198
- });
199
- }
200
- }
201
- }
202
- });
203
- });
204
- if (errors.length > 0) {
205
- throw new StyleValidationError(errors);
206
- }
207
156
  }, _Style_visitElements = function _Style_visitElements(visit) {
208
157
  const walk = (elements, path) => {
209
158
  elements.forEach((element, index) => {
@@ -111,6 +111,7 @@ export interface StyleDefinitionColor {
111
111
  readonly values: readonly string[];
112
112
  readonly notEqualTo?: readonly string[];
113
113
  readonly contrastTo?: string;
114
+ readonly minContrast?: Readonly<Record<string, number>>;
114
115
  }
115
116
  /**
116
117
  * A closed numeric range. `min === max` represents a fixed value. `step`
@@ -34,4 +34,16 @@ export declare class Color {
34
34
  * original candidates when filtering would empty the list.
35
35
  */
36
36
  static filterNotEqualTo(candidates: readonly string[], excluded: readonly string[]): string[];
37
+ /**
38
+ * Returns a new array with the candidates that reach the minimum contrast
39
+ * ratio to every reference color, in their given order.
40
+ *
41
+ * When no candidate does, each one is rated by the reference it misses by
42
+ * the most (the lowest contrast relative to the required minimum), and the
43
+ * candidates with the best rating are returned.
44
+ */
45
+ static filterMinContrast(candidates: readonly string[], references: readonly {
46
+ readonly color: string;
47
+ readonly ratio: number;
48
+ }[]): string[];
37
49
  }
@@ -3,7 +3,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
3
3
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
4
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
5
  };
6
- var _a, _Color_LINEARIZED, _Color_linearize;
6
+ var _a, _Color_contrastRatio, _Color_LINEARIZED, _Color_linearize;
7
7
  /**
8
8
  * Color helpers used by the renderer and option resolver.
9
9
  */
@@ -61,8 +61,7 @@ export class Color {
61
61
  static sortByContrast(candidates, refColor) {
62
62
  const refLum = this.luminance(refColor);
63
63
  const withRatio = candidates.map((c) => {
64
- const lum = this.luminance(c);
65
- const ratio = (Math.max(lum, refLum) + 0.05) / (Math.min(lum, refLum) + 0.05);
64
+ const ratio = __classPrivateFieldGet(this, _a, "m", _Color_contrastRatio).call(this, this.luminance(c), refLum);
66
65
  return { color: c, ratio };
67
66
  });
68
67
  withRatio.sort((a, b) => b.ratio - a.ratio);
@@ -77,8 +76,43 @@ export class Color {
77
76
  const filtered = candidates.filter((c) => !normalized.has(this.toRgbHex(c)));
78
77
  return filtered.length > 0 ? filtered : Array.from(candidates);
79
78
  }
79
+ /**
80
+ * Returns a new array with the candidates that reach the minimum contrast
81
+ * ratio to every reference color, in their given order.
82
+ *
83
+ * When no candidate does, each one is rated by the reference it misses by
84
+ * the most (the lowest contrast relative to the required minimum), and the
85
+ * candidates with the best rating are returned.
86
+ */
87
+ static filterMinContrast(candidates, references) {
88
+ const refs = references.map(({ color, ratio }) => ({
89
+ luminance: this.luminance(color),
90
+ ratio,
91
+ }));
92
+ const rated = candidates.map((color) => {
93
+ const luminance = this.luminance(color);
94
+ let passes = true;
95
+ let score = Infinity;
96
+ for (const ref of refs) {
97
+ const contrast = __classPrivateFieldGet(this, _a, "m", _Color_contrastRatio).call(this, luminance, ref.luminance);
98
+ passes &&= contrast >= ref.ratio;
99
+ score = Math.min(score, contrast / ref.ratio);
100
+ }
101
+ return { color, passes, score };
102
+ });
103
+ const passing = rated.filter((entry) => entry.passes);
104
+ if (passing.length > 0) {
105
+ return passing.map((entry) => entry.color);
106
+ }
107
+ const best = rated.reduce((max, entry) => Math.max(max, entry.score), 0);
108
+ return rated
109
+ .filter((entry) => entry.score === best)
110
+ .map((entry) => entry.color);
111
+ }
80
112
  }
81
- _a = Color, _Color_linearize = function _Color_linearize(channel) {
113
+ _a = Color, _Color_contrastRatio = function _Color_contrastRatio(a, b) {
114
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
115
+ }, _Color_linearize = function _Color_linearize(channel) {
82
116
  return __classPrivateFieldGet(_a, _a, "f", _Color_LINEARIZED)[channel];
83
117
  };
84
118
  /**
@@ -0,0 +1,3 @@
1
+ export class OptionsSchemaValidator {
2
+ static validate(data: any): void;
3
+ }