@slashsuite/ui-react 0.13.0 → 0.13.2

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,62 @@
1
+ /**
2
+ * The native theme generator: a theme's CSS (`themes/<id>.css`) as the style map a React Native
3
+ * renderer reads (`themes/<id>.native.json`). Pure: it takes the CSS text and the palette and
4
+ * returns the map, so the theme test can assert the committed file is current.
5
+ *
6
+ * Every palette utility lands in one place: a plain one (`bg-white`) in `utilities`, one behind a
7
+ * state variant in that state's slot (`hover:bg-violet-700` in `pressed`, `placeholder:text-slate-400`
8
+ * in `placeholderTextColor`, `backdrop:bg-slate-900/35` in `scrim`). A rule the map cannot hold as
9
+ * one utility (`.disabled\:opacity-50:disabled:is(…)`) is a compound. Anything else is listed in
10
+ * `unmapped`, so nothing is dropped silently, and the theme test requires that list to be empty.
11
+ */
12
+ /** A React Native style, as the theme sets it: colours as lower-case hex or `rgba(…)`, and opacity. */
13
+ export type NativeStyle = Record<string, string | number>;
14
+ /** The slot a state variant lands in. */
15
+ export type NativeState = "pressed" | "focused" | "placeholderTextColor" | "scrim" | "disabled" | "invalid" | "target";
16
+ /** A rule that holds only alongside other classes: `disabled:opacity-50` on a solid fill. */
17
+ export type NativeCompound = {
18
+ utility: string;
19
+ requiresAny: string[];
20
+ style: NativeStyle;
21
+ };
22
+ export type NativeTheme = {
23
+ /** The theme's id, its file name without `.css`. */
24
+ id: string;
25
+ /** The scope class the web theme sits under. */
26
+ scope: string;
27
+ scheme: "light" | "dark";
28
+ /** The status bar's content style: light content on a dark theme. */
29
+ statusBar: "light-content" | "dark-content";
30
+ /** The page: its canvas, its ink, its sans family and the family its headings take. */
31
+ base: {
32
+ backgroundColor: string;
33
+ color: string;
34
+ fontFamily: string | null;
35
+ headingFontFamily: string | null;
36
+ };
37
+ /** The text selection's colours. */
38
+ selection: NativeStyle;
39
+ /** Every plain palette utility, keyed as a component writes it. */
40
+ utilities: Record<string, NativeStyle>;
41
+ /** Each state's utilities, keyed by the plain utility they restyle: `hover:bg-violet-700` sits under `pressed`. */
42
+ states: Record<NativeState, Record<string, NativeStyle>>;
43
+ /** A utility drawn on a tint: `within["bg-violet-50"]["text-slate-500"]`. */
44
+ within: Record<string, Record<string, NativeStyle>>;
45
+ /** A utility as a heading draws it: `headings["text-slate-900"]`. */
46
+ headings: Record<string, NativeStyle>;
47
+ compounds: NativeCompound[];
48
+ };
49
+ /** Which slot each Tailwind variant the palette uses lands in. */
50
+ export declare const STATE_OF_VARIANT: Record<string, NativeState>;
51
+ /**
52
+ * The native map of one theme's CSS. `id` is the file name without `.css`. Returns the map and
53
+ * every rule or declaration it could not carry.
54
+ */
55
+ export declare function nativeTheme(css: string, id: string): {
56
+ theme: NativeTheme;
57
+ unmapped: string[];
58
+ };
59
+ /** The palette utilities a native map does not hold: each in `utilities`, or in its variant's slot. */
60
+ export declare function missingFromNative(theme: NativeTheme, palette: readonly string[]): string[];
61
+ /** The map as the file holds it: two-space JSON with a trailing newline. */
62
+ export declare const nativeThemeJson: (theme: NativeTheme) => string;
@@ -0,0 +1,290 @@
1
+ /**
2
+ * The native theme generator: a theme's CSS (`themes/<id>.css`) as the style map a React Native
3
+ * renderer reads (`themes/<id>.native.json`). Pure: it takes the CSS text and the palette and
4
+ * returns the map, so the theme test can assert the committed file is current.
5
+ *
6
+ * Every palette utility lands in one place: a plain one (`bg-white`) in `utilities`, one behind a
7
+ * state variant in that state's slot (`hover:bg-violet-700` in `pressed`, `placeholder:text-slate-400`
8
+ * in `placeholderTextColor`, `backdrop:bg-slate-900/35` in `scrim`). A rule the map cannot hold as
9
+ * one utility (`.disabled\:opacity-50:disabled:is(…)`) is a compound. Anything else is listed in
10
+ * `unmapped`, so nothing is dropped silently, and the theme test requires that list to be empty.
11
+ */
12
+ /** Which slot each Tailwind variant the palette uses lands in. */
13
+ export const STATE_OF_VARIANT = {
14
+ hover: "pressed",
15
+ "focus-visible": "focused",
16
+ "has-focus-visible": "focused",
17
+ placeholder: "placeholderTextColor",
18
+ backdrop: "scrim",
19
+ disabled: "disabled",
20
+ "aria-invalid": "invalid",
21
+ "has-aria-invalid": "invalid",
22
+ "user-invalid": "invalid",
23
+ "has-user-invalid": "invalid",
24
+ target: "target",
25
+ };
26
+ const CSS_TO_NATIVE = {
27
+ "background-color": "backgroundColor",
28
+ color: "color",
29
+ "border-color": "borderColor",
30
+ "outline-color": "outlineColor",
31
+ "accent-color": "accentColor",
32
+ opacity: "opacity",
33
+ "font-weight": "fontWeight",
34
+ };
35
+ /** Declarations a native map has no use for: web-only, or carried in `base`. Listed, so nothing else is dropped. */
36
+ const WEB_ONLY = new Set([
37
+ "transition",
38
+ "text-underline-offset",
39
+ "color-scheme",
40
+ "font-family",
41
+ "--font-mono",
42
+ "--font-sans",
43
+ "--font-heading",
44
+ ]);
45
+ const COLOUR = /^(#[0-9a-f]{3,8}|rgba?\([^)]*\)|transparent)$/i;
46
+ /** One canonical form of a colour: lower-case hex, `rgba(r, g, b, a)`. */
47
+ function colourOf(value, where, unmapped) {
48
+ if (!COLOUR.test(value)) {
49
+ unmapped.push(`${where}: "${value}" is not a colour React Native parses`);
50
+ return undefined;
51
+ }
52
+ return value
53
+ .toLowerCase()
54
+ .replace(/\(\s*/, "(")
55
+ .replace(/\s*\)/, ")")
56
+ .replace(/\s*,\s*/g, ", ");
57
+ }
58
+ function declarationsOf(body, where, unmapped) {
59
+ const style = {};
60
+ for (const declaration of body.split(";")) {
61
+ const colon = declaration.indexOf(":");
62
+ if (colon < 0)
63
+ continue;
64
+ const property = declaration.slice(0, colon).trim();
65
+ const value = declaration
66
+ .slice(colon + 1)
67
+ .replace(/\s+/g, " ")
68
+ .trim();
69
+ if (property === "" || WEB_ONLY.has(property) || property.startsWith("--hc-"))
70
+ continue;
71
+ const native = CSS_TO_NATIVE[property];
72
+ if (native === undefined) {
73
+ unmapped.push(`${where} { ${property} }`);
74
+ continue;
75
+ }
76
+ if (native === "opacity")
77
+ style[native] = Number(value);
78
+ else if (native === "fontWeight")
79
+ style[native] = value;
80
+ else {
81
+ const colour = colourOf(value, `${where} ${property}`, unmapped);
82
+ if (colour !== undefined)
83
+ style[native] = colour;
84
+ }
85
+ }
86
+ return style;
87
+ }
88
+ /** Split a selector list on the commas outside brackets. */
89
+ function selectorsOf(list) {
90
+ const parts = [];
91
+ let depth = 0;
92
+ let current = "";
93
+ for (const char of list) {
94
+ if (char === "(" || char === "[")
95
+ depth += 1;
96
+ if (char === ")" || char === "]")
97
+ depth -= 1;
98
+ if (char === "," && depth === 0) {
99
+ parts.push(current.trim());
100
+ current = "";
101
+ }
102
+ else
103
+ current += char;
104
+ }
105
+ return [...parts, current.trim()].filter(Boolean);
106
+ }
107
+ const unescapeClass = (name) => name.replace(/\\(.)/g, "$1");
108
+ const CLASS = String.raw `((?:\\.|[\w-])+)`;
109
+ /** `hover:bg-violet-700` as its variant and plain utility; no variant gives `undefined`. */
110
+ function splitVariant(utility) {
111
+ const colon = utility.lastIndexOf(":");
112
+ if (colon < 0)
113
+ return { variant: undefined, plain: utility };
114
+ return { variant: utility.slice(0, colon), plain: utility.slice(colon + 1) };
115
+ }
116
+ function merge(table, key, style) {
117
+ table[key] = { ...table[key], ...style };
118
+ }
119
+ function emptyParsed(scope) {
120
+ return {
121
+ scope,
122
+ base: { backgroundColor: "", color: "", fontFamily: null, headingFontFamily: null },
123
+ selection: {},
124
+ utilities: {},
125
+ states: {
126
+ pressed: {},
127
+ focused: {},
128
+ placeholderTextColor: {},
129
+ scrim: {},
130
+ disabled: {},
131
+ invalid: {},
132
+ target: {},
133
+ },
134
+ within: {},
135
+ headings: {},
136
+ compounds: [],
137
+ };
138
+ }
139
+ /** The first family of a `--font-…` stack in the scope rule, unquoted; none gives `null`. */
140
+ function familyOf(body, variable) {
141
+ const family = new RegExp(`--font-${variable}:([^;]+);`)
142
+ .exec(body)?.[1]
143
+ ?.split(",")[0]
144
+ ?.trim()
145
+ .replace(/^["']|["']$/g, "");
146
+ return family === undefined || family === "" ? null : family;
147
+ }
148
+ /** The scope rule: the page's canvas, ink, sans family and heading family. */
149
+ function readScope(parsed, body, file, unmapped) {
150
+ const style = declarationsOf(body, `${file} .${parsed.scope}`, unmapped);
151
+ parsed.base.backgroundColor = String(style["backgroundColor"] ?? "");
152
+ parsed.base.color = String(style["color"] ?? "");
153
+ parsed.base.fontFamily = familyOf(body, "sans");
154
+ parsed.base.headingFontFamily = familyOf(body, "heading");
155
+ }
156
+ /**
157
+ * A rule on the headings. The heading face is `base.headingFontFamily`, read from the scope rule, so
158
+ * a bare heading rule of font-family alone is taken; a utility on a heading
159
+ * (`:is(h1, h2, h3).text-slate-900`) lands in `headings`; anything else is unmapped.
160
+ */
161
+ function readHeading(parsed, rest, style) {
162
+ if (rest === "")
163
+ return Object.keys(style).every((key) => key === "fontFamily");
164
+ const utility = new RegExp(`^\\.${CLASS}$`).exec(rest)?.[1];
165
+ if (utility === undefined)
166
+ return false;
167
+ merge(parsed.headings, unescapeClass(utility), style);
168
+ return true;
169
+ }
170
+ /** A selector that is not one utility: the selection, the headings, a utility on a tint. */
171
+ function readSpecial(parsed, selector, style) {
172
+ const scope = parsed.scope;
173
+ if (new RegExp(`^\\.${scope}\\s*::selection$`).test(selector)) {
174
+ Object.assign(parsed.selection, style);
175
+ return true;
176
+ }
177
+ const heading = new RegExp(`^\\.${scope}\\s+:is\\(h1, h2, h3[^)]*\\)(.*)$`).exec(selector);
178
+ if (heading)
179
+ return readHeading(parsed, heading[1] ?? "", style);
180
+ const within = new RegExp(`^\\.${scope}\\s+\\.${CLASS}\\s+\\.${CLASS}$`).exec(selector);
181
+ if (!within)
182
+ return false;
183
+ const tint = unescapeClass(within[1] ?? "");
184
+ parsed.within[tint] = parsed.within[tint] ?? {};
185
+ merge(parsed.within[tint], unescapeClass(within[2] ?? ""), style);
186
+ return true;
187
+ }
188
+ /** One utility, plain, behind a state variant, or held only alongside other classes. */
189
+ function readUtility(parsed, utility, rest, style) {
190
+ const requires = /:is\(([^)]*)\)/.exec(rest)?.[1];
191
+ if (requires !== undefined) {
192
+ const requiresAny = requires.split(",").map((name) => unescapeClass(name.trim().slice(1)));
193
+ parsed.compounds.push({ utility, requiresAny, style });
194
+ return true;
195
+ }
196
+ const { variant, plain } = splitVariant(utility);
197
+ if (variant === undefined) {
198
+ // A plain class with its own `:hover` (`.link:hover`) is that class pressed; any other
199
+ // pseudo-class on a plain class has no slot.
200
+ if (rest === ":hover")
201
+ merge(parsed.states.pressed, plain, style);
202
+ else if (rest === "")
203
+ merge(parsed.utilities, plain, style);
204
+ else
205
+ return false;
206
+ return true;
207
+ }
208
+ const state = STATE_OF_VARIANT[variant];
209
+ if (state === undefined)
210
+ return false;
211
+ merge(parsed.states[state], plain, state === "placeholderTextColor" ? asPlaceholder(style) : style);
212
+ return true;
213
+ }
214
+ /** One `.scope …` selector into its place in the map; false when it has none. */
215
+ function readSelector(parsed, selector, style) {
216
+ if (readSpecial(parsed, selector, style))
217
+ return true;
218
+ const plain = new RegExp(`^\\.${parsed.scope}\\s+\\.${CLASS}(.*)$`).exec(selector);
219
+ if (!plain)
220
+ return false;
221
+ return readUtility(parsed, unescapeClass(plain[1] ?? ""), plain[2] ?? "", style);
222
+ }
223
+ /** A placeholder's colour is a prop on a native text input, not a style. */
224
+ const asPlaceholder = (style) => style["color"] === undefined ? style : { placeholderTextColor: style["color"] };
225
+ /**
226
+ * The native map of one theme's CSS. `id` is the file name without `.css`. Returns the map and
227
+ * every rule or declaration it could not carry.
228
+ */
229
+ export function nativeTheme(css, id) {
230
+ const file = `${id}.css`;
231
+ const uncommented = css.replace(/\/\*[\s\S]*?\*\//g, "");
232
+ const scheme = /@custom-variant\s+dark\b/.test(uncommented) ? "dark" : "light";
233
+ const unmapped = [];
234
+ const { scope, base, selection, utilities, states, within, headings, compounds } = parse(uncommented.replace(/@[^;{}]*;/g, ""), file, unmapped);
235
+ return {
236
+ theme: {
237
+ id,
238
+ scope,
239
+ scheme,
240
+ statusBar: scheme === "dark" ? "light-content" : "dark-content",
241
+ base,
242
+ selection,
243
+ utilities,
244
+ states,
245
+ within,
246
+ headings,
247
+ compounds,
248
+ },
249
+ unmapped,
250
+ };
251
+ }
252
+ /** The scope rule's map, from the first rule: its selector must be the one scope class. */
253
+ function parseScope(list, body, file, unmapped) {
254
+ const scope = /^\.([\w-]+)$/.exec(selectorsOf(list)[0] ?? "")?.[1];
255
+ if (scope === undefined)
256
+ throw new Error(`${file}: the first rule is not the scope rule`);
257
+ const parsed = emptyParsed(scope);
258
+ readScope(parsed, body, file, unmapped);
259
+ return parsed;
260
+ }
261
+ /** The rules of one theme's CSS, comments and at-statements gone: the scope rule first. */
262
+ function parse(source, file, unmapped) {
263
+ let parsed;
264
+ for (const [, list = "", body = ""] of source.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
265
+ if (parsed === undefined) {
266
+ parsed = parseScope(list, body, file, unmapped);
267
+ continue;
268
+ }
269
+ for (const selector of selectorsOf(list)) {
270
+ const style = declarationsOf(body, `${file} ${selector}`, unmapped);
271
+ if (!readSelector(parsed, selector, style))
272
+ unmapped.push(`${file}: selector ${selector}`);
273
+ }
274
+ }
275
+ if (parsed === undefined)
276
+ throw new Error(`${file}: no scope rule`);
277
+ return parsed;
278
+ }
279
+ /** The palette utilities a native map does not hold: each in `utilities`, or in its variant's slot. */
280
+ export function missingFromNative(theme, palette) {
281
+ return palette.filter((utility) => {
282
+ const { variant, plain } = splitVariant(utility);
283
+ if (variant === undefined)
284
+ return theme.utilities[plain] === undefined;
285
+ const state = STATE_OF_VARIANT[variant];
286
+ return state === undefined || theme.states[state][plain] === undefined;
287
+ });
288
+ }
289
+ /** The map as the file holds it: two-space JSON with a trailing newline. */
290
+ export const nativeThemeJson = (theme) => `${JSON.stringify(theme, null, 2)}\n`;
package/dist/cx.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  /** Join class names, dropping falsy parts. */
2
2
  export declare function cx(...parts: Array<string | false | null | undefined>): string;
3
- /** The keyboard focus ring every interactive control shares. */
4
- export declare const focusRing = "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-violet-600";
3
+ export { focusRing, insetFocusRing } from "./focus.js";
5
4
  /**
6
5
  * A heading's lines are balanced, so a two-line title does not end on one orphaned word; prose is
7
6
  * wrapped `pretty`, which keeps a short last line off a paragraph. Only the wrap style is set, so a
@@ -15,12 +14,6 @@ export declare const pretty = "[text-wrap-style:pretty]";
15
14
  * colour the page names is kept, so the fill takes the system's Highlight; `!` beats a theme's scoped remap of the stock fill.
16
15
  */
17
16
  export declare const forcedFill = "forced-colors:bg-[color:Highlight]!";
18
- /**
19
- * The same ring drawn inside the control, for one that fills a box which clips anything outside
20
- * it (a table's sortable title, a scroller). `focusRing` with `-outline-offset-2` added would not
21
- * do, since `outline-offset-2` comes later in the CSS and wins.
22
- */
23
- export declare const insetFocusRing = "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-violet-600";
24
17
  /**
25
18
  * On a row or card that holds a stretched link (`link-stretch`): every interactive descendant sits
26
19
  * above that link and is clickable on its own. `z-10` needs a position, so each gets `relative`,
package/dist/cx.js CHANGED
@@ -2,8 +2,8 @@
2
2
  export function cx(...parts) {
3
3
  return parts.filter(Boolean).join(" ");
4
4
  }
5
- /** The keyboard focus ring every interactive control shares. */
6
- export const focusRing = "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-violet-600";
5
+ // The keyboard focus ring and its inset twin are core's, the one copy both renderers read.
6
+ export { focusRing, insetFocusRing } from "./focus.js";
7
7
  /**
8
8
  * A heading's lines are balanced, so a two-line title does not end on one orphaned word; prose is
9
9
  * wrapped `pretty`, which keeps a short last line off a paragraph. Only the wrap style is set, so a
@@ -17,12 +17,6 @@ export const pretty = "[text-wrap-style:pretty]";
17
17
  * colour the page names is kept, so the fill takes the system's Highlight; `!` beats a theme's scoped remap of the stock fill.
18
18
  */
19
19
  export const forcedFill = "forced-colors:bg-[color:Highlight]!";
20
- /**
21
- * The same ring drawn inside the control, for one that fills a box which clips anything outside
22
- * it (a table's sortable title, a scroller). `focusRing` with `-outline-offset-2` added would not
23
- * do, since `outline-offset-2` comes later in the CSS and wins.
24
- */
25
- export const insetFocusRing = "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-violet-600";
26
20
  /**
27
21
  * On a row or card that holds a stretched link (`link-stretch`): every interactive descendant sits
28
22
  * above that link and is clickable on its own. `z-10` needs a position, so each gets `relative`,
package/dist/density.d.ts CHANGED
@@ -26,9 +26,9 @@ export declare function useResponsiveDensity(size: Size | ResponsiveSize | undef
26
26
  export declare function useTypeStep(): TypeStep | undefined;
27
27
  /** The size twins, for the data test that each is its table with `md:` on every class. */
28
28
  export declare const controlTextTables: {
29
- text: Record<"compact" | "default", Record<Size, string>>;
29
+ text: Record<import("./core/index.js").ControlTypeStep, Record<import("./core/index.js").ButtonSize, string>>;
30
30
  textMd: Record<"compact" | "default", Record<Size, string>>;
31
- leading: Record<Size, string>;
31
+ leading: Record<import("./core/index.js").ButtonSize, string>;
32
32
  leadingMd: Record<Size, string>;
33
33
  };
34
34
  /**
package/dist/density.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createContext, createElement, useContext, useMemo, } from "react";
2
+ import { CONTROL_LEADING, CONTROL_TEXT } from "./core/index.js";
2
3
  import { isResponsive } from "./size.js";
3
4
  const DensityContext = createContext({ size: undefined, type: undefined });
4
5
  /**
@@ -28,11 +29,6 @@ export function useResponsiveDensity(size) {
28
29
  export function useTypeStep() {
29
30
  return useContext(DensityContext).type;
30
31
  }
31
- /** A control's type size at each step: `md` is 16px at the default step, and `compact` is one step down. */
32
- const CONTROL_TEXT = {
33
- default: { sm: "text-sm", md: "text-base", lg: "text-lg" },
34
- compact: { sm: "text-xs", md: "text-sm", lg: "text-base" },
35
- };
36
32
  /** `CONTROL_TEXT` from the `md` breakpoint up, for a responsive size. */
37
33
  const CONTROL_TEXT_MD = {
38
34
  default: { sm: "md:text-sm", md: "md:text-base", lg: "md:text-lg" },
@@ -43,12 +39,8 @@ const CONTROL_TEXT_MD = {
43
39
  * not zoom the page when it takes the focus.
44
40
  */
45
41
  const TOUCH_TEXT = "pointer-coarse:text-base";
46
- /**
47
- * A control's line height by `size`, whatever its type step: 16, 20 and 24px, so with its padding
48
- * every control is 26, 38 and 46px tall at both steps, and a `Select`, an `IconButton` and a
49
- * `DateRangePicker`, whose heights are fixed, line up with it.
50
- */
51
- const CONTROL_LEADING = { sm: "leading-4", md: "leading-5", lg: "leading-6" };
42
+ // `CONTROL_TEXT` and `CONTROL_LEADING` are core's, the one copy both renderers read; a `Select`, an
43
+ // `IconButton` and a `DateRangePicker`, whose heights are fixed, line up with them.
52
44
  /** `CONTROL_LEADING` from the `md` breakpoint up, for a responsive size. */
53
45
  const CONTROL_LEADING_MD = {
54
46
  sm: "md:leading-4",
@@ -17,9 +17,10 @@ export type FlowNodeBox = FlowBox & {
17
17
  id: string;
18
18
  };
19
19
  /**
20
- * An arrow as laid out: the `from` and `to` ids, its place in `edges` (`index`), the points dagre
21
- * routed it through, the SVG path drawn through them (it ends on the target's edge, at the
22
- * arrowhead's tip) and its label's centre when it has one.
20
+ * An arrow as laid out: the `from` and `to` ids, its place in `edges` (`index`), the corners of its
21
+ * square route (it leaves the source's side facing the way it goes, turns only between ranks, and
22
+ * ends on the target's edge, at the arrowhead's tip), the SVG path through them and its label's
23
+ * centre when it has one.
23
24
  */
24
25
  export type FlowEdgePath = {
25
26
  from: string;
@@ -65,4 +66,3 @@ export type FlowDirection = "down" | "right";
65
66
  * typo draws no stray box. Pure: the same input gives the same layout.
66
67
  */
67
68
  export declare function layoutFlow(nodes: readonly LayoutNode[], edges: readonly LayoutEdge[], direction: FlowDirection): FlowLayout;
68
- export declare function stepPath(points: readonly FlowPoint[], direction: FlowDirection, lane?: number): string;
@@ -1,9 +1,11 @@
1
1
  /**
2
- * The layout behind `FlowDiagram`: dagre places the boxes and routes the arrows, then this file
3
- * turns its output into what the component draws. Internal: only the geometry types are exported
2
+ * The layout behind `FlowDiagram`: dagre places the boxes and gives each arrow a route,
3
+ * `flowRoute` draws the arrows round the boxes along it, and this file turns the result into what
4
+ * the component draws. Internal: only the geometry types are exported
4
5
  * from the package, for `FlowDiagram`'s `overlay`.
5
6
  */
6
7
  import { Graph, layout } from "@dagrejs/dagre";
8
+ import { routeEdges, squarePath } from "./flowRoute.js";
7
9
  /** Space round the drawing, between boxes in a rank, and between ranks. */
8
10
  const MARGIN = 16;
9
11
  const NODE_GAP = 32;
@@ -45,61 +47,78 @@ export function layoutFlow(nodes, edges, direction) {
45
47
  g.setEdge(e.from, e.to, e.label ? { width: e.label.width, height: e.label.height, labelpos: "c" } : {}, String(index));
46
48
  }
47
49
  layout(g);
48
- const box = (key) => {
50
+ return routeLayout(g, { ids, groups, kept }, direction === "right");
51
+ }
52
+ /**
53
+ * Routes dagre's laid-out graph round its boxes and labels (`flowRoute`) and reads it back in the
54
+ * diagram's own space, rounded. `across` is true when the diagram is ranked right.
55
+ */
56
+ function routeLayout(g, { ids, groups, kept }, across) {
57
+ /** Turns a point or box into rank-down space, and back: ranked right, x and y swap. */
58
+ const turn = (p) => (across ? { x: p.y, y: p.x } : p);
59
+ const turnBox = (b) => across ? { x: b.y, y: b.x, width: b.height, height: b.width } : b;
60
+ const raw = (key) => {
49
61
  const { x = 0, y = 0, width = 0, height = 0 } = g.node(key);
50
- return {
51
- x: round(x - width / 2),
52
- y: round(y - height / 2),
53
- width: round(width),
54
- height: round(height),
55
- };
62
+ return turnBox({ x: x - width / 2, y: y - height / 2, width, height });
63
+ };
64
+ const routes = kept.map(({ e, index }) => ({
65
+ e,
66
+ index,
67
+ routed: g.edge(e.from, e.to, String(index)),
68
+ }));
69
+ const labelAt = routes.map(({ e, routed }) => e.label && routed.x !== undefined && routed.y !== undefined
70
+ ? turn({ x: routed.x, y: routed.y })
71
+ : null);
72
+ const labels = routes.flatMap(({ e }, i) => {
73
+ const at = labelAt[i];
74
+ if (!e.label || !at)
75
+ return [];
76
+ const size = turnBox({ x: 0, y: 0, width: e.label.width, height: e.label.height });
77
+ return [
78
+ {
79
+ x: at.x - size.width / 2,
80
+ y: at.y - size.height / 2,
81
+ width: size.width,
82
+ height: size.height,
83
+ },
84
+ ];
85
+ });
86
+ const { lines, shift, grow } = routeEdges(new Map([...ids].map((id) => [id, raw(id)])), labels, routes.map(({ e, routed }) => ({
87
+ from: e.from,
88
+ to: e.to,
89
+ points: (routed.points ?? []).map(turn),
90
+ })));
91
+ /** A box from rank-down space, moved past any widened gap, back in the diagram's space. */
92
+ const place = (b) => {
93
+ const top = shift(b.y);
94
+ const bottom = shift(b.y + b.height);
95
+ const out = turnBox({ x: b.x, y: top, width: b.width, height: bottom - top });
96
+ return { x: round(out.x), y: round(out.y), width: round(out.width), height: round(out.height) };
56
97
  };
57
98
  const graph = g.graph();
99
+ const size = turn({ x: graph.width ?? 0, y: graph.height ?? 0 });
100
+ const grown = turn({ x: size.x, y: size.y + grow });
58
101
  return {
59
- width: Math.ceil(graph.width ?? 0),
60
- height: Math.ceil(graph.height ?? 0),
61
- nodes: [...ids].map((id) => ({ id, ...box(id) })),
62
- groups: groups.map((name) => ({ name, ...box(groupKey(name)) })),
63
- edges: kept.map(({ e, index }) => {
64
- const routed = g.edge(e.from, e.to, String(index));
65
- const points = (routed.points ?? []).map((p) => ({ x: round(p.x), y: round(p.y) }));
102
+ width: Math.ceil(grown.x),
103
+ height: Math.ceil(grown.y),
104
+ nodes: [...ids].map((id) => ({ id, ...place(raw(id)) })),
105
+ groups: groups.map((name) => ({ name, ...place(raw(groupKey(name))) })),
106
+ edges: routes.map(({ e, index }, i) => {
107
+ const points = (lines[i] ?? []).map((p) => {
108
+ const out = turn(p);
109
+ return { x: round(out.x), y: round(out.y) };
110
+ });
111
+ const at = labelAt[i];
66
112
  return {
67
113
  from: e.from,
68
114
  to: e.to,
69
115
  index,
70
116
  points,
71
- path: stepPath(points, direction, LANES[index % LANES.length]),
72
- labelAt: e.label && routed.x !== undefined && routed.y !== undefined
73
- ? { x: round(routed.x), y: round(routed.y) }
117
+ path: squarePath(points),
118
+ labelAt: at
119
+ ? (({ x, y }) => ({ x: round(x), y: round(y) }))(turn({ x: at.x, y: shift(at.y) }))
74
120
  : null,
75
121
  };
76
122
  }),
77
123
  };
78
124
  }
79
- /**
80
- * A square path through dagre's route points: each step leaves along the rank `direction`, turns
81
- * once at `lane` of the way across (0.5 is halfway), and arrives along it again, so every arrow is
82
- * made of straight runs at right angles and ends exactly on the last point, where its arrowhead
83
- * sits. Arrows between the same two ranks take different lanes, so their cross runs do not overlap.
84
- */
85
- /** Where each arrow turns between two ranks, by its index: spread so parallel runs stay apart. */
86
- const LANES = [0.5, 0.3, 0.7, 0.4, 0.6];
87
- export function stepPath(points, direction, lane = 0.5) {
88
- const [first, ...rest] = points;
89
- if (!first)
90
- return "";
91
- let d = `M${first.x},${first.y}`;
92
- let from = first;
93
- for (const to of rest) {
94
- if (direction === "right") {
95
- const mid = round(from.x + (to.x - from.x) * lane);
96
- d += `H${mid}V${to.y}H${to.x}`;
97
- }
98
- else {
99
- const mid = round(from.y + (to.y - from.y) * lane);
100
- d += `V${mid}H${to.x}V${to.y}`;
101
- }
102
- from = to;
103
- }
104
- return d;
105
- }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * How `FlowDiagram`'s arrows are drawn round its boxes, after dagre has placed them. Internal.
3
+ *
4
+ * dagre ranks the boxes and gives each arrow a route: a point on the source, one point in every
5
+ * rank it passes (each clear of the boxes in that rank) and a point on the target. Drawn as square
6
+ * steps that turn halfway between two points, an arrow can turn inside a rank of tall boxes and run
7
+ * through one, and an arrow that leaves a box's side runs along its border. So this routes every
8
+ * arrow again, in the rank direction:
9
+ *
10
+ * - it leaves its source through the side facing its next point and enters its target through the
11
+ * side facing its last one, at ports spread along that side, so no two arrows share a port and
12
+ * none runs along a border;
13
+ * - it runs along the rank direction through each of dagre's points, and turns only in a gap
14
+ * between ranks, where no box and no arrow label is;
15
+ * - the turns in one gap are spread over tracks, so two runs across the same gap never lie on one
16
+ * line, and a gap too narrow for its tracks is widened, moving everything past it along.
17
+ *
18
+ * Every function here works in rank-down space (ranks stacked along y); a diagram ranked right is
19
+ * turned into it and back.
20
+ */
21
+ import type { FlowBox as Rect, FlowPoint as Point } from "./flowLayout.js";
22
+ /** One arrow to route: its ends, and dagre's points from the source to the target. */
23
+ type RouteEdge = {
24
+ from: string;
25
+ to: string;
26
+ points: readonly Point[];
27
+ };
28
+ /** The routed diagram: every arrow as a square path's corners, and how to move a y past widened gaps. */
29
+ type Routed = {
30
+ lines: Point[][];
31
+ shift: (y: number) => number;
32
+ grow: number;
33
+ };
34
+ /**
35
+ * Routes every arrow round the boxes and labels (rank-down space): see the file's comment. The
36
+ * lines come back in `edges`' order, in the space after the gaps are widened; `shift` moves a y
37
+ * from before into it, and `grow` is how much taller the diagram became.
38
+ */
39
+ export declare function routeEdges(boxes: ReadonlyMap<string, Rect>, labels: readonly Rect[], edges: readonly RouteEdge[]): Routed;
40
+ /** The SVG path through square corners: a move, then one straight run to each next corner. */
41
+ export declare function squarePath(points: readonly Point[]): string;
42
+ export {};