@samizdata/mozaic 0.15.0 → 0.16.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.
- package/README.md +2 -1
- package/dist/embed/ElementChart.svelte +25 -0
- package/dist/embed/ElementChart.svelte.d.ts +18 -0
- package/dist/embed/code.d.ts +20 -0
- package/dist/embed/code.js +18 -0
- package/dist/embed/element.d.ts +44 -0
- package/dist/embed/element.js +153 -0
- package/dist/embed/index.d.ts +2 -1
- package/dist/embed/index.js +2 -1
- package/dist/frame/ChartTools.svelte +5 -1
- package/dist/interactive/touch-hold.js +2 -1
- package/package.json +18 -3
- package/vite/index.d.ts +18 -0
- package/vite/index.js +52 -0
- package/vite/jsconfig.json +5 -0
package/README.md
CHANGED
|
@@ -38,9 +38,10 @@ pnpm add @samizdata/mozaic d3-scale d3-array d3-shape
|
|
|
38
38
|
| `@samizdata/mozaic/transforms` | `stack`, `bin`, `groupBy`, `rollup`, `indexTo`, `dodge`, `treemapLayout`, `avoidOverlap`, `hemicycleLayout`, `kernelSmooth`, `loess` |
|
|
39
39
|
| `@samizdata/mozaic/styles` | `base`, `extendTheme`, `checkTheme`, `rampSteps`, `contrastRatio` (house styles live with each brand) |
|
|
40
40
|
| `@samizdata/mozaic/locale` | `createLocale` (`en`, `ro`, `ru`) |
|
|
41
|
-
| `@samizdata/mozaic/embed` | `Embed`, `useEmbedParams`, `embedCode`, `hostScript`, `observeHeight`
|
|
41
|
+
| `@samizdata/mozaic/embed` | `Embed`, `useEmbedParams`, `embedCode`, `hostScript`, `observeHeight`; optional web component: `defineChartElements`, `elementCode` |
|
|
42
42
|
| `@samizdata/mozaic/export` | `figureToSvg`, `downloadSvg`, `downloadPng`, `figureToPng` |
|
|
43
43
|
| `@samizdata/mozaic/recipes` | `BarChart`, `ColumnChart`, `LineChart`, `ScatterChart`, `ArrowChart`, `BarDotChart`, `StackedBarChart`, `MosaicChart`, `PercentileChart`, `StripChart`, `FootprintMap` |
|
|
44
|
+
| `@samizdata/mozaic/vite` | `elementConfig` (Node: builds a project's web component embed, `element.js`) |
|
|
44
45
|
|
|
45
46
|
## CLI
|
|
46
47
|
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
What `<mozaic-chart>` mounts in its shadow root: the chart on its own, marked as embedded so it
|
|
4
|
+
leaves out the controls meant for the chart's own site (like `<Embed>` on an embed page). Used by
|
|
5
|
+
`defineChartElements()`; you should not need it directly.
|
|
6
|
+
-->
|
|
7
|
+
<script lang="ts">
|
|
8
|
+
import type { Component } from 'svelte';
|
|
9
|
+
import type { LocaleCode } from '../locale/index.js';
|
|
10
|
+
import type { Theme } from '../styles/types.js';
|
|
11
|
+
import { setEmbedded } from '../core/context.js';
|
|
12
|
+
import type { ElementChartProps } from './element.js';
|
|
13
|
+
|
|
14
|
+
interface Props {
|
|
15
|
+
/** The chart to render. */
|
|
16
|
+
component: Component<ElementChartProps>;
|
|
17
|
+
style: Theme;
|
|
18
|
+
locale: LocaleCode;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let { component: ChartComponent, style, locale }: Props = $props();
|
|
22
|
+
setEmbedded();
|
|
23
|
+
</script>
|
|
24
|
+
|
|
25
|
+
<ChartComponent {style} {locale} medium="web" />
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Component } from 'svelte';
|
|
2
|
+
import type { LocaleCode } from '../locale/index.js';
|
|
3
|
+
import type { Theme } from '../styles/types.js';
|
|
4
|
+
import type { ElementChartProps } from './element.js';
|
|
5
|
+
interface Props {
|
|
6
|
+
/** The chart to render. */
|
|
7
|
+
component: Component<ElementChartProps>;
|
|
8
|
+
style: Theme;
|
|
9
|
+
locale: LocaleCode;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* What `<mozaic-chart>` mounts in its shadow root: the chart on its own, marked as embedded so it
|
|
13
|
+
* leaves out the controls meant for the chart's own site (like `<Embed>` on an embed page). Used by
|
|
14
|
+
* `defineChartElements()`; you should not need it directly.
|
|
15
|
+
*/
|
|
16
|
+
declare const ElementChart: Component<Props, {}, "">;
|
|
17
|
+
type ElementChart = ReturnType<typeof ElementChart>;
|
|
18
|
+
export default ElementChart;
|
package/dist/embed/code.d.ts
CHANGED
|
@@ -16,3 +16,23 @@ export interface ChartEmbed {
|
|
|
16
16
|
/** The iframe's height before the script resizes it; defaults to the chart's height where it is shown. */
|
|
17
17
|
height?: number;
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* The HTML snippet for the web component embed (`<mozaic-chart>`), the optional alternative to the
|
|
21
|
+
* iframe for sites that allow scripts. Its children (a link to the embed page, when `href` is given)
|
|
22
|
+
* show where the script does not run.
|
|
23
|
+
*/
|
|
24
|
+
export declare function elementCode(options: {
|
|
25
|
+
/** The project's name, as registered by `defineChartElements()`. */
|
|
26
|
+
project: string;
|
|
27
|
+
/** The chart's slug. */
|
|
28
|
+
chart: string;
|
|
29
|
+
locale?: string;
|
|
30
|
+
/** A theme name, for projects that register several. */
|
|
31
|
+
theme?: string;
|
|
32
|
+
/** The project's element script (`element.js`). */
|
|
33
|
+
scriptSrc: string;
|
|
34
|
+
/** The chart's title, the text of the fallback link. */
|
|
35
|
+
title: string;
|
|
36
|
+
/** The chart's embed page, linked from the fallback for readers without JavaScript. */
|
|
37
|
+
href?: string;
|
|
38
|
+
}): string;
|
package/dist/embed/code.js
CHANGED
|
@@ -7,3 +7,21 @@ export function embedCode(options) {
|
|
|
7
7
|
const iframe = `<iframe src="${attr(src)}" title="${attr(title)}" data-mozaic-embed scrolling="no" loading="lazy" height="${height}" style="width:100%;border:0;"></iframe>`;
|
|
8
8
|
return scriptSrc ? `${iframe}\n<script src="${attr(scriptSrc)}" async></script>` : iframe;
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* The HTML snippet for the web component embed (`<mozaic-chart>`), the optional alternative to the
|
|
12
|
+
* iframe for sites that allow scripts. Its children (a link to the embed page, when `href` is given)
|
|
13
|
+
* show where the script does not run.
|
|
14
|
+
*/
|
|
15
|
+
export function elementCode(options) {
|
|
16
|
+
const { project, chart, locale, theme, scriptSrc, title, href } = options;
|
|
17
|
+
const attrs = [`project="${attr(project)}"`, `chart="${attr(chart)}"`];
|
|
18
|
+
if (locale)
|
|
19
|
+
attrs.push(`locale="${attr(locale)}"`);
|
|
20
|
+
if (theme)
|
|
21
|
+
attrs.push(`theme="${attr(theme)}"`);
|
|
22
|
+
const fallback = href ? `<a href="${attr(href)}">${text(title)}</a>` : '';
|
|
23
|
+
return `<mozaic-chart ${attrs.join(' ')}>${fallback}</mozaic-chart>\n<script src="${attr(scriptSrc)}" defer></script>`;
|
|
24
|
+
}
|
|
25
|
+
function text(value) {
|
|
26
|
+
return value.replace(/&/g, '&').replace(/</g, '<');
|
|
27
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Component } from 'svelte';
|
|
2
|
+
import type { LocaleCode } from '../locale/index.js';
|
|
3
|
+
import type { Medium, Theme } from '../styles/types.js';
|
|
4
|
+
/**
|
|
5
|
+
* The web component embed: an optional alternative to the iframe for sites that allow scripts.
|
|
6
|
+
*
|
|
7
|
+
* A project builds one classic script (`element.js`) that calls `defineChartElements()`. Host pages
|
|
8
|
+
* then place charts with `<mozaic-chart project chart locale>`, and each one renders into its own
|
|
9
|
+
* Shadow DOM, so the page's CSS stays out and the chart's CSS stays in.
|
|
10
|
+
*
|
|
11
|
+
* Several projects can share a page: whichever script loads first defines `<mozaic-chart>`, and
|
|
12
|
+
* every script adds its charts to a shared registry on `window`. The registry and the element talk
|
|
13
|
+
* only through the small `ElementProject` interface below, so bundles built with different mozaic
|
|
14
|
+
* versions work together. Keep it backward compatible.
|
|
15
|
+
*/
|
|
16
|
+
/** The custom element's tag name. */
|
|
17
|
+
export declare const ELEMENT_TAG = "mozaic-chart";
|
|
18
|
+
/** Props every chart rendered by the element accepts (the same as on an embed page). */
|
|
19
|
+
export interface ElementChartProps {
|
|
20
|
+
style: Theme;
|
|
21
|
+
locale: LocaleCode;
|
|
22
|
+
medium?: Medium;
|
|
23
|
+
width?: number;
|
|
24
|
+
}
|
|
25
|
+
/** One chart a project's element can show. */
|
|
26
|
+
export interface ElementChartEntry {
|
|
27
|
+
/** Matches the element's `chart` attribute; use the same slug as the embed page. */
|
|
28
|
+
slug: string;
|
|
29
|
+
component: Component<ElementChartProps>;
|
|
30
|
+
}
|
|
31
|
+
export interface ChartElementsOptions {
|
|
32
|
+
/** Matches the element's `project` attribute; use `config.project`. Must be unique among projects on a page. */
|
|
33
|
+
project: string;
|
|
34
|
+
charts: readonly ElementChartEntry[];
|
|
35
|
+
/** House style. Several are picked between by the element's `theme` attribute (the theme's `name`); the first is the default. */
|
|
36
|
+
theme: Theme | readonly Theme[];
|
|
37
|
+
/** Languages the element accepts in its `locale` attribute. The first is the default; defaults to the theme's. */
|
|
38
|
+
locales?: readonly LocaleCode[];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Register a project's charts and define `<mozaic-chart>` if no other script has yet. Call it once,
|
|
42
|
+
* at the top level of the project's element entry (`src/element.ts`); it does nothing on the server.
|
|
43
|
+
*/
|
|
44
|
+
export declare function defineChartElements(options: ChartElementsOptions): void;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { mount, unmount } from 'svelte';
|
|
2
|
+
import ElementChart from './ElementChart.svelte';
|
|
3
|
+
/**
|
|
4
|
+
* The web component embed: an optional alternative to the iframe for sites that allow scripts.
|
|
5
|
+
*
|
|
6
|
+
* A project builds one classic script (`element.js`) that calls `defineChartElements()`. Host pages
|
|
7
|
+
* then place charts with `<mozaic-chart project chart locale>`, and each one renders into its own
|
|
8
|
+
* Shadow DOM, so the page's CSS stays out and the chart's CSS stays in.
|
|
9
|
+
*
|
|
10
|
+
* Several projects can share a page: whichever script loads first defines `<mozaic-chart>`, and
|
|
11
|
+
* every script adds its charts to a shared registry on `window`. The registry and the element talk
|
|
12
|
+
* only through the small `ElementProject` interface below, so bundles built with different mozaic
|
|
13
|
+
* versions work together. Keep it backward compatible.
|
|
14
|
+
*/
|
|
15
|
+
/** The custom element's tag name. */
|
|
16
|
+
export const ELEMENT_TAG = 'mozaic-chart';
|
|
17
|
+
const REGISTER_EVENT = 'mozaic:element-register';
|
|
18
|
+
/**
|
|
19
|
+
* `rem` in a shadow root is the host page's root font size (often 10px or 62.5%), not the reader's default
|
|
20
|
+
* as in an iframe. The element build rewrites `rem` in component CSS to `calc(n * var(--mz-rem, 16px))`
|
|
21
|
+
* (see `elementConfig()`), and `withRemVar()` does the same to theme tokens. `--mz-rem` is registered as a
|
|
22
|
+
* length, so `1em` on `:host` (whose font size `all: initial` resets to the reader's default) becomes px there
|
|
23
|
+
* and is inherited as px, without compounding. If registering fails, the 16px fallback applies.
|
|
24
|
+
*/
|
|
25
|
+
const REM_VAR = '--mz-rem';
|
|
26
|
+
let remRegistered;
|
|
27
|
+
function registerRem() {
|
|
28
|
+
if (remRegistered !== undefined)
|
|
29
|
+
return remRegistered;
|
|
30
|
+
try {
|
|
31
|
+
CSS.registerProperty({ name: REM_VAR, syntax: '<length>', inherits: true, initialValue: '16px' });
|
|
32
|
+
remRegistered = true;
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
// Already registered by another project's script on the page.
|
|
36
|
+
remRegistered = error instanceof DOMException && error.name === 'InvalidModificationError';
|
|
37
|
+
}
|
|
38
|
+
return remRegistered;
|
|
39
|
+
}
|
|
40
|
+
/** Replace `rem` lengths with the element's `--mz-rem`. */
|
|
41
|
+
function remToVar(value) {
|
|
42
|
+
return value.replace(/(-?\d*\.?\d+)rem\b/g, `calc($1 * var(${REM_VAR}, 16px))`);
|
|
43
|
+
}
|
|
44
|
+
function withRemVar(theme) {
|
|
45
|
+
const convert = (tokens) => Object.fromEntries(Object.entries(tokens).map(([k, v]) => [k, typeof v === 'string' ? remToVar(v) : v]));
|
|
46
|
+
return { ...theme, tokens: convert(theme.tokens), print: { ...theme.print, tokens: convert(theme.print.tokens) } };
|
|
47
|
+
}
|
|
48
|
+
/** Inherited styles from the host page stop at the element; `:host` is the only box the page can style. */
|
|
49
|
+
function hostCss() {
|
|
50
|
+
const rem = registerRem() ? `${REM_VAR}:1em;` : '';
|
|
51
|
+
return `:host{all:initial;display:block;text-align:start;${rem}}:host([hidden]){display:none}`;
|
|
52
|
+
}
|
|
53
|
+
function registry() {
|
|
54
|
+
const w = window;
|
|
55
|
+
return (w.__mozaicElements ??= { projects: {} });
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Register a project's charts and define `<mozaic-chart>` if no other script has yet. Call it once,
|
|
59
|
+
* at the top level of the project's element entry (`src/element.ts`); it does nothing on the server.
|
|
60
|
+
*/
|
|
61
|
+
export function defineChartElements(options) {
|
|
62
|
+
if (typeof window === 'undefined' || typeof customElements === 'undefined')
|
|
63
|
+
return;
|
|
64
|
+
const themes = (Array.isArray(options.theme) ? options.theme : [options.theme]).map(withRemVar);
|
|
65
|
+
const locales = options.locales?.length ? options.locales : [themes[0].defaultLocale];
|
|
66
|
+
const charts = new Map(options.charts.map((c) => [c.slug, c.component]));
|
|
67
|
+
const project = {
|
|
68
|
+
mount(root, attributes) {
|
|
69
|
+
const component = charts.get(attributes.chart);
|
|
70
|
+
if (!component) {
|
|
71
|
+
console.warn(`mozaic: project "${options.project}" has no chart "${attributes.chart}"`);
|
|
72
|
+
// Show the element's fallback content (its children) instead.
|
|
73
|
+
root.replaceChildren(document.createElement('slot'));
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
const style = themes.find((t) => t.name === attributes.theme) ?? themes[0];
|
|
77
|
+
let locale = locales[0];
|
|
78
|
+
if (attributes.locale) {
|
|
79
|
+
if (locales.includes(attributes.locale))
|
|
80
|
+
locale = attributes.locale;
|
|
81
|
+
else
|
|
82
|
+
console.warn(`mozaic: chart "${attributes.chart}" has no locale "${attributes.locale}"; using "${locale}"`);
|
|
83
|
+
}
|
|
84
|
+
const host = document.createElement('style');
|
|
85
|
+
host.textContent = hostCss();
|
|
86
|
+
root.replaceChildren(host);
|
|
87
|
+
const app = mount(ElementChart, { target: root, props: { component, style, locale } });
|
|
88
|
+
return () => {
|
|
89
|
+
void unmount(app);
|
|
90
|
+
root.replaceChildren();
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const shared = registry();
|
|
95
|
+
// The first script for a project wins: a page that includes it twice keeps the charts it already drew.
|
|
96
|
+
if (!shared.projects[options.project]) {
|
|
97
|
+
shared.projects[options.project] = project;
|
|
98
|
+
window.dispatchEvent(new CustomEvent(REGISTER_EVENT, { detail: options.project }));
|
|
99
|
+
}
|
|
100
|
+
if (!customElements.get(ELEMENT_TAG))
|
|
101
|
+
customElements.define(ELEMENT_TAG, createElementClass());
|
|
102
|
+
}
|
|
103
|
+
function createElementClass() {
|
|
104
|
+
return class MozaicChartElement extends HTMLElement {
|
|
105
|
+
static observedAttributes = ['project', 'chart', 'locale', 'theme'];
|
|
106
|
+
#stop;
|
|
107
|
+
#waiting = false;
|
|
108
|
+
connectedCallback() {
|
|
109
|
+
this.#render();
|
|
110
|
+
}
|
|
111
|
+
disconnectedCallback() {
|
|
112
|
+
this.#clear();
|
|
113
|
+
this.#wait(false);
|
|
114
|
+
}
|
|
115
|
+
attributeChangedCallback() {
|
|
116
|
+
if (this.isConnected)
|
|
117
|
+
this.#render();
|
|
118
|
+
}
|
|
119
|
+
#onRegister = (event) => {
|
|
120
|
+
if (event.detail === this.getAttribute('project'))
|
|
121
|
+
this.#render();
|
|
122
|
+
};
|
|
123
|
+
#wait(on) {
|
|
124
|
+
if (on === this.#waiting)
|
|
125
|
+
return;
|
|
126
|
+
this.#waiting = on;
|
|
127
|
+
if (on)
|
|
128
|
+
window.addEventListener(REGISTER_EVENT, this.#onRegister);
|
|
129
|
+
else
|
|
130
|
+
window.removeEventListener(REGISTER_EVENT, this.#onRegister);
|
|
131
|
+
}
|
|
132
|
+
#clear() {
|
|
133
|
+
this.#stop?.();
|
|
134
|
+
this.#stop = undefined;
|
|
135
|
+
}
|
|
136
|
+
#render() {
|
|
137
|
+
this.#clear();
|
|
138
|
+
const name = this.getAttribute('project');
|
|
139
|
+
const chart = this.getAttribute('chart');
|
|
140
|
+
if (!name || !chart)
|
|
141
|
+
return;
|
|
142
|
+
const project = registry().projects[name];
|
|
143
|
+
// Its script has not run yet (or comes from another project's bundle): draw when it registers.
|
|
144
|
+
if (!project)
|
|
145
|
+
return this.#wait(true);
|
|
146
|
+
this.#wait(false);
|
|
147
|
+
const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
|
|
148
|
+
this.#stop =
|
|
149
|
+
project.mount(root, { chart, locale: this.getAttribute('locale'), theme: this.getAttribute('theme') }) ??
|
|
150
|
+
undefined;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
package/dist/embed/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { default as Embed } from './Embed.svelte';
|
|
2
2
|
export { observeHeight, postHeight, type ResizeMessage } from './resize.js';
|
|
3
3
|
export { hostScript } from './host.js';
|
|
4
|
-
export { embedCode, type ChartEmbed } from './code.js';
|
|
4
|
+
export { embedCode, elementCode, type ChartEmbed } from './code.js';
|
|
5
5
|
export { useEmbedParams } from './params.svelte.js';
|
|
6
|
+
export { defineChartElements, ELEMENT_TAG, type ChartElementsOptions, type ElementChartEntry, type ElementChartProps } from './element.js';
|
|
6
7
|
export type { EmbedEntry, EmbedManifest } from './manifest.js';
|
package/dist/embed/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { default as Embed } from './Embed.svelte';
|
|
2
2
|
export { observeHeight, postHeight } from './resize.js';
|
|
3
3
|
export { hostScript } from './host.js';
|
|
4
|
-
export { embedCode } from './code.js';
|
|
4
|
+
export { embedCode, elementCode } from './code.js';
|
|
5
5
|
export { useEmbedParams } from './params.svelte.js';
|
|
6
|
+
export { defineChartElements, ELEMENT_TAG } from './element.js';
|
|
@@ -48,7 +48,11 @@ chart as PNG or SVG. Hidden in print and in exports; inside `<Embed>` only the d
|
|
|
48
48
|
);
|
|
49
49
|
|
|
50
50
|
const figure = () => tools?.closest('.mz-chart') as HTMLElement | null;
|
|
51
|
-
|
|
51
|
+
// The chart's own root: the document, or a shadow root in the web component embed.
|
|
52
|
+
const title = () =>
|
|
53
|
+
((tools?.getRootNode() ?? document) as Document | ShadowRoot)
|
|
54
|
+
.getElementById(chart.ids.title)
|
|
55
|
+
?.textContent?.trim() ?? '';
|
|
52
56
|
|
|
53
57
|
function toggle(tool: 'table' | 'embed' | 'download') {
|
|
54
58
|
open = open === tool ? null : tool;
|
|
@@ -27,7 +27,8 @@ export function touchHold(root, clear) {
|
|
|
27
27
|
if (event.pointerType === 'touch' && !cancelled && typeof document !== 'undefined') {
|
|
28
28
|
const outside = (e) => {
|
|
29
29
|
const el = root();
|
|
30
|
-
|
|
30
|
+
// composedPath() sees through shadow roots (the web component embed), where e.target is the host element.
|
|
31
|
+
if (el && e.composedPath().includes(el))
|
|
31
32
|
return;
|
|
32
33
|
release();
|
|
33
34
|
clear(e);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@samizdata/mozaic",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.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",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"src/lib/recipes",
|
|
21
21
|
"cli/bin",
|
|
22
22
|
"cli/src",
|
|
23
|
+
"vite",
|
|
23
24
|
"!dist/**/*.test.*",
|
|
24
25
|
"!dist/**/*.spec.*"
|
|
25
26
|
],
|
|
@@ -108,10 +109,24 @@
|
|
|
108
109
|
"types": "./cli/src/index.d.ts",
|
|
109
110
|
"default": "./cli/src/index.js"
|
|
110
111
|
},
|
|
112
|
+
"./vite": {
|
|
113
|
+
"types": "./vite/index.d.ts",
|
|
114
|
+
"default": "./vite/index.js"
|
|
115
|
+
},
|
|
111
116
|
"./package.json": "./package.json"
|
|
112
117
|
},
|
|
113
118
|
"peerDependencies": {
|
|
114
|
-
"svelte": "^5.57.0"
|
|
119
|
+
"svelte": "^5.57.0",
|
|
120
|
+
"@sveltejs/vite-plugin-svelte": ">=6",
|
|
121
|
+
"vite": ">=7"
|
|
122
|
+
},
|
|
123
|
+
"peerDependenciesMeta": {
|
|
124
|
+
"@sveltejs/vite-plugin-svelte": {
|
|
125
|
+
"optional": true
|
|
126
|
+
},
|
|
127
|
+
"vite": {
|
|
128
|
+
"optional": true
|
|
129
|
+
}
|
|
115
130
|
},
|
|
116
131
|
"dependencies": {
|
|
117
132
|
"d3-array": "^3.2.4",
|
|
@@ -169,7 +184,7 @@
|
|
|
169
184
|
"scripts": {
|
|
170
185
|
"dev": "vite dev",
|
|
171
186
|
"package": "svelte-kit sync && svelte-package && publint",
|
|
172
|
-
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && tsc -p cli/jsconfig.json",
|
|
187
|
+
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && tsc -p cli/jsconfig.json && tsc -p vite/jsconfig.json",
|
|
173
188
|
"test:unit": "vitest",
|
|
174
189
|
"test": "vitest --run",
|
|
175
190
|
"test:coverage": "vitest --run --coverage"
|
package/vite/index.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { UserConfig } from 'vite';
|
|
2
|
+
|
|
3
|
+
export interface ElementConfigOptions {
|
|
4
|
+
/** The entry that calls `defineChartElements()`. Default `src/element.ts`. */
|
|
5
|
+
entry?: string;
|
|
6
|
+
/** Where to write the script: the SvelteKit build folder. Default `build`. */
|
|
7
|
+
outDir?: string;
|
|
8
|
+
/** Default `element.js`. */
|
|
9
|
+
fileName?: string;
|
|
10
|
+
/** Extra resolve conditions, before the defaults (`module`, `browser`, `production`). */
|
|
11
|
+
conditions?: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Vite config that builds a project's web component embed (`element.js`). */
|
|
15
|
+
export function elementConfig(options?: ElementConfigOptions): UserConfig;
|
|
16
|
+
|
|
17
|
+
/** `1.5rem` → `calc(1.5 * var(--mz-rem, 16px))`, as the element build does to component CSS. */
|
|
18
|
+
export function remToVar(css: string): string;
|
package/vite/index.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Build helpers for projects (Node only): `import { elementConfig } from '@samizdata/mozaic/vite'`.
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `1.5rem` → `calc(1.5 * var(--mz-rem, 16px))`. Keep in step with `remToVar` in src/lib/embed/element.ts.
|
|
7
|
+
* @param {string} css
|
|
8
|
+
*/
|
|
9
|
+
export function remToVar(css) {
|
|
10
|
+
return css.replace(/(-?\d*\.?\d+)rem\b/g, 'calc($1 * var(--mz-rem, 16px))');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Vite config that builds a project's web component embed: one classic script (`element.js`, an
|
|
15
|
+
* IIFE, so host pages need no CORS) with the project's charts, Svelte and mozaic in it. Component
|
|
16
|
+
* CSS is injected into each chart's shadow root instead of emitted as a file. Run it after the
|
|
17
|
+
* SvelteKit build (which empties `outDir`): `vite build && vite build -c vite.element.config.ts`.
|
|
18
|
+
*
|
|
19
|
+
* @param {import('./index.d.ts').ElementConfigOptions} [options]
|
|
20
|
+
* @returns {import('vite').UserConfig}
|
|
21
|
+
*/
|
|
22
|
+
export function elementConfig(options = {}) {
|
|
23
|
+
const { entry = 'src/element.ts', outDir = 'build', fileName = 'element.js', conditions = [] } = options;
|
|
24
|
+
return {
|
|
25
|
+
plugins: [
|
|
26
|
+
svelte({
|
|
27
|
+
// Inject each component's CSS where it mounts (the shadow root), not into a .css file.
|
|
28
|
+
emitCss: false,
|
|
29
|
+
// In a shadow root `rem` is the host page's root size: use the element's `--mz-rem` instead (see element.ts).
|
|
30
|
+
preprocess: { style: ({ content }) => ({ code: remToVar(content) }) },
|
|
31
|
+
compilerOptions: {
|
|
32
|
+
css: 'injected',
|
|
33
|
+
// Runes for the project, the library's own setting for dependencies (as in the SvelteKit config).
|
|
34
|
+
runes: ({ filename }) => (filename.split(/[/\\]/).includes('node_modules') ? undefined : true)
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
],
|
|
38
|
+
resolve: {
|
|
39
|
+
alias: { $lib: resolve('src/lib') },
|
|
40
|
+
conditions: [...conditions, 'module', 'browser', 'production']
|
|
41
|
+
},
|
|
42
|
+
define: { 'process.env.NODE_ENV': '"production"' },
|
|
43
|
+
publicDir: false,
|
|
44
|
+
build: {
|
|
45
|
+
outDir,
|
|
46
|
+
// The SvelteKit build is already there.
|
|
47
|
+
emptyOutDir: false,
|
|
48
|
+
copyPublicDir: false,
|
|
49
|
+
lib: { entry, formats: ['iife'], name: 'mozaicElement', fileName: () => fileName }
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|