Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions framework/build/postcss-token-layer.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Puts vc-shell's design token declarations in the `vc-shell` cascade layer.
*
* A token rule is one whose selectors are all `:root`, optionally with attributes
* (`:root[data-theme="dark"]`), and whose declarations are all custom properties. An app's
* own, unlayered `:root { --token: ... }` then wins whatever order the stylesheets load in,
* so it needs no `:root:root` or `!important`. Inside the layer the framework's rules keep
* their usual order and specificity, so the dark theme still overrides the defaults.
*/
const ROOT_ONLY = /^:root(\[[^\]]+\])*$/;

function isTokenRule(rule) {
if (rule.parent?.type === "atrule") return false;
if (!rule.selectors.every((s) => ROOT_ONLY.test(s.trim()))) return false;
let hasDecl = false;
for (const node of rule.nodes) {
if (node.type === "comment") continue;
if (node.type !== "decl" || !node.prop.startsWith("--")) return false;
hasDecl = true;
}
return hasDecl;
}

module.exports = () => ({
postcssPlugin: "vc-shell-token-layer",
OnceExit(root, { AtRule }) {
root.walkRules((rule) => {
if (!isTokenRule(rule)) return;
const layer = new AtRule({ name: "layer", params: "vc-shell" });
rule.replaceWith(layer);
layer.append(rule);
});
},
});
module.exports.postcss = true;
28 changes: 28 additions & 0 deletions framework/build/postcss-token-layer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import postcss from "postcss";
const tokenLayer = require("./postcss-token-layer.cjs");

const run = async (css: string) => (await postcss([tokenLayer()]).process(css, { from: undefined })).css;

describe("postcss-token-layer", () => {
it("puts a :root token rule in the vc-shell layer", async () => {
expect((await run(":root { --status-bg: red; }")).replace(/\s+/g, " ")).toBe(
"@layer vc-shell { :root { --status-bg: red; } }",
);
});

it("layers theme token rules too, so they keep beating the defaults inside the layer", async () => {
expect(await run(':root[data-theme="dark"] { --x: 1; }')).toContain("@layer vc-shell");
});

it("leaves rules that are not pure token declarations", async () => {
const css = [
":root { --x: 1; color: red; }",
":root .vc-status { --x: 1; }",
':root, [dir="ltr"] { --vc-inline-sign: 1; }',
".vc-status { --x: 1; }",
"@media (min-width: 1px) { :root { --x: 1; } }",
].join("\n");
expect(await run(css)).toBe(css);
});
});
24 changes: 24 additions & 0 deletions framework/core/blade-navigation/closeCancelled.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Thrown by `useBlade().closeChildren()` when the user keeps a child blade open
* (it has unsaved changes and the user answered "Cancel").
*
* The code after `await closeChildren()` usually deletes, moves or reloads the record the
* child edits, so stopping it is the point: the rejection ends the caller without a check.
* vc-shell treats it as a cancellation, not a failure: its error handlers show no toast,
* no blade error banner and log nothing. Catch it with `isBladeCloseCancelled` only to do
* something on cancel. New code passes the action instead, `closeChildren(action)`, which skips
* the action without throwing.
*/
export class BladeCloseCancelledError extends Error {
constructor() {
super("A child blade was kept open");
this.name = "BladeCloseCancelledError";
}
}

/** True for the cancellation `closeChildren()` throws when the user keeps a child blade open. */
export function isBladeCloseCancelled(err: unknown): err is BladeCloseCancelledError {
return (
err instanceof BladeCloseCancelledError || (err as { name?: unknown } | null)?.name === "BladeCloseCancelledError"
);
}
1 change: 1 addition & 0 deletions framework/core/blade-navigation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
export { useBladeStack } from "@core/blade-navigation/useBladeStack";
export { useBladeMessaging } from "@core/blade-navigation/useBladeMessaging";
export * from "@core/blade-navigation/types";
export { BladeCloseCancelledError, isBladeCloseCancelled } from "@core/blade-navigation/closeCancelled";
export { __registerBladeConfig, getBladeConfig, getAllBladeConfigs } from "@core/blade-navigation/bladeConfigRegistry";
// Table query-state: page-facing pull-accessor only. The TableQueryStateKey service
// and createBladeQueryState factory stay internal (consumed directly by VcDataTable
Expand Down
6 changes: 3 additions & 3 deletions framework/core/blade-navigation/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ export interface IBladeStack {
/** The last visible blade */
readonly activeBlade: ComputedRef<BladeDescriptor | undefined>;

/** Switch to a different workspace — clears all existing blades */
/** Switch to a different workspace — closes all existing blades, respecting their guards */
openWorkspace(event: BladeOpenEvent): Promise<void>;
/** Open a new blade as a child of the active blade */
openBlade(event: BladeOpenEvent & { parentId?: string }): Promise<void>;
Expand All @@ -214,8 +214,8 @@ export interface IBladeStack {
replaceCurrentBlade(event: BladeOpenEvent & { parentId?: string }): Promise<void>;
/** Cover the current blade — hides it and opens a new blade on top (closing reveals the hidden blade) */
coverCurrentBlade(event: BladeOpenEvent & { parentId?: string }): Promise<void>;
/** Close all children of a blade (deepest first, respecting guards) */
closeChildren(parentId: string): Promise<void>;
/** Close all children of a blade (deepest first, respecting guards). Returns true if a guard prevented the close. */
closeChildren(parentId: string): Promise<boolean>;

/**
* Register a before-close guard for a blade.
Expand Down
51 changes: 51 additions & 0 deletions framework/core/blade-navigation/useBladeStack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,29 @@ describe("createBladeStack", () => {
expect(stack.workspace.value?.name).toBe("Products");
});

it("keeps the stack when an open blade refuses to close", async () => {
await stack.openWorkspace({ name: "Orders" });
await stack.openBlade({ name: "OrderDetails", param: "123" });
const childId = stack.activeBlade.value!.id;
stack.registerBeforeClose(childId, async () => true);

await stack.openWorkspace({ name: "Products" });

expect(stack.workspace.value?.name).toBe("Orders");
expect(stack.activeBlade.value?.id).toBe(childId);
});

it("asks the workspace blade too before switching", async () => {
await stack.openWorkspace({ name: "Orders" });
const guard = vi.fn(async () => false);
stack.registerBeforeClose(stack.workspace.value!.id, guard);

await stack.openWorkspace({ name: "Products" });

expect(guard).toHaveBeenCalledOnce();
expect(stack.workspace.value?.name).toBe("Products");
});

it("is a no-op when opening the same workspace", async () => {
await stack.openWorkspace({ name: "Orders" });
const firstId = stack.workspace.value!.id;
Expand Down Expand Up @@ -213,6 +236,34 @@ describe("createBladeStack", () => {

// ── closeBlade ─────────────────────────────────────────────────────────────

describe("closeChildren", () => {
it("closes the children and reports nothing prevented it", async () => {
await stack.openWorkspace({ name: "Orders" });
await stack.openBlade({ name: "OrderDetails", param: "123" });

const prevented = await stack.closeChildren(stack.workspace.value!.id);

expect(prevented).toBe(false);
expect(stack.blades.value).toHaveLength(1);
});

it("reports that a child refused to close, so the parent can stop", async () => {
await stack.openWorkspace({ name: "Orders" });
await stack.openBlade({ name: "OrderDetails", param: "123" });
stack.registerBeforeClose(stack.activeBlade.value!.id, async () => true);

const prevented = await stack.closeChildren(stack.workspace.value!.id);

expect(prevented).toBe(true);
expect(stack.blades.value).toHaveLength(2);
});

it("reports nothing prevented when there are no children", async () => {
await stack.openWorkspace({ name: "Orders" });
expect(await stack.closeChildren(stack.workspace.value!.id)).toBe(false);
});
});

describe("closeBlade", () => {
beforeEach(async () => {
await stack.openWorkspace({ name: "Orders" });
Expand Down
23 changes: 13 additions & 10 deletions framework/core/blade-navigation/useBladeStack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,10 @@ export function createBladeStack(
return false;
}

// Close all existing blades (no guards — workspace switch is unconditional)
_closeBladesCleanup([..._blades.value]);
// Switching the workspace closes every blade, so each one may refuse (unsaved changes)
const bladesToClose = [..._blades.value];
if (await _checkGuards(bladesToClose)) return false;
_closeBladesCleanup(bladesToClose);

// Create workspace descriptor
const descriptor = createWorkspaceDescriptor(event, _descriptorCtx);
Expand Down Expand Up @@ -327,22 +329,21 @@ export function createBladeStack(

// ── Close Children ──────────────────────────────────────────────────────

/** @returns true when children were actually closed. */
async function _closeChildren(parentId: string): Promise<boolean> {
async function _closeChildren(parentId: string): Promise<CloseOutcome> {
const parentIndex = _blades.value.findIndex((b) => b.id === parentId);
if (parentIndex === -1) return false;
if (parentIndex === -1) return "refused";

const children = _blades.value.slice(parentIndex + 1);
if (children.length === 0) return false;
if (children.length === 0) return "refused";

// Check guards (deepest first)
const prevented = await _checkGuards(children);
if (prevented) return false;
if (prevented) return "prevented";

// Cleanup and remove
_closeBladesCleanup(children);
_blades.value = _blades.value.slice(0, parentIndex + 1);
return true;
return "closed";
}

// URL sync. The sink resolves the location from this stack, so it runs after the
Expand Down Expand Up @@ -376,8 +377,10 @@ export function createBladeStack(
return outcome === "prevented";
}

async function closeChildren(parentId: string): Promise<void> {
if (await _closeChildren(parentId)) urlSink.replace();
async function closeChildren(parentId: string): Promise<boolean> {
const outcome = await _closeChildren(parentId);
if (outcome === "closed") urlSink.replace();
return outcome === "prevented";
}

// ── Guards ────────────────────────────────────────────────────────────────
Expand Down
74 changes: 74 additions & 0 deletions framework/core/blade-navigation/utils/bladeRouterGuard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ describe("bladeRouterGuard", () => {
registry = createMockRegistry({
Orders: { route: "/orders", isWorkspace: true },
OrderDetails: { route: "/order", routable: true },
Products: { route: "/products", isWorkspace: true },
});
stack = createBladeStack(registry);
});
Expand Down Expand Up @@ -269,6 +270,33 @@ describe("bladeRouterGuard", () => {
});
});

describe("switching to another workspace", () => {
it("cancels navigation when an open blade refuses to close", async () => {
await stack.openWorkspace({ name: "Orders" });
await stack.openBlade({ name: "OrderDetails", param: "123" });
stack.registerBeforeClose(stack.blades.value[1].id, async () => true);

const to = mockRoute({ path: "/products", matched: [rootRecord, catchAllRecord] });
const result = await bladeRouterGuard(to, stack, registry);

expect(result).toBe(false);
expect(stack.workspace.value?.name).toBe("Orders");
expect(stack.blades.value).toHaveLength(2);
});

it("switches when the open blades agree to close", async () => {
await stack.openWorkspace({ name: "Orders" });
await stack.openBlade({ name: "OrderDetails", param: "123" });
stack.registerBeforeClose(stack.blades.value[1].id, async () => false);

const to = mockRoute({ path: "/products", matched: [rootRecord, catchAllRecord] });
const result = await bladeRouterGuard(to, stack, registry);

expect(result).toBeUndefined();
expect(stack.workspace.value?.name).toBe("Products");
});
});

// ── Addresses restoreFromUrl can't open ───────────────────────────────

describe("an address with no workspace", () => {
Expand Down Expand Up @@ -346,6 +374,52 @@ describe("bladeRouterGuard", () => {
});
});

// ── Deep link into a remote module ──────────────────────────────────────

describe("a deep link to a blade of a module that is still loading", () => {
it("keeps the address and opens the blade when the host replays it", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const Empty = { render: () => null };
// The module registers its blades only after it loads
const blades: Record<string, { route?: string; isWorkspace?: boolean }> = {};
const lazyRegistry: IBladeRegistry = {
registeredBladesMap: computed(() => new Map()),
getBlade: (name) => createMockRegistry(blades).getBlade(name),
getBladeComponent: () => undefined,
getBladeByRoute: (route) => createMockRegistry(blades).getBladeByRoute(route),
};
const lazyStack = createBladeStack(lazyRegistry);
let loading = true;
const router = createRouter({
history: createMemoryHistory(),
routes: [
{
path: "/",
name: "App",
component: Empty,
meta: { root: true },
children: [{ path: "", name: "Home", component: Empty }],
},
],
});
router.addRoute("App", { path: ":pathMatch(.*)*", component: Empty, meta: { bladeCatchAll: true } });
router.beforeEach((to) => bladeRouterGuard(to, lazyStack, lazyRegistry, undefined, router, () => loading));

await router.push("/reviews");
expect(router.options.history.location).toBe("/reviews");
expect(lazyStack.workspace.value).toBeUndefined();

// The module loads, then the host replays the address
blades.Reviews = { route: "/reviews", isWorkspace: true };
loading = false;
await router.replace({ path: "/reviews", force: true });

expect(lazyStack.workspace.value?.name).toBe("Reviews");
expect(router.options.history.location).toBe("/reviews");
vi.restoreAllMocks();
});
});

// ── Tenant prefix ──────────────────────────────────────────────────────

describe("tenant prefix handling", () => {
Expand Down
16 changes: 15 additions & 1 deletion framework/core/blade-navigation/utils/bladeRouterGuard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export async function bladeRouterGuard(
bladeRegistry: UseBladeRegistryReturn,
hasAccess?: (permissions: string | string[] | undefined) => boolean,
router?: Router,
modulesLoading?: () => boolean,
): Promise<BladeGuardResult> {
// Only process routes under the root (App) route
if (!to.matched.some((r) => r.meta?.root)) return undefined;
Expand Down Expand Up @@ -93,7 +94,20 @@ export async function bladeRouterGuard(
>;

// Restore blade stack from URL (idempotent — skips if already matching)
const restored = await restoreFromUrl(bladeStack, bladeRegistry, parsed, hasAccess, router, routeParams);
const restored = await restoreFromUrl(
bladeStack,
bladeRegistry,
parsed,
hasAccess,
router,
routeParams,
modulesLoading,
);

// An open blade refused to close, so stay where the user is
if (restored === "prevented") {
return false;
}

// A URL that can't be opened goes to the main route, by returning the redirect: Vue Router then
// replaces the URL itself, which a navigation started from inside this guard can't do reliably
Expand Down
Loading
Loading