@diagrammo/dgmo 0.44.0 → 0.45.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.
@@ -0,0 +1,15 @@
1
+ const HTML_ENTITIES: Record<string, string> = {
2
+ '&': '&amp;',
3
+ '<': '&lt;',
4
+ '>': '&gt;',
5
+ '"': '&quot;',
6
+ "'": '&#39;',
7
+ };
8
+
9
+ export function escapeHtml(s: string): string {
10
+ return s.replace(/[&<>"']/g, (ch) => HTML_ENTITIES[ch] ?? ch);
11
+ }
12
+
13
+ export function escapeAttr(s: string): string {
14
+ return s.replace(/[&<>"']/g, (ch) => HTML_ENTITIES[ch] ?? ch);
15
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Standard DGMO embed block (BL-114) — the ONE canonical
3
+ * "diagram + source chrome" HTML builder shared by every embed surface:
4
+ * remark-dgmo (and through it the astro/docusaurus/fumadocs/nextra/vitepress
5
+ * wrappers), the `/auto` script-tag drop-in, `<dgmo-diagram>`, dgmo-mcp HTML
6
+ * reports, the marketing site, and the Obsidian plugin.
7
+ *
8
+ * Chrome contract (user-approved 2026-07-05): the diagram is the star. A slim
9
+ * icon toolbar sits in a reserved row below the SVG, invisible until the
10
+ * block is hovered/focused or the source is open. Three wordless icon
11
+ * buttons — `</>` toggles the hidden source panel, copy, open-in-editor. No
12
+ * disclosure triangle, no text labels. The toolbar IS the <summary> of a
13
+ * native <details>, so show/hide works with zero JavaScript; copy needs a
14
+ * small delegated click handler (remark-dgmo's `bindDgmo` is the reference).
15
+ *
16
+ * Markup vocabulary: `figure.dgmo` (`--diagram`/`--showcase`/`--error`),
17
+ * `.dgmo-light`/`.dgmo-dark` (dual color-mode) or `.dgmo-svg` (single),
18
+ * `details.dgmo-source-wrap > summary.dgmo-toolbar`, `.dgmo-source-inner`,
19
+ * `pre.dgmo-pre > span.dgmo-code` with `.dgmo-tok-<role>` token spans. While
20
+ * the source is open the wrapper gets one shared frame (`:has()` rule) so
21
+ * diagram + code read as a single unit. No visible caption — `title` becomes
22
+ * the wrapper's aria-label. Styles ship as `BLOCK_CSS` / `dist/block.css`.
23
+ */
24
+
25
+ import { render } from '../render';
26
+ import { encodeDiagramUrl } from '../sharing';
27
+ import { resolvePaletteOrFallback } from '../palettes';
28
+ import { highlightDgmo } from '../editor/highlight-api';
29
+ import { normalizeSvgForEmbed } from '../utils/svg-embed';
30
+ import { escapeHtml, escapeAttr } from './escape';
31
+
32
+ export { BLOCK_CSS } from './css';
33
+
34
+ /** Default hosted editor used by "Open in editor" links. */
35
+ export const EDITOR_BASE_URL = 'https://online.diagrammo.app';
36
+
37
+ export type BlockMode = 'diagram' | 'showcase';
38
+
39
+ /**
40
+ * Color-mode strategy for the emitted SVG(s).
41
+ * - `auto` — render twice (light + dark) and let CSS flip visibility.
42
+ * - `light` / `dark` / `transparent` — single render with that theme.
43
+ */
44
+ export type BlockColorMode = 'auto' | 'light' | 'dark' | 'transparent';
45
+
46
+ export interface DgmoBlockOptions {
47
+ /** `diagram` (default): SVG only. `showcase`: SVG + source chrome. */
48
+ mode?: BlockMode;
49
+ /** Palette name. Default `slate`; unknown names warn + fall back. */
50
+ palette?: string;
51
+ /** Default `auto` (dual light/dark render). */
52
+ colorMode?: BlockColorMode;
53
+ /** Default: true in showcase mode, false in diagram mode. */
54
+ showSource?: boolean;
55
+ /** Default: true in showcase mode, false in diagram mode. */
56
+ showCopy?: boolean;
57
+ /** Default: true in showcase mode, false in diagram mode. */
58
+ showOpenInEditor?: boolean;
59
+ /** Base URL for the open-in-editor link. Default: online.diagrammo.app. */
60
+ editorBaseUrl?: string;
61
+ /** Outer wrapper element. Default `figure`. */
62
+ wrapper?: 'figure' | 'div';
63
+ /** Base class for the wrapper (styling hook). Default `dgmo`. */
64
+ className?: string;
65
+ /** Extra classes appended to every emitted wrapper (compat shims). */
66
+ legacyClassNames?: string[];
67
+ /**
68
+ * Accessible name for the block (`aria-label` on the wrapper). NOT rendered
69
+ * visually — the chart's visible title belongs in the DGMO source itself.
70
+ */
71
+ title?: string;
72
+ /** Receives palette-fallback warnings. Default: console.warn. */
73
+ onWarn?: (message: string) => void;
74
+ }
75
+
76
+ type ResolvedBlockOptions = Required<
77
+ Omit<DgmoBlockOptions, 'title' | 'onWarn'>
78
+ > & {
79
+ title: string | undefined;
80
+ onWarn: (message: string) => void;
81
+ };
82
+
83
+ export interface DgmoBlockResult {
84
+ html: string;
85
+ diagnostics: Array<{ message: string; line?: number; severity?: string }>;
86
+ }
87
+
88
+ function resolveBlockOptions(opts: DgmoBlockOptions): ResolvedBlockOptions {
89
+ const mode: BlockMode = opts.mode ?? 'diagram';
90
+ const showcase = mode === 'showcase';
91
+ return {
92
+ mode,
93
+ palette: opts.palette ?? 'slate',
94
+ colorMode: opts.colorMode ?? 'auto',
95
+ showSource: opts.showSource ?? showcase,
96
+ showCopy: opts.showCopy ?? showcase,
97
+ showOpenInEditor: opts.showOpenInEditor ?? showcase,
98
+ editorBaseUrl: opts.editorBaseUrl ?? EDITOR_BASE_URL,
99
+ wrapper: opts.wrapper ?? 'figure',
100
+ className: opts.className ?? 'dgmo',
101
+ legacyClassNames: opts.legacyClassNames ?? [],
102
+ title: opts.title,
103
+
104
+ onWarn: opts.onWarn ?? ((message) => console.warn(message)),
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Render one ```dgmo source block to the standard embed HTML. Async because
110
+ * it runs the full dgmo render pipeline (once per color mode).
111
+ *
112
+ * Render errors are NOT caught here — callers decide between throwing,
113
+ * `errorBlockHtml()`, or their own fallback.
114
+ */
115
+ export async function renderDgmoBlock(
116
+ source: string,
117
+ options: DgmoBlockOptions = {}
118
+ ): Promise<DgmoBlockResult> {
119
+ const opts = resolveBlockOptions(options);
120
+ const trimmed = source.trim();
121
+ // Resolve-with-fallback so unknown names warn here (render() itself falls
122
+ // back silently); render() takes the palette by NAME, so pass the id.
123
+ const paletteId = resolvePaletteOrFallback(opts.palette, opts.onWarn).id;
124
+ const diagnostics: DgmoBlockResult['diagnostics'] = [];
125
+
126
+ let svgsHtml: string;
127
+ if (opts.colorMode === 'auto') {
128
+ const [light, dark] = await Promise.all([
129
+ render(trimmed, { palette: paletteId, theme: 'light' }),
130
+ render(trimmed, { palette: paletteId, theme: 'dark' }),
131
+ ]);
132
+ diagnostics.push(...light.diagnostics, ...dark.diagnostics);
133
+ svgsHtml =
134
+ `<div class="${escapeAttr(innerClasses(opts, 'dgmo-light'))}">${normalizeSvgForEmbed(light.svg)}</div>` +
135
+ `<div class="${escapeAttr(innerClasses(opts, 'dgmo-dark'))}">${normalizeSvgForEmbed(dark.svg)}</div>`;
136
+ } else {
137
+ const result = await render(trimmed, {
138
+ palette: paletteId,
139
+ theme: opts.colorMode,
140
+ });
141
+ diagnostics.push(...result.diagnostics);
142
+ svgsHtml = `<div class="${escapeAttr(innerClasses(opts, 'dgmo-svg'))}">${normalizeSvgForEmbed(result.svg)}</div>`;
143
+ }
144
+
145
+ return { html: assembleBlock(trimmed, svgsHtml, opts), diagnostics };
146
+ }
147
+
148
+ /**
149
+ * Assemble the standard block around already-rendered SVG markup. Exposed for
150
+ * surfaces that render through their own pipeline (e.g. dgmo-mcp's
151
+ * renderPipeline) but must emit the canonical chrome. `svgsHtml` must be the
152
+ * `.dgmo-light`+`.dgmo-dark` (or `.dgmo-svg`) wrapper divs.
153
+ */
154
+ export function buildDgmoBlockHtml(
155
+ source: string,
156
+ svgsHtml: string,
157
+ options: DgmoBlockOptions = {}
158
+ ): string {
159
+ return assembleBlock(source.trim(), svgsHtml, resolveBlockOptions(options));
160
+ }
161
+
162
+ /**
163
+ * Standard error card for a block that failed to parse/render. Same shape on
164
+ * every surface: `.dgmo--error` with `role="alert"`, message + offending
165
+ * source.
166
+ */
167
+ export function errorBlockHtml(
168
+ err: unknown,
169
+ source: string,
170
+ options: Pick<DgmoBlockOptions, 'className' | 'legacyClassNames'> = {}
171
+ ): string {
172
+ const msg =
173
+ err instanceof Error ? err.message : 'Failed to render dgmo block.';
174
+ const base = options.className ?? 'dgmo';
175
+ const legacy = (options.legacyClassNames ?? []).join(' ');
176
+ const cls = legacy
177
+ ? `${base} ${legacy} ${base}--error`
178
+ : `${base} ${base}--error`;
179
+ return (
180
+ `<div class="${escapeAttr(cls)}" role="alert">` +
181
+ `<strong>dgmo render error:</strong> ${escapeHtml(msg)}` +
182
+ `<pre>${escapeHtml(source)}</pre></div>`
183
+ );
184
+ }
185
+
186
+ // ============================================================
187
+ // Internals
188
+ // ============================================================
189
+
190
+ function wrapperClasses(
191
+ opts: ResolvedBlockOptions,
192
+ variant: 'diagram' | 'showcase'
193
+ ): string {
194
+ const base = `${opts.className} ${opts.className}--${variant}`;
195
+ const legacy = opts.legacyClassNames.join(' ');
196
+ return legacy ? `${base} ${legacy}` : base;
197
+ }
198
+
199
+ function innerClasses(opts: ResolvedBlockOptions, primary: string): string {
200
+ const legacy = opts.legacyClassNames.join(' ');
201
+ return legacy ? `${primary} ${legacy}` : primary;
202
+ }
203
+
204
+ function assembleBlock(
205
+ source: string,
206
+ svgsHtml: string,
207
+ opts: ResolvedBlockOptions
208
+ ): string {
209
+ const Wrapper = opts.wrapper;
210
+ const showcase = opts.mode === 'showcase';
211
+ const variant = showcase ? 'showcase' : 'diagram';
212
+
213
+ const ariaAttr = opts.title ? ` aria-label="${escapeAttr(opts.title)}"` : '';
214
+
215
+ const sourceHtml = showcase ? sourceDisclosure(source, opts) : '';
216
+
217
+ return (
218
+ `<${Wrapper} class="${escapeAttr(wrapperClasses(opts, variant))}"${ariaAttr}>` +
219
+ svgsHtml +
220
+ sourceHtml +
221
+ `</${Wrapper}>`
222
+ );
223
+ }
224
+
225
+ // ----- icon SVGs (static author-controlled markup) -----
226
+ const CODE_ICON = `<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m10 4.5 4 3.5-4 3.5"/><path d="m6 4.5-4 3.5 4 3.5"/></svg>`;
227
+ const COPY_ICON = `<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5.5" y="5.5" width="8" height="8" rx="1.5"/><path d="M10.5 5.5V3a1.5 1.5 0 0 0-1.5-1.5H3A1.5 1.5 0 0 0 1.5 3v6A1.5 1.5 0 0 0 3 10.5h2.5"/></svg>`;
228
+ const EXTERNAL_ICON = `<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.5 2.5h4v4"/><path d="M13.5 2.5 7 9"/><path d="M12.5 9.5v3a1 1 0 0 1-1 1h-8a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1h3"/></svg>`;
229
+
230
+ /**
231
+ * The hidden source panel plus its toolbar. The <summary> is the toolbar row;
232
+ * its default click behavior is the source toggle, so no JS is needed for
233
+ * show/hide. The `</>` span deliberately does NOT get the `.dgmo-toolbar-btn`
234
+ * class — client copy/open handlers preventDefault on `.dgmo-toolbar-btn`
235
+ * inside a <summary> (to not also toggle), and the toggle must keep the
236
+ * default.
237
+ */
238
+ function sourceDisclosure(source: string, opts: ResolvedBlockOptions): string {
239
+ if (!opts.showSource) return '';
240
+
241
+ const toggle = `<span class="dgmo-toggle" title="View DGMO source">${CODE_ICON}</span>`;
242
+
243
+ const copyButton = opts.showCopy
244
+ ? `<button type="button" class="dgmo-toolbar-btn dgmo-copy" aria-label="Copy DGMO source" title="Copy source" data-dgmo-source="${escapeAttr(source)}">${COPY_ICON}</button>`
245
+ : '';
246
+
247
+ let openButton = '';
248
+ if (opts.showOpenInEditor) {
249
+ const encoded = encodeDiagramUrl(source, { baseUrl: opts.editorBaseUrl });
250
+ // `too-large` (or any encode failure) → omit the link; copy remains.
251
+ if (encoded.url) {
252
+ openButton = `<a href="${escapeAttr(encoded.url)}" target="_blank" rel="noopener noreferrer" class="dgmo-toolbar-btn dgmo-open" aria-label="Open in online editor" title="Open in online editor">${EXTERNAL_ICON}</a>`;
253
+ }
254
+ }
255
+
256
+ const sourceHtml = highlightedSource(source);
257
+
258
+ return (
259
+ `<details class="dgmo-source-wrap">` +
260
+ `<summary class="dgmo-toolbar" aria-label="View DGMO source">${toggle}${copyButton}${openButton}</summary>` +
261
+ `<div class="dgmo-source-inner">${sourceHtml}</div>` +
262
+ `</details>`
263
+ );
264
+ }
265
+
266
+ function highlightedSource(source: string): string {
267
+ const tokens = highlightDgmo(source);
268
+ const inner = tokens
269
+ .map((t) => {
270
+ const text = escapeHtml(t.text);
271
+ if (!t.role || t.role === 'default') return text;
272
+ return `<span class="dgmo-tok-${escapeAttr(t.role)}">${text}</span>`;
273
+ })
274
+ .join('');
275
+ // <pre><span> rather than <pre><code>: Astro's Shiki rehype plugin and
276
+ // Docusaurus's MDX pipeline post-process any <pre><code> pair (even ones
277
+ // emitted as raw HTML), clobbering pre-rendered highlight spans. A <span>
278
+ // inner element bypasses the matcher while keeping preformatted semantics.
279
+ return `<pre class="dgmo-pre"><span class="dgmo-code">${inner}</span></pre>`;
280
+ }
@@ -115,8 +115,8 @@ const DIM = 'dgmo-evt-dim';
115
115
  const ERA_HL = 'dgmo-evt-era-hl';
116
116
  // Clicking a legend entry collapses that tag value's cards (and their leaders)
117
117
  // to bare dots — the dot stays on the spine in its tag color and still reveals
118
- // its card on hover; the legend entry renders struck-through with a hollow
119
- // swatch so the muted state is self-documenting and reversible. Preview-only
118
+ // its card on hover; the legend entry dims with a hollow swatch so the muted
119
+ // state is self-documenting and reversible. Preview-only
120
120
  // (never in `exportMode`), so static SVG/PNG always carries the full set.
121
121
  const COLLAPSED = 'dgmo-evt-collapsed';
122
122
  const OFF = 'dgmo-evt-off';
@@ -136,7 +136,7 @@ const HOVER_CSS =
136
136
  // the extra class out-specifies both the collapse rule and DIM.
137
137
  `.dgmo-event-card.${COLLAPSED},.dgmo-event-leader.${COLLAPSED}{opacity:0;pointer-events:none}` +
138
138
  `.dgmo-event-card.${COLLAPSED}.${HL},.dgmo-event-leader.${COLLAPSED}.${HL}{opacity:1;pointer-events:auto}` +
139
- `[data-legend-entry].${OFF} text{text-decoration:line-through;opacity:.5}`;
139
+ `[data-legend-entry].${OFF} text{opacity:.5}`;
140
140
 
141
141
  type Side = 'above' | 'below';
142
142
 
@@ -739,11 +739,10 @@ export function renderEventLine(
739
739
 
740
740
  if (!exportMode) svg.append('style').text(HOVER_CSS);
741
741
 
742
- svg
743
- .append('rect')
744
- .attr('width', contentW)
745
- .attr('height', totalH)
746
- .attr('fill', palette.bg);
742
+ // No opaque full-canvas background rect: the SVG's CSS `background` style
743
+ // (and resvg's background option on PNG export) supplies the fill, so
744
+ // transparent-theme / Obsidian embeds blend with the host instead of
745
+ // showing a dark box — matching every other chart type.
747
746
 
748
747
  if (showTitle) {
749
748
  const t = svg
@@ -153,6 +153,7 @@ export function renderSwimlaneForExport(
153
153
  .attr('width', width)
154
154
  .attr('height', height)
155
155
  .attr('viewBox', `0 0 ${width} ${height}`)
156
+ .attr('preserveAspectRatio', 'xMidYMin meet')
156
157
  .style('font-family', FONT_FAMILY) as unknown as D3Svg;
157
158
 
158
159
  const defs = svg.append('defs');