@samizdata/mozaic 0.7.0 → 0.9.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.
@@ -3,10 +3,12 @@
3
3
  A text annotation with an optional curved arrow pointing at a data point.
4
4
  `x`/`y` are in data space (band scales point at the band centre); `dx`/`dy`
5
5
  place the label in pixels relative to that point. Newlines split the label.
6
+ Pass `color` (the target's series colour) to colour the text and arrow.
6
7
  -->
7
8
  <script lang="ts">
8
9
  import { useChart, usePlot } from '../core/context.js';
9
10
  import { scaled } from '../core/scales.js';
11
+ import { readableColor } from '../styles/color.js';
10
12
  import { calloutGeometry } from './callout-geometry.js';
11
13
 
12
14
  interface Props {
@@ -21,6 +23,12 @@ place the label in pixels relative to that point. Newlines split the label.
21
23
  /** Defaults to `start` when the label is right of the target, `end` when left. */
22
24
  anchor?: 'start' | 'middle' | 'end';
23
25
  fontSize?: number;
26
+ /**
27
+ * Colour for the text and arrow, usually the series colour of the
28
+ * target. Darkened (or lightened on dark backgrounds) where needed to
29
+ * reach 4.5:1 against the background. Defaults to the text colour.
30
+ */
31
+ color?: string;
24
32
  class?: string;
25
33
  }
26
34
 
@@ -34,6 +42,7 @@ place the label in pixels relative to that point. Newlines split the label.
34
42
  arrow = true,
35
43
  anchor,
36
44
  fontSize,
45
+ color,
37
46
  class: className = ''
38
47
  }: Props = $props();
39
48
 
@@ -41,6 +50,7 @@ place the label in pixels relative to that point. Newlines split the label.
41
50
  const plot = usePlot();
42
51
 
43
52
  const size = $derived(fontSize ?? chart.theme.plot.fontSize);
53
+ const ink = $derived(color ? readableColor(color, chart.theme.tokens['--mz-color-bg']) : undefined);
44
54
  const lines = $derived(label.split('\n'));
45
55
  const lineHeight = $derived(size * 1.25);
46
56
  const textAnchor = $derived(anchor ?? (dx > 0 ? 'start' : dx < 0 ? 'end' : 'middle'));
@@ -59,10 +69,10 @@ place the label in pixels relative to that point. Newlines split the label.
59
69
 
60
70
  <g class="mz-callout {className}">
61
71
  {#if arrow}
62
- <path class="mz-callout-arrow" d={geometry.arrow} />
63
- <path class="mz-callout-arrow" d={geometry.head} />
72
+ <path class="mz-callout-arrow" d={geometry.arrow} style:stroke={ink} />
73
+ <path class="mz-callout-arrow" d={geometry.head} style:stroke={ink} />
64
74
  {/if}
65
- <text x={lx} y={ly} text-anchor={textAnchor} font-size={size}>
75
+ <text x={lx} y={ly} text-anchor={textAnchor} font-size={size} style:fill={ink}>
66
76
  {#each lines as line, i}
67
77
  <tspan x={lx} dy={i === 0 ? 0 : lineHeight}>{line}</tspan>
68
78
  {/each}
@@ -10,12 +10,19 @@ interface Props {
10
10
  /** Defaults to `start` when the label is right of the target, `end` when left. */
11
11
  anchor?: 'start' | 'middle' | 'end';
12
12
  fontSize?: number;
13
+ /**
14
+ * Colour for the text and arrow, usually the series colour of the
15
+ * target. Darkened (or lightened on dark backgrounds) where needed to
16
+ * reach 4.5:1 against the background. Defaults to the text colour.
17
+ */
18
+ color?: string;
13
19
  class?: string;
14
20
  }
15
21
  /**
16
22
  * A text annotation with an optional curved arrow pointing at a data point.
17
23
  * `x`/`y` are in data space (band scales point at the band centre); `dx`/`dy`
18
24
  * place the label in pixels relative to that point. Newlines split the label.
25
+ * Pass `color` (the target's series colour) to colour the text and arrow.
19
26
  */
20
27
  declare const Callout: import("svelte").Component<Props, {}, "">;
21
28
  type Callout = ReturnType<typeof Callout>;
@@ -2,10 +2,12 @@
2
2
  @component
3
3
  A label next to a data point, with an optional marker dot. For labelling a
4
4
  few highlighted points in a scatter plot. Text has a halo for legibility.
5
+ Pass `color` (the point's series colour) to colour the label and marker.
5
6
  -->
6
7
  <script lang="ts">
7
- import { usePlot } from '../core/context.js';
8
+ import { useChart, usePlot } from '../core/context.js';
8
9
  import { position } from '../core/scales.js';
10
+ import { readableColor } from '../styles/color.js';
9
11
 
10
12
  interface Props {
11
13
  x: unknown;
@@ -17,23 +19,43 @@ few highlighted points in a scatter plot. Text has a halo for legibility.
17
19
  /** Draw a ring around the point. */
18
20
  marker?: boolean;
19
21
  bold?: boolean;
22
+ /**
23
+ * Colour for the label and marker, usually the series colour of the
24
+ * point. Darkened (or lightened on dark backgrounds) where needed to
25
+ * reach 4.5:1 against the background. Defaults to the text colour.
26
+ */
27
+ color?: string;
20
28
  class?: string;
21
29
  }
22
30
 
23
- let { x, y, label, dx = 6, dy = 0, anchor, marker = false, bold = false, class: className = '' }: Props = $props();
31
+ let {
32
+ x,
33
+ y,
34
+ label,
35
+ dx = 6,
36
+ dy = 0,
37
+ anchor,
38
+ marker = false,
39
+ bold = false,
40
+ color,
41
+ class: className = ''
42
+ }: Props = $props();
24
43
 
44
+ const chart = useChart();
25
45
  const plot = usePlot();
26
46
  const p = $derived(position(plot, x, y));
27
47
  const textAnchor = $derived(anchor ?? (dx > 0 ? 'start' : dx < 0 ? 'end' : 'middle'));
48
+ const ink = $derived(color ? readableColor(color, chart.theme.tokens['--mz-color-bg']) : undefined);
28
49
  </script>
29
50
 
30
51
  <g class="mz-label {className}">
31
- {#if marker}<circle cx={p[0]} cy={p[1]} r={6} />{/if}
52
+ {#if marker}<circle cx={p[0]} cy={p[1]} r={6} style:stroke={ink} />{/if}
32
53
  <text
33
54
  x={p[0] + dx}
34
55
  y={p[1] + dy}
35
56
  dy="0.32em"
36
57
  text-anchor={textAnchor}
58
+ style:fill={ink}
37
59
  style:font-weight={bold ? 'var(--mz-weight-strong)' : undefined}>{label}</text
38
60
  >
39
61
  </g>
@@ -8,11 +8,18 @@ interface Props {
8
8
  /** Draw a ring around the point. */
9
9
  marker?: boolean;
10
10
  bold?: boolean;
11
+ /**
12
+ * Colour for the label and marker, usually the series colour of the
13
+ * point. Darkened (or lightened on dark backgrounds) where needed to
14
+ * reach 4.5:1 against the background. Defaults to the text colour.
15
+ */
16
+ color?: string;
11
17
  class?: string;
12
18
  }
13
19
  /**
14
20
  * A label next to a data point, with an optional marker dot. For labelling a
15
21
  * few highlighted points in a scatter plot. Text has a halo for legibility.
22
+ * Pass `color` (the point's series colour) to colour the label and marker.
16
23
  */
17
24
  declare const Label: import("svelte").Component<Props, {}, "">;
18
25
  type Label = ReturnType<typeof Label>;
@@ -1,6 +1,8 @@
1
1
  <!--
2
2
  @component
3
- Notes, sources and credits below the plot, with the house wordmark on the right.
3
+ Notes, sources and credits below the plot. Each takes the full width, except the `Source` line,
4
+ which shares its row with the house logo on the right. Without a `Source`, the logo sits below
5
+ the rest, on the right.
4
6
  -->
5
7
  <script lang="ts">
6
8
  import type { Snippet } from 'svelte';
@@ -14,26 +16,35 @@ Notes, sources and credits below the plot, with the house wordmark on the right.
14
16
  </script>
15
17
 
16
18
  <footer class="mz-footer {className}">
17
- <div class="mz-footer-text">
18
- {@render children?.()}
19
- </div>
19
+ {@render children?.()}
20
20
  {#if logo}<Logo />{/if}
21
21
  </footer>
22
22
 
23
23
  <style>
24
24
  .mz-footer {
25
- display: flex;
26
- align-items: flex-end;
27
- justify-content: space-between;
28
- gap: 1rem;
25
+ display: grid;
26
+ grid-template-columns: minmax(0, 1fr) auto;
27
+ /* Dense, so the logo (last in the markup) goes back up to the free cell beside the source. */
28
+ grid-auto-flow: row dense;
29
+ align-items: center;
30
+ column-gap: 1rem;
31
+ row-gap: 0.25rem;
29
32
  font-size: var(--mz-size-small);
30
33
  line-height: 1.4;
31
34
  color: var(--mz-color-muted);
32
35
  }
33
- .mz-footer-text {
34
- display: flex;
35
- flex-direction: column;
36
- gap: 0.25rem;
37
- min-width: 0;
36
+ .mz-footer > :global(*) {
37
+ grid-column: 1 / -1;
38
+ }
39
+ .mz-footer > :global(.mz-source) {
40
+ grid-column: 1;
41
+ }
42
+ .mz-footer > :global(.mz-logo) {
43
+ grid-column: 2;
44
+ justify-self: end;
45
+ }
46
+ /* No taller than one and a half lines of footer text, whatever height the style gives the mark. */
47
+ .mz-footer > :global(.mz-logo .mz-logo-mark) {
48
+ max-height: 1.5lh;
38
49
  }
39
50
  </style>
@@ -4,7 +4,11 @@ type $$ComponentProps = {
4
4
  class?: string;
5
5
  children?: Snippet;
6
6
  };
7
- /** Notes, sources and credits below the plot, with the house wordmark on the right. */
7
+ /**
8
+ * Notes, sources and credits below the plot. Each takes the full width, except the `Source` line,
9
+ * which shares its row with the house logo on the right. Without a `Source`, the logo sits below
10
+ * the rest, on the right.
11
+ */
8
12
  declare const Footer: import("svelte").Component<$$ComponentProps, {}, "">;
9
13
  type Footer = ReturnType<typeof Footer>;
10
14
  export default Footer;
@@ -1,6 +1,7 @@
1
1
  <!--
2
2
  @component
3
- "Note: …", with the label in the chart's language. Set `plural` for several notes.
3
+ "Note: …", with the label in the chart's language. Set `plural` for several notes. Renders
4
+ nothing when the content is empty (`<Notes>{t.notes}</Notes>` with no `notes` string).
4
5
  -->
5
6
  <script lang="ts">
6
7
  import type { Snippet } from 'svelte';
@@ -13,13 +14,16 @@
13
14
 
14
15
  <p class="mz-notes">
15
16
  <span class="mz-label">{plural ? chart.locale.strings.notes : chart.locale.strings.note}:</span>
16
- {@render children?.()}
17
+ <span class="mz-notes-body">{@render children?.()}</span>
17
18
  </p>
18
19
 
19
20
  <style>
20
21
  .mz-notes {
21
22
  margin: 0;
22
23
  }
24
+ .mz-notes:has(> .mz-notes-body:empty) {
25
+ display: none;
26
+ }
23
27
  .mz-label {
24
28
  font-family: var(--mz-font-label);
25
29
  font-weight: var(--mz-weight-label);
@@ -3,7 +3,10 @@ type $$ComponentProps = {
3
3
  plural?: boolean;
4
4
  children?: Snippet;
5
5
  };
6
- /** "Note: …", with the label in the chart's language. Set `plural` for several notes. */
6
+ /**
7
+ * "Note: …", with the label in the chart's language. Set `plural` for several notes. Renders
8
+ * nothing when the content is empty (`<Notes>{t.notes}</Notes>` with no `notes` string).
9
+ */
7
10
  declare const Notes: import("svelte").Component<$$ComponentProps, {}, "">;
8
11
  type Notes = ReturnType<typeof Notes>;
9
12
  export default Notes;
@@ -1,12 +1,14 @@
1
1
  <!--
2
2
  @component
3
3
  Direct labels at the end of lines: a dot in the series colour on the last
4
- point, and the label in text colour beside it. Labels are nudged apart so
5
- they never overlap; a short leader joins a nudged label to its dot.
4
+ point, and the label beside it, in the text colour or (with `colorText`) in
5
+ the series colour so the labels double as the legend. Labels are nudged apart
6
+ so they never overlap; a short leader joins a nudged label to its dot.
6
7
  -->
7
8
  <script lang="ts" generics="T">
8
- import { usePlot } from '../core/context.js';
9
+ import { useChart, usePlot } from '../core/context.js';
9
10
  import { scaled } from '../core/scales.js';
11
+ import { readableColor } from '../styles/color.js';
10
12
  import { avoidOverlap } from '../transforms/labels.js';
11
13
 
12
14
  interface Props {
@@ -20,12 +22,19 @@ they never overlap; a short leader joins a nudged label to its dot.
20
22
  dx?: number;
21
23
  /** Minimum vertical distance between labels, px. */
22
24
  minGap?: number;
25
+ /**
26
+ * Colour each label like its series, darkened (or lightened on dark
27
+ * backgrounds) where needed to reach 4.5:1 against the background.
28
+ */
29
+ colorText?: boolean;
23
30
  class?: string;
24
31
  }
25
32
 
26
- let { data, x, y, text, color, dx = 10, minGap = 14, class: className = '' }: Props = $props();
33
+ let { data, x, y, text, color, dx = 10, minGap = 14, colorText = false, class: className = '' }: Props = $props();
27
34
 
35
+ const chart = useChart();
28
36
  const plot = usePlot();
37
+ const background = $derived(chart.theme.tokens['--mz-color-bg']);
29
38
 
30
39
  const labels = $derived.by(() => {
31
40
  const points = data.map((d) => ({ d, px: scaled(plot.x, x(d)), py: scaled(plot.y, y(d)) }));
@@ -44,7 +53,12 @@ they never overlap; a short leader joins a nudged label to its dot.
44
53
  <path class="mz-leader" d="M{label.px + 5},{label.py}L{label.px + dx - 3},{label.ly}" />
45
54
  {/if}
46
55
  <circle cx={label.px} cy={label.py} r={4} fill={color(label.d)} />
47
- <text x={label.px + dx} y={label.ly} dy="0.32em">{text(label.d)}</text>
56
+ <text
57
+ x={label.px + dx}
58
+ y={label.ly}
59
+ dy="0.32em"
60
+ style:fill={colorText ? readableColor(color(label.d), background) : undefined}>{text(label.d)}</text
61
+ >
48
62
  {/each}
49
63
  </g>
50
64
 
@@ -10,6 +10,11 @@ declare function $$render<T>(): {
10
10
  dx?: number;
11
11
  /** Minimum vertical distance between labels, px. */
12
12
  minGap?: number;
13
+ /**
14
+ * Colour each label like its series, darkened (or lightened on dark
15
+ * backgrounds) where needed to reach 4.5:1 against the background.
16
+ */
17
+ colorText?: boolean;
13
18
  class?: string;
14
19
  };
15
20
  exports: {};
@@ -33,8 +38,9 @@ interface $$IsomorphicComponent {
33
38
  }
34
39
  /**
35
40
  * Direct labels at the end of lines: a dot in the series colour on the last
36
- * point, and the label in text colour beside it. Labels are nudged apart so
37
- * they never overlap; a short leader joins a nudged label to its dot.
41
+ * point, and the label beside it, in the text colour or (with `colorText`) in
42
+ * the series colour so the labels double as the legend. Labels are nudged apart
43
+ * so they never overlap; a short leader joins a nudged label to its dot.
38
44
  */
39
45
  declare const LineEndLabels: $$IsomorphicComponent;
40
46
  type LineEndLabels<T> = InstanceType<typeof LineEndLabels<T>>;
@@ -2,6 +2,15 @@
2
2
  export declare function luminance(hex: string): number;
3
3
  /** WCAG contrast ratio between two `#rrggbb` colours (1–21). */
4
4
  export declare function contrastRatio(a: string, b: string): number;
5
+ /**
6
+ * A data colour that can be used for text: `color` itself when it reaches
7
+ * `minContrast` (WCAG 4.5:1 by default) against `background`, otherwise the
8
+ * least-changed shade of it that does, darkened towards black on light
9
+ * backgrounds and lightened towards white on dark ones. Lets a label take its
10
+ * series colour and still be readable. Colours that aren't `#rgb`/`#rrggbb`
11
+ * are returned unchanged.
12
+ */
13
+ export declare function readableColor(color: string, background?: string, minContrast?: number): string;
5
14
  /**
6
15
  * `n` colours from a light → dark ramp for binned data (choropleths, heat
7
16
  * steps). Steps too pale to see against `background` (below `minContrast`)
@@ -12,6 +12,54 @@ export function contrastRatio(a, b) {
12
12
  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
13
13
  return (hi + 0.05) / (lo + 0.05);
14
14
  }
15
+ const HEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
16
+ function expand(hex) {
17
+ const h = hex.slice(1);
18
+ return h.length === 3 ? `#${[...h].map((c) => c + c).join('')}` : hex;
19
+ }
20
+ function toLinear(c) {
21
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
22
+ }
23
+ function toHex(linear) {
24
+ return `#${linear
25
+ .map((c) => {
26
+ const s = c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
27
+ return Math.round(Math.min(1, Math.max(0, s)) * 255)
28
+ .toString(16)
29
+ .padStart(2, '0');
30
+ })
31
+ .join('')}`;
32
+ }
33
+ /**
34
+ * A data colour that can be used for text: `color` itself when it reaches
35
+ * `minContrast` (WCAG 4.5:1 by default) against `background`, otherwise the
36
+ * least-changed shade of it that does, darkened towards black on light
37
+ * backgrounds and lightened towards white on dark ones. Lets a label take its
38
+ * series colour and still be readable. Colours that aren't `#rgb`/`#rrggbb`
39
+ * are returned unchanged.
40
+ */
41
+ export function readableColor(color, background = '#ffffff', minContrast = 4.5) {
42
+ if (!HEX.test(color) || !HEX.test(background))
43
+ return color;
44
+ const c = expand(color).toLowerCase();
45
+ const bg = expand(background);
46
+ if (contrastRatio(c, bg) >= minContrast)
47
+ return c;
48
+ const target = contrastRatio('#000000', bg) >= contrastRatio('#ffffff', bg) ? 0 : 1;
49
+ const n = parseInt(c.slice(1), 16);
50
+ const linear = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((v) => toLinear(v / 255));
51
+ const mix = (t) => toHex(linear.map((v) => v + (target - v) * t));
52
+ // Smallest mix towards black/white that passes; contrast rises with t.
53
+ let [lo, hi] = [0, 1];
54
+ for (let i = 0; i < 24; i++) {
55
+ const mid = (lo + hi) / 2;
56
+ if (contrastRatio(mix(mid), bg) >= minContrast)
57
+ hi = mid;
58
+ else
59
+ lo = mid;
60
+ }
61
+ return mix(hi);
62
+ }
15
63
  /**
16
64
  * `n` colours from a light → dark ramp for binned data (choropleths, heat
17
65
  * steps). Steps too pale to see against `background` (below `minContrast`)
@@ -2,7 +2,7 @@ import type { Breakpoint, Theme } from './types.js';
2
2
  export type { Breakpoint, Medium, Padding, Theme, ThemeOverrides } from './types.js';
3
3
  /** House styles live with each brand (e.g. `datavis/mozaic/` in a brand repo) and extend `base`. */
4
4
  export { base, extendTheme } from './base.js';
5
- export { contrastRatio, luminance, rampSteps } from './color.js';
5
+ export { contrastRatio, luminance, rampSteps, readableColor } from './color.js';
6
6
  export { checkTheme } from './check.js';
7
7
  /** Serialise theme tokens into an inline `style` attribute value. */
8
8
  export declare function tokensToStyle(tokens: Theme['tokens']): string;
@@ -1,6 +1,6 @@
1
1
  /** House styles live with each brand (e.g. `datavis/mozaic/` in a brand repo) and extend `base`. */
2
2
  export { base, extendTheme } from './base.js';
3
- export { contrastRatio, luminance, rampSteps } from './color.js';
3
+ export { contrastRatio, luminance, rampSteps, readableColor } from './color.js';
4
4
  export { checkTheme } from './check.js';
5
5
  /** Serialise theme tokens into an inline `style` attribute value. */
6
6
  export function tokensToStyle(tokens) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@samizdata/mozaic",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Chart components for the web and print, built on Svelte 5 and d3, and the mozaic CLI (export embeds to SVG, PDF and PNG; eject recipes).",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "author": "Nicu Calcea",