@terpjs/react-core 0.32.0 → 0.34.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.
@@ -11,6 +11,7 @@ import { afterEach, describe, expect, it } from "vitest";
11
11
  import * as lintLayouts from "../../eslint-boundaries/src/layouts.js";
12
12
 
13
13
  import { BarChart } from "./charts/BarChart";
14
+ import { ConfirmDialog } from "./ConfirmDialog";
14
15
  import { TrendChart } from "./charts/TrendChart";
15
16
  import { DashboardPage } from "./DashboardPage";
16
17
  import { DetailPage } from "./DetailPage";
@@ -32,6 +33,7 @@ import { Stat, StatGroup } from "./Stat";
32
33
  import { StatusHistory } from "./charts/StatusHistory";
33
34
  import { Badge } from "./ui/Badge";
34
35
  import { OverviewPage } from "./OverviewPage";
36
+ import { CanvasHost, WorkspacePage } from "./WorkspacePage";
35
37
 
36
38
  // The public surface, as source: the archetype-coverage check below derives its list from
37
39
  // the entry point's own exports rather than restating one. `raw.d.ts` declares the ambient
@@ -185,6 +187,7 @@ describe("every archetype the package exports is governed, or says it is not", (
185
187
  "Page",
186
188
  "SettingsPage",
187
189
  "SplitPage",
190
+ "WorkspacePage",
188
191
  ]);
189
192
  });
190
193
 
@@ -432,10 +435,11 @@ describe("layout contract survives the roots the styling migration renames", ()
432
435
  ),
433
436
  );
434
437
  // The dashboard's body (ADR 0169 §4) added the figure and chart families -- the run history
435
- // among the charts -- and the timeline.
438
+ // among the charts -- and the timeline. The workspace (ADR 0179) added its canvas host.
436
439
  expect([...named].sort()).toEqual([
437
440
  "alert",
438
441
  "bar-chart",
442
+ "canvas-host",
439
443
  "card",
440
444
  "dataview",
441
445
  "detail-list",
@@ -822,3 +826,60 @@ describe("the dashboard's body (ADR 0169 §4)", () => {
822
826
  });
823
827
  });
824
828
  });
829
+
830
+ describe("the workspace's body (ADR 0179)", () => {
831
+ it("passes one canvas, whatever is drawn on it", async () => {
832
+ underContract(
833
+ <WorkspacePage title="Network">
834
+ <CanvasHost label="Network diagram">
835
+ {/* The host's subtree is the app's: an svg, or a canvas library's root. */}
836
+ <svg viewBox="0 0 100 100" role="img" aria-label="Two nodes">
837
+ <circle cx="20" cy="50" r="8" />
838
+ </svg>
839
+ </CanvasHost>
840
+ </WorkspacePage>,
841
+ );
842
+ await expectAccepted();
843
+ });
844
+
845
+ it("passes a framework state in the canvas's place", async () => {
846
+ underContract(
847
+ <WorkspacePage title="Network">
848
+ <EmptyState title="No nodes yet" />
849
+ </WorkspacePage>,
850
+ );
851
+ await expectAccepted();
852
+ });
853
+
854
+ it("passes a confirm dialog beside the canvas, for an action taken on it", async () => {
855
+ // Mutation: drop ConfirmDialog from the slot table, and deleting a node has nowhere to ask.
856
+ underContract(
857
+ <WorkspacePage title="Network">
858
+ <CanvasHost label="Network diagram">
859
+ <svg viewBox="0 0 100 100" role="img" aria-label="Two nodes" />
860
+ </CanvasHost>
861
+ <ConfirmDialog
862
+ open={false}
863
+ onOpenChange={() => {}}
864
+ onConfirm={() => {}}
865
+ title="Delete this node?"
866
+ />
867
+ </WorkspacePage>,
868
+ );
869
+ await expectAccepted();
870
+ });
871
+
872
+ it("refuses anything beside or instead of the canvas, with the directive message", async () => {
873
+ // Mutation: drop the WorkspacePage slot table, and the workspace's body is unconstrained.
874
+ underContract(
875
+ <WorkspacePage title="Network">
876
+ <div>a canvas sized by hand</div>
877
+ </WorkspacePage>,
878
+ );
879
+ await waitFor(() => {
880
+ expect(screen.getByTestId("refused").textContent).toBe(
881
+ slotViolationMessage("standard", "WorkspacePage", "<div>"),
882
+ );
883
+ });
884
+ });
885
+ });
@@ -50,6 +50,8 @@ export const LAYOUT_CONTRACTS: Readonly<Record<string, LayoutContractSpec>> = {
50
50
  "collection; a split " +
51
51
  "body is two SplitPanes and nothing else; and a dashboard body is its figures and " +
52
52
  "charts in Grid sections, the collection they summarise and the framework states. " +
53
+ "A workspace body is one CanvasHost, the surface that fills the screen, the " +
54
+ "framework states and a ConfirmDialog. " +
53
55
  "A screen that needs no contract " +
54
56
  "composes the plain Page, whose body this contract deliberately leaves unconstrained. " +
55
57
  "Every page, the plain one included, keeps two rules of its frame: its summary band " +
@@ -128,6 +130,16 @@ export const LAYOUT_CONTRACTS: Readonly<Record<string, LayoutContractSpec>> = {
128
130
  ConfirmDialog: "dialog",
129
131
  },
130
132
  },
133
+ WorkspacePage: {
134
+ components: {
135
+ CanvasHost: "canvas-host",
136
+ EmptyState: "empty-state",
137
+ ErrorState: "error-state",
138
+ LoadingState: "loading-state",
139
+ Alert: "alert",
140
+ ConfirmDialog: "dialog",
141
+ },
142
+ },
131
143
  DetailPage: {
132
144
  components: {
133
145
  DetailList: "detail-list",
@@ -75,6 +75,8 @@ const MARKERS = [
75
75
  "bar-chart-value",
76
76
  "breadcrumbs",
77
77
  "breadcrumbs-current",
78
+ "breadcrumbs-pending",
79
+ "breadcrumbs-pending-text",
78
80
  "breadcrumbs-separator",
79
81
  "button",
80
82
  "button-icon",
@@ -85,6 +87,8 @@ const MARKERS = [
85
87
  "calendar-title",
86
88
  "calendar-week",
87
89
  "calendar-weekday",
90
+ "canvas-host",
91
+ "canvas-host-layer",
88
92
  "card",
89
93
  "card-actions",
90
94
  "card-description",
@@ -674,7 +674,7 @@ describe("buildAppRouter", () => {
674
674
  .map((argument) => (argument instanceof Error ? argument.message : String(argument)))
675
675
  .join(" ");
676
676
  expect(`${logged} ${document.body.textContent ?? ""}`).toContain(
677
- "(Page, HubPage, OverviewPage, FormPage, SettingsPage, SplitPage, DashboardPage or DetailPage)",
677
+ "(Page, HubPage, OverviewPage, FormPage, SettingsPage, SplitPage, DashboardPage, WorkspacePage or DetailPage)",
678
678
  );
679
679
  });
680
680
 
package/src/router.tsx CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  Outlet,
7
7
  useNavigate,
8
8
  useParams,
9
+ useMatch,
9
10
  useRouter,
10
11
  useRouterState,
11
12
  useSearch,
@@ -13,7 +14,7 @@ import {
13
14
  type RouterHistory,
14
15
  } from "@tanstack/react-router";
15
16
  import type { ComponentType, ReactNode } from "react";
16
- import { useCallback, useEffect, useRef, useState } from "react";
17
+ import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
17
18
  import type { ModuleManifest, NavGroup, UiText } from "@terpjs/contract";
18
19
 
19
20
  import { AppShell } from "./AppShell";
@@ -35,6 +36,7 @@ import { isDeclarationVisible, visibleNav } from "./nav";
35
36
  import { NavLinkContext } from "./navLink";
36
37
  import type { NavLinkRenderer } from "./navLink";
37
38
  import { PageMarkerContext } from "./pageMarker";
39
+ import { TrailLabelsContext, TrailMemoryContext, trailMemory } from "./trailMemory";
38
40
  import {
39
41
  RouteSearchContext,
40
42
  declaredSearchKeys,
@@ -514,11 +516,16 @@ export function buildAppRouter(
514
516
  ),
515
517
  [],
516
518
  );
519
+ // What the trail has said about each place, for as long as the app runs (ADR 0173): one map
520
+ // for the shell's lifetime, so a page mounted by the next navigation still finds it. Each
521
+ // routed view binds it to its own path (RouteComponent), never to this location.
522
+ const trailLabels = useRef(new Map<string, string>()).current;
517
523
  return (
518
524
  // Publish the router's Link so every layout component that renders an in-app link
519
525
  // (Breadcrumbs, HubCard) navigates client-side by default. Forgetting `renderLink`
520
526
  // used to degrade the app silently: a raw anchor, a full page reload, no error.
521
527
  <NavLinkContext.Provider value={renderNavLink}>
528
+ <TrailLabelsContext.Provider value={trailLabels}>
522
529
  <AppShell
523
530
  title={options.title}
524
531
  logo={brandMark(layout.brand?.logo) ?? options.logo}
@@ -570,6 +577,7 @@ export function buildAppRouter(
570
577
  >
571
578
  <Outlet />
572
579
  </AppShell>
580
+ </TrailLabelsContext.Provider>
573
581
  </NavLinkContext.Provider>
574
582
  );
575
583
  }
@@ -584,6 +592,14 @@ export function buildAppRouter(
584
592
  ): AnyRoute {
585
593
  function RouteComponent() {
586
594
  const user = useAuth().currentUser();
595
+ // The trail's memory, bound to the path THIS view's match is at (ADR 0173): the leaf is
596
+ // remembered as this page's name, never as the name of a location the router has moved on to.
597
+ const trailLabels = useContext(TrailLabelsContext);
598
+ const ownPath = useMatch({ strict: false }).pathname;
599
+ const memory = useMemo(
600
+ () => (trailLabels === null ? null : trailMemory(trailLabels, ownPath)),
601
+ [trailLabels, ownPath],
602
+ );
587
603
  const rank = user?.role_rank ?? null;
588
604
  // The same resolution the sidebar uses, and using it here is what stops `permission` from
589
605
  // becoming a cosmetic gate: hiding a link while leaving its route reachable by URL is not
@@ -624,6 +640,7 @@ export function buildAppRouter(
624
640
  }
625
641
  return (
626
642
  <RouteSearchContext.Provider value={searchKeys}>
643
+ <TrailMemoryContext.Provider value={memory}>
627
644
  <LayoutContractContext.Provider value={layoutContract}>
628
645
  <PageMarkerContext.Provider
629
646
  value={() => {
@@ -633,6 +650,7 @@ export function buildAppRouter(
633
650
  <View />
634
651
  </PageMarkerContext.Provider>
635
652
  </LayoutContractContext.Provider>
653
+ </TrailMemoryContext.Provider>
636
654
  </RouteSearchContext.Provider>
637
655
  );
638
656
  }
@@ -373,13 +373,14 @@ describe("cascade structure", () => {
373
373
  // one shell rule keyed on a descendant of an attribute rather than on a marker of its own,
374
374
  // because the mechanism is deliberately NOT a new element (ADR 0097 §2). The `:not()` is the
375
375
  // whole band: the frame's two bands -- the title band and the summary band (ADR 0169 §4) --
376
- // keep the page grid's full track while their siblings take the measure.
376
+ // keep the page grid's full track while their siblings take the measure, and so does a
377
+ // workspace's canvas host (ADR 0179), which is not read along a line.
377
378
  // Selector AND declaration read out of ONE rule body, not as two independent substrings
378
379
  // of the layer. Asserted separately, an empty measure rule plus the declaration moved onto
379
380
  // some other rule during a consolidation would satisfy both — and the only baseline that
380
381
  // moved would read as an intentional layout change.
381
382
  const measureRule =
382
- /\[data-terp="appshell"\]\[data-content-width="measured"\]\s*\n?\s*\[data-terp="page"\] > \*:not\(\[data-terp="page-header"\], \[data-terp="page-summary"\]\) \{([^}]*)\}/.exec(
383
+ /\[data-terp="appshell"\]\[data-content-width="measured"\]\s*\n?\s*\[data-terp="page"\] > \*:not\(\[data-terp="page-header"\], \[data-terp="page-summary"\], \[data-terp="canvas-host"\]\) \{([^}]*)\}/.exec(
383
384
  base,
384
385
  );
385
386
  expect(measureRule, "the content measure must be one rule keyed on the shell's attribute").not
@@ -2482,3 +2483,175 @@ describe("what a review of the screens in use changed", () => {
2482
2483
  );
2483
2484
  });
2484
2485
  });
2486
+
2487
+ describe("flat at rest (ADR 0172)", () => {
2488
+ /** Every rule whose body reads a shadow token, by its selector. */
2489
+ function shadowReaders(): string[] {
2490
+ const readers: string[] = [];
2491
+ for (const match of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
2492
+ if (/var\(--shadow-/.test(match[2]!)) readers.push(match[1]!.trim().replace(/\s+/g, " "));
2493
+ }
2494
+ return readers.sort();
2495
+ }
2496
+
2497
+ it("lets only a layer cast a shadow, and never a block on the page", () => {
2498
+ // A shadow means something over the page: the six layers below. A card, a hub card, a
2499
+ // figure, a chart, a button and the table frame are told apart by fill and hairline.
2500
+ // Mutation: any resting block given a shadow again, or a layer that loses its own.
2501
+ expect(shadowReaders()).toEqual(
2502
+ [
2503
+ '[data-terp="appshell"][data-variant="mobile"] [data-terp="appshell-sidebar"]',
2504
+ '[data-terp="combobox-list"]',
2505
+ '[data-terp="dialog"]',
2506
+ '[data-terp="popover-panel"]',
2507
+ '[data-terp="toast"]',
2508
+ '[data-terp="tooltip"]',
2509
+ ].sort(),
2510
+ );
2511
+ });
2512
+ });
2513
+
2514
+ describe("a page's sections stand further apart than a section's blocks (ADR 0174)", () => {
2515
+ const always = baseOnly(layerBody("terp.base"));
2516
+ const ruleBody = (selector: string) => {
2517
+ const match = [...always.matchAll(/([^{}]+)\{([^{}]*)\}/g)].find(
2518
+ (rule) => rule[1]!.trim().replace(/\s+/g, " ") === selector,
2519
+ );
2520
+ expect(match, `${selector} has no rule of its own`).toBeDefined();
2521
+ return match![2]!;
2522
+ };
2523
+ const sectionGap = () => /(?:^|[;\s])gap: (var\(--space-\d+\))/.exec(ruleBody('[data-terp="page"]'))?.[1];
2524
+
2525
+ it("spaces the page's sections a step wider than a hub spaces its cards", () => {
2526
+ // Mutation: the page's gap back to --space-4, the hub grid's own, so a row of cards is as
2527
+ // far from the chart under it as from its neighbour again. Grid's side of the same promise
2528
+ // is its default `gap = 4`, a prop it always stamps, so it is measured in the workbench's
2529
+ // computed lane rather than read from a rule here.
2530
+ expect(sectionGap()).toBe("var(--space-6)");
2531
+ expect(ruleBody('[data-terp="hubpage-grid"]')).toContain("gap: var(--space-4)");
2532
+ });
2533
+
2534
+ it("cancels and repeats the section gap with the page's own token", () => {
2535
+ // Read from the page rule rather than written out, so moving the gap again moves these
2536
+ // with it or fails here. Mutation: either one left at --space-4 while the page moves,
2537
+ // which drops the summary band 8px under the title band, or sets the body nearer the
2538
+ // sequence bar than the band.
2539
+ const gap = sectionGap();
2540
+ expect(gap).toBeDefined();
2541
+ expect(
2542
+ ruleBody(
2543
+ '[data-terp="appshell-main"] > [data-terp="page"]:not([data-measure="narrow"]) > [data-terp="page-summary"]',
2544
+ ),
2545
+ ).toContain(`margin: calc(-1 * ${gap})`);
2546
+ expect(ruleBody('[data-terp="page-sequence"]')).toContain(`margin-block-start: ${gap}`);
2547
+ });
2548
+ });
2549
+
2550
+ describe("a workspace fills the height the shell leaves it (ADR 0179)", () => {
2551
+ const always = baseOnly(layerBody("terp.base"));
2552
+ const ruleIn = (body: string, selector: string) => {
2553
+ const match = [...body.matchAll(/([^{}]+)\{([^{}]*)\}/g)].find(
2554
+ (rule) => rule[1]!.trim().replace(/\s+/g, " ") === selector,
2555
+ );
2556
+ expect(match, `${selector} has no rule of its own`).toBeDefined();
2557
+ return match![2]!;
2558
+ };
2559
+ const ruleBody = (selector: string) => ruleIn(always, selector);
2560
+ const workspace = '[data-terp="page"][data-fill="workspace"]';
2561
+
2562
+ it("turns the shell's main into a column only when it holds a workspace", () => {
2563
+ // Mutation: drop the :has() scope, and every page's main becomes a flex column.
2564
+ const main = ruleBody(`[data-terp="appshell-main"]:has(> ${workspace})`);
2565
+ expect(main).toContain("display: flex");
2566
+ expect(main).toContain("flex-direction: column");
2567
+ expect(ruleBody(`[data-terp="appshell-main"] > ${workspace}`)).toContain("flex-grow: 1");
2568
+ // Every other page keeps the grid it always had.
2569
+ expect(ruleBody('[data-terp="page"]')).toContain("display: grid");
2570
+ });
2571
+
2572
+ it("gives the canvas what the band and the summary leave, and a floor where nothing does", () => {
2573
+ expect(ruleBody(workspace)).toContain("flex-direction: column");
2574
+ expect(ruleBody(`${workspace} > [data-terp="canvas-host"]`)).toContain("flex: 1 1 auto");
2575
+ const host = ruleBody('[data-terp="canvas-host"]');
2576
+ // Mutation: drop the floor, and a standalone canvas collapses to nothing.
2577
+ expect(host).toContain("min-height: 24rem");
2578
+ // Mutation: drop the clip, and a canvas panned past its edge paints over the band.
2579
+ // clip, not hidden: hidden makes the host a scroll container that focus can scroll.
2580
+ expect(host).toContain("overflow: clip");
2581
+ expect(host).not.toContain("overflow: hidden");
2582
+ expect(host).toContain("position: relative");
2583
+ });
2584
+
2585
+ it("lets a state in the canvas's place take the canvas's box, so the frame does not jump", () => {
2586
+ // Mutation: drop this rule, and a loading workspace is a short block that jumps to the full
2587
+ // height when the canvas arrives.
2588
+ const states = ruleBody(
2589
+ ["loading-state", "error-state", "empty-state"]
2590
+ .map((marker) => `${workspace} > [data-terp="${marker}"]`)
2591
+ .join(", "),
2592
+ );
2593
+ expect(states).toContain("flex: 1 1 auto");
2594
+ expect(states).toContain("min-height: 24rem");
2595
+ // Centred in the taller box, rather than the grid states' rows spreading down it.
2596
+ expect(states).toContain("align-content: center");
2597
+ });
2598
+
2599
+ it("leaves the host out of a measured shell's measure, as it does the bands", () => {
2600
+ // Mutation: drop canvas-host from the :not(), and in a measured shell the canvas stops at
2601
+ // the measure and sits against the start of the track.
2602
+ const measure = [...always.matchAll(/([^{}]+)\{([^{}]*)\}/g)].find((rule) =>
2603
+ rule[1]!
2604
+ .replace(/\s+/g, " ")
2605
+ .includes('[data-content-width="measured"] [data-terp="page"] > *:not('),
2606
+ );
2607
+ expect(measure, "the content measure has no rule").toBeDefined();
2608
+ expect(measure![1]).toContain('[data-terp="canvas-host"]');
2609
+ expect(measure![2]).toContain("width: min(100%, var(--shell-content-max-width))");
2610
+ });
2611
+
2612
+ it("paints the host from tokens only, as a block of the page", () => {
2613
+ const host = ruleBody('[data-terp="canvas-host"]');
2614
+ expect(host).toContain("background: var(--color-bg-surface)");
2615
+ expect(host).toContain("border: 1px solid var(--color-neutral-200)");
2616
+ expect(host).toContain("border-radius: var(--radius-lg)");
2617
+ expect(host).not.toMatch(/#[0-9a-f]{3,8}\b|rgb\(/i);
2618
+ });
2619
+
2620
+ it("lays its canvas over the whole host, through a layer of its own with a definite size", () => {
2621
+ // The layer, not the canvas, is what is positioned: a canvas library's root is positioned
2622
+ // by the library's own sheet, which beats a layered rule.
2623
+ const layer = ruleBody('[data-terp="canvas-host-layer"]');
2624
+ expect(layer).toContain("position: absolute");
2625
+ expect(layer).toContain("inset: 0");
2626
+ expect(declaresRuleFor(always, '[data-terp="canvas-host"] > *')).toBe(false);
2627
+ // Mutation: drop the explicit size, and an svg takes its height from its viewBox's ratio
2628
+ // and sits at the top of a tall canvas instead of filling it.
2629
+ const child = ruleBody('[data-terp="canvas-host-layer"] > :not([data-terp="dialog"])');
2630
+ expect(child).toContain("width: 100%");
2631
+ expect(child).toContain("height: 100%");
2632
+ expect(child).not.toContain("position");
2633
+ });
2634
+
2635
+ it("draws the shared focus ring on the host while its canvas has keyboard focus", () => {
2636
+ // The canvas fills the host edge to edge, so a ring around it lies wholly in what the host
2637
+ // clips. Mutation: drop this rule, and a keyboard user on the canvas sees no indicator.
2638
+ // In terp.state with the shared ring, and its declarations copied rather than restated:
2639
+ // the ring is one indicator wherever it is drawn.
2640
+ const state = baseOnly(layerBody("terp.state"));
2641
+ const declarations = (body: string) =>
2642
+ body
2643
+ .split(";")
2644
+ .map((part) => part.trim())
2645
+ .filter((part) => part.length > 0);
2646
+ const ring = declarations(ruleIn(state, "[data-terp]:focus-visible"));
2647
+ expect(ring).toContain("outline: 2px solid var(--color-fg-accent)");
2648
+ expect(
2649
+ declarations(
2650
+ ruleIn(
2651
+ state,
2652
+ '[data-terp="canvas-host"]:has(> [data-terp="canvas-host-layer"] > :focus-visible)',
2653
+ ),
2654
+ ),
2655
+ ).toEqual(ring);
2656
+ });
2657
+ });