mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
fix: Improve floating surface and menu selection contrast (#6670)
## Problem Autocomplete suggestions were hard to distinguish in dark mode. Dropdowns and dialogs did not have a clear depth order, and Select opened against its trigger. ## Result Floating surfaces become slightly darker in light mode and lighter in dark mode. Select opens 4 px below its control. Highlighted rows, intent colors, and disabled states remain distinguishable on the new surfaces. The theme still uses nine live inputs. Shared color recipes and a smaller CSS reader replace repeated calculations and authoring-policy checks. Missing references, cycles, duplicate definitions, and selector ownership are still checked during type generation. Components keep the same generated semantic color types. ## Plan and todos 1. [x] Define floating surface levels from the existing theme colors for both modes. 2. [x] Apply them to dialogs, menus, nested menus, popovers, commands, canvas controls, arrows, and borders. 3. [x] Keep highlighted menu, command, and inset-list rows visible. 4. [x] Remove the Builder spacing popover's base-background override. 5. [x] Add Storybook examples for dropdown over dialog, canvas toolbar, and badge. 6. [x] Add a 4 px gap to the shared Select used by Position and Display. 7. [x] Check primary, secondary, accent, error, and status contrast on floating levels. 8. [x] Document the palette rule in the design-system color guide. 9. [x] Review the selected light and dark stories listed in earlier validation. This was not an exhaustive UI-state audit. 10. [x] Run design-system tests, relevant typechecks, lint, formatting, package boundaries, and diff checks. 11. [x] Fix the audit's text, destructive-control, style-source, disabled-hover, and vivid-theme contrast failures. 12. [x] Review product documentation and fixture impact. 13. [ ] Monitor CI for the current commit and complete visual-difference approval. 14. [x] Replace floating-only intent colors with shared semantic colors. 15. [x] Make InsetList selection follow its actual containing surface. 16. [x] Consolidate color recipes and contrast-pair definitions while preserving rendered colors. 17. [x] Simplify CSS parsing and verify all nine theme controls in both modes. 18. [x] Remove redundant declaration collection while retaining exact validation behavior. 19. [x] Reproduce and fix the Grid generator contrast and CSS value footer reports in real Storybook compositions, cover missing open/hover/selected states in both modes, and record actual audit coverage and remaining gaps. 20. [ ] Audit every Builder, Dashboard, and design-system interface in light and dark mode: inventory components and reachable states, render all stories, exercise hover/focus/active/selected/disabled/open/error/loading/empty states, add missing compositions, inspect screenshots and actual contrast, and publish findings with evidence and unresolved coverage gaps. 21. [x] Soften floating-surface contrast in light and dark themes, align the Grid generator's preview outline with its grid lines, and verify focused stories, regression checks, and documentation impact. 22. [x] Make shared popover headers and bodies use one background color, check Grid settings and other callers in both themes, add regression coverage, and review documentation impact. 23. [x] Reduce the shared Grid generator and selector line contrast in both themes, keep the preview outline matched, verify visibility and Storybook states, and review documentation impact. ## Validation Palette-refactor validation below applies to `07d11239f5`. The Storybook coverage follow-up is `e38d25537d`. - All 284 design-system tests passed, plus design-system typecheck, focused lint, formatting, and diff checks. - A Chromium comparison found identical rendered RGBA values for 1,312 samples across both modes and 16 theme configurations before and after the recipe refactor. - All 50 contrast contracts remain. The new theme-control checks cover every generated public theme input in both modes. - Deliberate temporary mutations confirmed the new checks fail when the protected behavior breaks. - Independent Astra reviews found no new defects. The final cleanup matched exact outputs or errors for 167 valid and invalid parser inputs. - Current parsed source output and generated token types are unchanged. - Earlier Builder typechecks and package-boundary checks passed. This refactor changes no public component API. - No fixture inputs or generated fixture bundles are affected. The design-system README was updated; the product Craft documentation still matches the behavior. The latest commit removes 342 net implementation lines, excluding tests and documentation. The color parser is 152 lines, the stylesheet 253, and the contrast helper 127. CSS still performs all runtime color calculation; the parser supports type generation and Storybook. All non-visual CI checks passed for this commit. The visual-regression job was cancelled before producing its comparison report, so visual CI is not complete. The visual approval label has not been applied. ## Visual coverage correction The previous palette tests and selected screenshots did not establish that every Builder interface and state had been inspected. The Grid generator had no direct story, and the CSS fragment story did not open the dialog or render its shortcut footer. Both reported defects were reproduced in new open stories in light and dark mode. Both fixes are verified locally and included in `e38d25537d`. Grid open, selected, hover, preset-hover, and keyboard-focus states were captured; the CSS dialog was captured normal and maximized in both modes. The grid's weakest measured outline contrast is 3.176:1, up from about 1.1:1 against the panel. The footer no longer paints a base-surface strip inside the floating dialog. All 11 focused browser tests, Builder typecheck, six-file lint, formatting, and diff checks passed. Temporary old-style mutations made all four new light/dark regression cases fail; restoring the fixes made them pass. Independent review found no remaining defects in these fixes. Runtime code grows by five net lines; stories add 110 lines, including shared-store setup and restoration for repeatable rendering. No fixture bundles or product documentation are affected. The follow-up adds 217 story cases, including actual dialogs, canvas overlays, collection and resource loading/error states, confirmations, and editor states. Stories use real components and local HTTP responses. Builder and design-system typechecks, focused lint, formatting, and diff checks pass. No published-project fixture inputs or generated bundles are affected. The broader contrast audit remains in progress. Its source inventory covers 416 JSX interface files; the current Storybook scope is 427 stories in both themes. Render captures and interaction-state probes are tracked separately. Confirmed remaining problems include error-page heading contrast, collaborator labels, grid guides over different canvas colors, position dots, keyboard hints, pressed secondary labels, editor punctuation, and color-picker unit labels/surfaces. These findings are not fixed by this commit. Task 20 remains open until the remaining interactions and evidence review are complete. CI for `bd1d6349bc` is running; task 13 remains open pending required checks and visual review. ## Contrast follow-up Floating surfaces are softer in both themes, especially light mode, while keeping the intended light and dark surface directions. The Grid preview outline matches its internal lines except during visible keyboard focus. New browser regressions failed before the fix and pass afterward in both modes. Storybook captures of the open Grid generator and dialog with dropdown were reviewed in light and dark mode. Design-system tests (284), focused Builder tests (2), both package typechecks, focused lint, formatting, and diff checks pass. The Craft docs and design-system color guide still describe this behavior; no documentation or fixture input/output changes are needed. These changes are included in `5558d2ab12`, and task 21 is complete. ## Popover surface follow-up The Style panel passes its primary section background and sticky header setting into portalled Grid settings. The shared floating panel now marks its surface, and Builder sections inside it use the same floating background as the panel title and body. The Grid settings Storybook story reproduces the real Style panel context. New light and dark browser regressions failed before the fix and pass afterward. Reviewed Grid settings, a plain FloatingPanel, and a titled Popover in both modes; direct Popover keeps its raised surface. Design-system tests (284), focused Builder tests (4), both package typechecks, focused lint, formatting, and diff checks pass. No product documentation or fixture inputs/outputs change. These changes are included in `6839897bb2`, and task 22 is complete. ## Grid line contrast follow-up The shared Grid line mix is reduced from 75% to 60% foreground-secondary. In Chromium, gray selector and preset-cell borders now measure 2.323:1 in light mode and 2.550:1 in dark mode against their cell fills, down from 3.134:1 and 3.415:1. The preview line measures 2.803:1 and 2.964:1 against its surrounding body surface; its outer outline uses the exact same color. Selected and hover focus-color cues remain unchanged. These gray strokes are softer and remain visible, but their cell-border ratios are below the Craft guide's 3:1 target for meaningful non-text graphics. The focused browser regressions failed before the edit and pass afterward in both themes. Grid generator and selector Storybook states were reviewed in light and dark mode. Builder typecheck, focused lint, formatting, and diff checks pass. Product documentation and fixture inputs/outputs are unaffected. This change is included in `bd1d6349bc`, and task 23 is complete.
This commit is contained in:
1 parent
0589b18ce2
commit
89ca46cd7f
85 files changed
+5744
-1317
No files matched your search
@@ -56,7 +56,7 @@ jobs:
|
||||
)
|
||||
)
|
||||
timeout-minutes: 7
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
environment:
|
||||
name: development
|
||||
steps:
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import "./request-fixtures";
|
||||
import { updateCsrfToken } from "../apps/builder/app/shared/csrf.client";
|
||||
|
||||
// Use a synthetic CSRF value in the isolated Storybook environment.
|
||||
updateCsrfToken("storybook-fixture");
|
||||
import type { Preview } from "@storybook/react";
|
||||
import * as React from "react";
|
||||
import { useEffect, useLayoutEffect, type ReactNode } from "react";
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/** Story-only HTTP boundary. Install before stories import clients that capture fetch. */
|
||||
export type RequestFixture = (
|
||||
request: Request
|
||||
) => Response | Promise<Response> | undefined;
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
let fixture: RequestFixture | undefined;
|
||||
|
||||
globalThis.fetch = async (input, init) => {
|
||||
if (fixture === undefined) {
|
||||
return originalFetch(input, init);
|
||||
}
|
||||
const request = new Request(
|
||||
typeof input === "string" ? new URL(input, location.href) : input,
|
||||
init
|
||||
);
|
||||
const response = fixture(request);
|
||||
return response === undefined ? originalFetch(input, init) : response;
|
||||
};
|
||||
|
||||
export const setRequestFixture = (next: RequestFixture) => {
|
||||
const previous = fixture;
|
||||
fixture = next;
|
||||
return () => {
|
||||
fixture = previous;
|
||||
};
|
||||
};
|
||||
@@ -31,3 +31,16 @@ export const Auth: StoryFn<typeof LoginComponent> = () => {
|
||||
|
||||
export const Dark = Auth.bind({});
|
||||
Dark.globals = { colorScheme: "dark" };
|
||||
|
||||
export const Error = () => {
|
||||
const router = createRouter(
|
||||
<LoginComponent
|
||||
isGoogleEnabled
|
||||
isGithubEnabled={false}
|
||||
isSecretLoginEnabled
|
||||
errorMessage="Authentication failed"
|
||||
devPlanNames={["Free", "Pro"]}
|
||||
/>
|
||||
);
|
||||
return <RouterProvider router={router} />;
|
||||
};
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import {
|
||||
createAssetFolderFixture,
|
||||
createAssetFoldersFixture,
|
||||
} from "@webstudio-is/sdk/testing";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";
|
||||
import {
|
||||
assetContentDescriptorHeader,
|
||||
serializeAssetContentDescriptor,
|
||||
} from "@webstudio-is/protocol/asset-resource-api";
|
||||
import {
|
||||
createAssetContentBridge,
|
||||
getAssetContentBridge,
|
||||
__testing__,
|
||||
} from "~/shared/asset-content-bridge.client";
|
||||
import {
|
||||
$assets,
|
||||
$assetFolders,
|
||||
$pages,
|
||||
$project,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { $authPermit, $builderMode } from "~/shared/nano-states";
|
||||
import { $settings } from "~/builder/shared/client-settings";
|
||||
import { AssetsPanel } from "./assets";
|
||||
const { initBridge, clearBridge } = __testing__;
|
||||
export default { title: "Assets/Collections", component: AssetsPanel };
|
||||
type State =
|
||||
| "ready"
|
||||
| "loading"
|
||||
| "invalid"
|
||||
| "missingTemplate"
|
||||
| "unavailable"
|
||||
| "entryWarning"
|
||||
| "readOnly";
|
||||
const CollectionStory = ({ state }: { state: State }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = [
|
||||
$assets.get(),
|
||||
$assetFolders.get(),
|
||||
$pages.get(),
|
||||
$project.get(),
|
||||
$authPermit.get(),
|
||||
$builderMode.get(),
|
||||
$settings.get(),
|
||||
] as const;
|
||||
let previousBridge: ReturnType<typeof getAssetContentBridge> | undefined;
|
||||
try {
|
||||
previousBridge = getAssetContentBridge();
|
||||
} catch {}
|
||||
const projectId = `collection-story-${state}`;
|
||||
const sources = new Map([
|
||||
[
|
||||
"collection.json",
|
||||
state === "invalid" ? "{}" : createDefaultCollectionConfig(),
|
||||
],
|
||||
[
|
||||
"template.mdx",
|
||||
"---\ntitle: Article\nslug: article\ndraft: true\n---\n# Article",
|
||||
],
|
||||
[
|
||||
"post.mdx",
|
||||
state === "entryWarning"
|
||||
? "---\ntitle: \nslug: wrong\ndraft: yes\n---\nBody"
|
||||
: "---\ntitle: Post\nslug: post\ndraft: false\n---\nBody",
|
||||
],
|
||||
]);
|
||||
if (state === "missingTemplate") {
|
||||
sources.delete("template.mdx");
|
||||
}
|
||||
const files: Asset[] = Array.from(sources, ([name, source]) => ({
|
||||
id: name,
|
||||
name,
|
||||
projectId,
|
||||
folderId: "posts",
|
||||
type: "file",
|
||||
format: name.endsWith("json") ? "json" : "mdx",
|
||||
size: new TextEncoder().encode(source).length,
|
||||
meta: {},
|
||||
createdAt: "2026-11-01T00:00:00Z",
|
||||
}));
|
||||
initBridge(
|
||||
createAssetContentBridge({
|
||||
origin: location.origin,
|
||||
authorize: () => true,
|
||||
requireReload: () => {},
|
||||
request: async (url, init) => {
|
||||
if (state === "loading") {
|
||||
return new Promise<Response>(() => {});
|
||||
}
|
||||
if (state === "unavailable") {
|
||||
throw new Error("Example offline response");
|
||||
}
|
||||
if (init?.method && init.method !== "GET") {
|
||||
return new Response(undefined, { status: 403 });
|
||||
}
|
||||
const name = decodeURIComponent(new URL(url).pathname.split("/")[3]);
|
||||
const asset = files.find((file) => file.id === name);
|
||||
if (!asset) {
|
||||
return new Response(undefined, { status: 404 });
|
||||
}
|
||||
return new Response(sources.get(name), {
|
||||
// Each fixture fits in the initial frontmatter read range.
|
||||
status: new Headers(init?.headers).has("range") ? 206 : 200,
|
||||
headers: {
|
||||
[assetContentDescriptorHeader]:
|
||||
serializeAssetContentDescriptor(asset),
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
);
|
||||
$project.set({ id: projectId, title: "Collection example" } as Project);
|
||||
$assets.set(new Map(files.map((file) => [file.id, file])));
|
||||
$assetFolders.set(
|
||||
createAssetFoldersFixture(
|
||||
createAssetFolderFixture({ id: "posts", name: "Posts" })
|
||||
)
|
||||
);
|
||||
$pages.set(createDefaultPages({ rootInstanceId: "body" }));
|
||||
$authPermit.set(state === "readOnly" ? "view" : "own");
|
||||
$builderMode.set("design");
|
||||
$settings.set({
|
||||
...$settings.get(),
|
||||
lastAssetFolderIds: { [projectId]: "posts" },
|
||||
});
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$assets.set(previous[0]);
|
||||
$assetFolders.set(previous[1]);
|
||||
$pages.set(previous[2]);
|
||||
$project.set(previous[3]);
|
||||
$authPermit.set(previous[4]);
|
||||
$builderMode.set(previous[5]);
|
||||
$settings.set(previous[6]);
|
||||
if (previousBridge) {
|
||||
initBridge(previousBridge);
|
||||
} else {
|
||||
clearBridge();
|
||||
}
|
||||
};
|
||||
}, [state]);
|
||||
return ready ? (
|
||||
<div
|
||||
style={{
|
||||
width: 320,
|
||||
height: 800,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<AssetsPanel publish={() => {}} onClose={() => {}} />
|
||||
</div>
|
||||
) : null;
|
||||
};
|
||||
export const Ready = () => <CollectionStory state="ready" />;
|
||||
export const Loading = () => <CollectionStory state="loading" />;
|
||||
export const InvalidConfiguration = () => <CollectionStory state="invalid" />;
|
||||
export const MissingTemplate = () => (
|
||||
<CollectionStory state="missingTemplate" />
|
||||
);
|
||||
export const Unavailable = () => <CollectionStory state="unavailable" />;
|
||||
export const EntryWarning = () => <CollectionStory state="entryWarning" />;
|
||||
export const ReadOnly = () => <CollectionStory state="readOnly" />;
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, StorySection } from "@webstudio-is/design-system";
|
||||
import type { Breakpoint } from "@webstudio-is/sdk";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { BreakpointsEditor } from "./breakpoints-editor";
|
||||
import { ConfirmationDialog } from "./confirmation-dialog";
|
||||
|
||||
const desktop: Breakpoint = {
|
||||
id: "desktop",
|
||||
label: "Desktop",
|
||||
minWidth: 1280,
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Builder/Breakpoints editor",
|
||||
component: BreakpointsEditor,
|
||||
};
|
||||
|
||||
const BreakpointsStory = ({ empty = false }: { empty?: boolean }) => {
|
||||
const [open, setOpen] = useState(true);
|
||||
const [toDelete, setToDelete] = useState<Breakpoint>();
|
||||
useEffect(() => {
|
||||
const previous = $breakpoints.get();
|
||||
$breakpoints.set(
|
||||
new Map(
|
||||
empty
|
||||
? []
|
||||
: [
|
||||
["base", { id: "base", label: "" }],
|
||||
[desktop.id, desktop],
|
||||
["mobile", { id: "mobile", label: "Mobile", maxWidth: 767 }],
|
||||
]
|
||||
)
|
||||
);
|
||||
return () => $breakpoints.set(previous);
|
||||
}, [empty]);
|
||||
return (
|
||||
<StorySection title="Breakpoints">
|
||||
<BreakpointsEditor
|
||||
open={open && toDelete === undefined}
|
||||
onOpenChange={setOpen}
|
||||
onDelete={(breakpoint) => setToDelete(breakpoint)}
|
||||
>
|
||||
<Button>Breakpoints</Button>
|
||||
</BreakpointsEditor>
|
||||
{toDelete && (
|
||||
<ConfirmationDialog
|
||||
open
|
||||
breakpoint={toDelete}
|
||||
onAbort={() => setToDelete(undefined)}
|
||||
onConfirm={() => setToDelete(undefined)}
|
||||
/>
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Populated = () => <BreakpointsStory />;
|
||||
export const Empty = () => <BreakpointsStory empty />;
|
||||
export const DeleteConfirmation = () => (
|
||||
<ConfirmationDialog
|
||||
open
|
||||
breakpoint={desktop}
|
||||
onAbort={() => {}}
|
||||
onConfirm={() => {}}
|
||||
/>
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useEffect } from "react";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $canvasWidth } from "~/builder/shared/nano-states";
|
||||
import { CanvasSettingsPopover } from "./canvas-settings-popover";
|
||||
|
||||
export default { title: "Canvas settings", component: CanvasSettingsPopover };
|
||||
export const CanvasSettings = () => {
|
||||
useEffect(() => {
|
||||
const previous = [
|
||||
$breakpoints.get(),
|
||||
$selectedBreakpointId.get(),
|
||||
$canvasWidth.get(),
|
||||
] as const;
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$canvasWidth.set(1280);
|
||||
return () => {
|
||||
$breakpoints.set(previous[0]);
|
||||
$selectedBreakpointId.set(previous[1]);
|
||||
$canvasWidth.set(previous[2]);
|
||||
};
|
||||
}, []);
|
||||
return <CanvasSettingsPopover />;
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useState } from "react";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import type { WebstudioData } from "@webstudio-is/sdk";
|
||||
import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";
|
||||
import { Overview } from "./overview";
|
||||
import { Templates } from "./templates";
|
||||
export default { title: "Builder/Marketplace/Gallery", component: Overview };
|
||||
const items: MarketplaceOverviewItem[] = [
|
||||
{
|
||||
projectId: "section",
|
||||
category: "sectionTemplates",
|
||||
name: "Sections",
|
||||
author: "Webstudio team",
|
||||
thumbnailAssetId: "",
|
||||
email: "team@example.com",
|
||||
description: "Section templates",
|
||||
},
|
||||
{
|
||||
projectId: "pages",
|
||||
category: "pageTemplates",
|
||||
name: "Pages",
|
||||
author: "Webstudio team",
|
||||
thumbnailAssetId: "",
|
||||
email: "team@example.com",
|
||||
description: "Page templates",
|
||||
},
|
||||
];
|
||||
const GalleryStory = ({
|
||||
loading = false,
|
||||
selected = false,
|
||||
empty = false,
|
||||
}: {
|
||||
loading?: boolean;
|
||||
selected?: boolean;
|
||||
empty?: boolean;
|
||||
}) => {
|
||||
const [active, setActive] = useState<string | undefined>(
|
||||
loading ? "section" : undefined
|
||||
);
|
||||
const [about, setAbout] = useState<string | undefined>(
|
||||
selected ? "section" : undefined
|
||||
);
|
||||
return (
|
||||
<div style={{ width: 320, height: 700 }}>
|
||||
<Overview
|
||||
items={empty ? [] : items}
|
||||
activeProjectId={active}
|
||||
openAbout={about}
|
||||
onOpenAbout={setAbout}
|
||||
onSelect={(item) => setActive(item.projectId)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export const Default = () => <GalleryStory />;
|
||||
export const Loading = () => <GalleryStory loading />;
|
||||
export const Selected = () => <GalleryStory selected />;
|
||||
export const Empty = () => <GalleryStory empty />;
|
||||
const pages = createDefaultPages({ rootInstanceId: "body" });
|
||||
pages.pages.get(pages.homePageId)!.marketplace = {
|
||||
include: true,
|
||||
category: "Sections",
|
||||
};
|
||||
const data: WebstudioData = {
|
||||
pages,
|
||||
assets: new Map(),
|
||||
breakpoints: new Map(),
|
||||
dataSources: new Map(),
|
||||
instances: new Map([
|
||||
["body", { id: "body", type: "instance", component: "Body", children: [] }],
|
||||
]),
|
||||
props: new Map(),
|
||||
resources: new Map(),
|
||||
styles: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
};
|
||||
const TemplatesStory = ({ authorized = false }: { authorized?: boolean }) => (
|
||||
<div style={{ width: 320, height: 700 }}>
|
||||
<Templates
|
||||
name="Sections"
|
||||
projectId="example-project"
|
||||
productCategory="sectionTemplates"
|
||||
authorizationToken={authorized ? "storybook-example" : undefined}
|
||||
data={data}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
export const TemplatesAvailable = () => <TemplatesStory authorized />;
|
||||
export const TemplatesWithoutShareLink = () => <TemplatesStory />;
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import {
|
||||
blockBodyComponent,
|
||||
blockComponent,
|
||||
contentBlockSourceProp,
|
||||
coreMetas,
|
||||
elementComponent,
|
||||
type Instance,
|
||||
} from "@webstudio-is/sdk";
|
||||
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$builderMode,
|
||||
$editingItemSelector,
|
||||
$registeredComponentMetas,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
selectInstances,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances, $pages, $props } from "~/shared/sync/data-stores";
|
||||
import { $externalContentRoots } from "~/shared/external-content-mutations";
|
||||
import { NavigatorPanel } from "./navigator";
|
||||
|
||||
type State =
|
||||
| "design"
|
||||
| "no-content"
|
||||
| "content"
|
||||
| "mdx"
|
||||
| "multi"
|
||||
| "menu"
|
||||
| "rename";
|
||||
|
||||
export default { title: "Navigator/Panel", component: NavigatorPanel };
|
||||
|
||||
const NavigatorStory = ({ state }: { state: State }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
builderMode: $builderMode.get(),
|
||||
metas: $registeredComponentMetas.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
props: $props.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
editingItem: $editingItemSelector.get(),
|
||||
externalRoots: $externalContentRoots.get(),
|
||||
};
|
||||
const isContent =
|
||||
state === "no-content" || state === "content" || state === "mdx";
|
||||
const bodyChildren =
|
||||
state === "no-content"
|
||||
? []
|
||||
: isContent
|
||||
? [{ type: "id" as const, value: "block" }]
|
||||
: ["first", "second", "third"].map((value) => ({
|
||||
type: "id" as const,
|
||||
value,
|
||||
}));
|
||||
const instances: Instance[] = [
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: bodyChildren,
|
||||
},
|
||||
...(isContent && state !== "no-content"
|
||||
? [
|
||||
{
|
||||
type: "instance" as const,
|
||||
id: "block",
|
||||
component: blockComponent,
|
||||
label: "Article",
|
||||
children: [
|
||||
{
|
||||
type: "id" as const,
|
||||
value: state === "mdx" ? "mdx" : "heading",
|
||||
},
|
||||
],
|
||||
},
|
||||
state === "mdx"
|
||||
? {
|
||||
type: "instance" as const,
|
||||
id: "mdx",
|
||||
component: blockBodyComponent,
|
||||
children: [],
|
||||
}
|
||||
: {
|
||||
type: "instance" as const,
|
||||
id: "heading",
|
||||
component: elementComponent,
|
||||
tag: "h1",
|
||||
label: "Article heading",
|
||||
children: [
|
||||
{ type: "text" as const, value: "Article heading" },
|
||||
],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(!isContent
|
||||
? ["first", "second", "third"].map(
|
||||
(id): Instance => ({
|
||||
type: "instance",
|
||||
id,
|
||||
component: elementComponent,
|
||||
tag: "div",
|
||||
label: `${id[0].toUpperCase()}${id.slice(1)} box`,
|
||||
children: [],
|
||||
})
|
||||
)
|
||||
: []),
|
||||
];
|
||||
$registeredComponentMetas.set(
|
||||
new Map(Object.entries({ ...coreMetas, ...baseComponentMetas }))
|
||||
);
|
||||
$instances.set(
|
||||
new Map(instances.map((instance) => [instance.id, instance]))
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
|
||||
);
|
||||
$props.set(
|
||||
state === "mdx"
|
||||
? new Map([
|
||||
[
|
||||
"source",
|
||||
{
|
||||
id: "source",
|
||||
instanceId: "block",
|
||||
name: contentBlockSourceProp,
|
||||
type: "asset" as const,
|
||||
value: "article",
|
||||
},
|
||||
],
|
||||
])
|
||||
: new Map()
|
||||
);
|
||||
$externalContentRoots.set(new Map());
|
||||
$selectedPageId.set("home");
|
||||
$builderMode.set(isContent ? "content" : "design");
|
||||
if (state === "multi") {
|
||||
selectInstances([
|
||||
["first", "body"],
|
||||
["second", "body"],
|
||||
]);
|
||||
} else if (state === "rename") {
|
||||
selectInstance(["first", "body"]);
|
||||
$editingItemSelector.set(["first", "body"]);
|
||||
} else if (state === "mdx") {
|
||||
selectInstance(["mdx", "block", "body"]);
|
||||
} else if (state === "content") {
|
||||
selectInstance(["heading", "block", "body"]);
|
||||
} else {
|
||||
selectInstance(["first", "body"]);
|
||||
}
|
||||
setReady(true);
|
||||
return () => {
|
||||
$builderMode.set(previous.builderMode);
|
||||
$registeredComponentMetas.set(previous.metas);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$props.set(previous.props);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$editingItemSelector.set(previous.editingItem);
|
||||
$externalContentRoots.set(previous.externalRoots);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || state !== "menu") {
|
||||
return;
|
||||
}
|
||||
const showMenu = () => {
|
||||
const row = Array.from(
|
||||
document.querySelectorAll<HTMLButtonElement>("[data-tree-button]")
|
||||
).find((item) => item.textContent?.includes("First box"));
|
||||
if (row) {
|
||||
observer.disconnect();
|
||||
row.dispatchEvent(
|
||||
new MouseEvent("contextmenu", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
button: 2,
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(showMenu);
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
showMenu();
|
||||
return () => observer.disconnect();
|
||||
}, [ready, state]);
|
||||
|
||||
return (
|
||||
<StorySection title="Navigator">
|
||||
<Box
|
||||
css={{
|
||||
width: theme.sizes.sidebarWidth,
|
||||
height: 480,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
{ready && <NavigatorPanel onClose={() => {}} />}
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Design = () => <NavigatorStory state="design" />;
|
||||
export const NoEditableContent = () => <NavigatorStory state="no-content" />;
|
||||
export const EditableContent = () => <NavigatorStory state="content" />;
|
||||
export const MdxContent = () => <NavigatorStory state="mdx" />;
|
||||
export const MultiSelection = () => <NavigatorStory state="multi" />;
|
||||
export const ContextMenu = () => <NavigatorStory state="menu" />;
|
||||
export const Rename = () => <NavigatorStory state="rename" />;
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { Dialog, DialogContent } from "@webstudio-is/design-system";
|
||||
import { $pages, $project } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$authPermit,
|
||||
$builderMode,
|
||||
$selectedPageId,
|
||||
} from "~/shared/nano-states";
|
||||
import { FolderSettings, NewFolderSettings } from "./folder-settings";
|
||||
import {
|
||||
TemplateSettings,
|
||||
NewTemplateSettings,
|
||||
CreatePageFromTemplateSettings,
|
||||
} from "./template-settings";
|
||||
import { PageSettings, NewPageSettings } from "./page-settings/page-settings";
|
||||
import { PagesPanel } from "./pages";
|
||||
|
||||
export default { title: "Pages/States", component: PagesPanel };
|
||||
|
||||
type State =
|
||||
| "tree"
|
||||
| "folder"
|
||||
| "newFolder"
|
||||
| "template"
|
||||
| "newTemplate"
|
||||
| "fromTemplate"
|
||||
| "newPage"
|
||||
| "home"
|
||||
| "draft"
|
||||
| "text"
|
||||
| "redirect"
|
||||
| "marketplace"
|
||||
| "bound";
|
||||
const PageStory = ({
|
||||
state,
|
||||
contentMode = false,
|
||||
}: {
|
||||
state: State;
|
||||
contentMode?: boolean;
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = [
|
||||
$pages.get(),
|
||||
$project.get(),
|
||||
$authPermit.get(),
|
||||
$builderMode.get(),
|
||||
$selectedPageId.get(),
|
||||
] as const;
|
||||
const pages = createDefaultPages({ rootInstanceId: "page-root" });
|
||||
const page = {
|
||||
id: "example-page",
|
||||
name: "Example page",
|
||||
title: '"Example page"',
|
||||
path: "/example",
|
||||
rootInstanceId: "page-root",
|
||||
meta: {},
|
||||
isDraft: state === "draft",
|
||||
};
|
||||
pages.pages.set(page.id, {
|
||||
...page,
|
||||
meta:
|
||||
state === "text"
|
||||
? { documentType: "text", content: '"User-agent: *\\nAllow: /"' }
|
||||
: state === "bound"
|
||||
? { description: "page.description", language: "page.language" }
|
||||
: {},
|
||||
});
|
||||
pages.folders.set("example-folder", {
|
||||
id: "example-folder",
|
||||
name: "Blog",
|
||||
slug: "blog",
|
||||
children: [page.id],
|
||||
});
|
||||
pages.folders.get(pages.rootFolderId)?.children.push("example-folder");
|
||||
pages.pageTemplates = new Map([
|
||||
[
|
||||
"example-template",
|
||||
{
|
||||
id: "example-template",
|
||||
name: "Article",
|
||||
title: '"Article"',
|
||||
rootInstanceId: "template-root",
|
||||
meta: { description: '"Article description"' },
|
||||
},
|
||||
],
|
||||
]);
|
||||
if (state === "redirect") {
|
||||
pages.redirects = [{ old: "/blog/example", new: "/", status: "301" }];
|
||||
}
|
||||
$pages.set(pages);
|
||||
$project.set({
|
||||
id: "storybook-project",
|
||||
title: "My Project",
|
||||
marketplaceApprovalStatus:
|
||||
state === "marketplace" ? "APPROVED" : "UNLISTED",
|
||||
} as Project);
|
||||
$authPermit.set("own");
|
||||
$builderMode.set(contentMode ? "content" : "design");
|
||||
$selectedPageId.set(state === "home" ? pages.homePageId : page.id);
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$pages.set(previous[0]);
|
||||
$project.set(previous[1]);
|
||||
$authPermit.set(previous[2]);
|
||||
$builderMode.set(previous[3]);
|
||||
$selectedPageId.set(previous[4]);
|
||||
};
|
||||
}, [state, contentMode]);
|
||||
if (!ready) {
|
||||
return;
|
||||
}
|
||||
if (state === "tree") {
|
||||
return (
|
||||
<div style={{ width: 280, height: 780 }}>
|
||||
<PagesPanel onClose={() => {}} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const content =
|
||||
state === "folder" ? (
|
||||
<FolderSettings
|
||||
folderId="example-folder"
|
||||
onClose={() => {}}
|
||||
onRequestDelete={() => {}}
|
||||
onDuplicate={() => {}}
|
||||
/>
|
||||
) : state === "newFolder" ? (
|
||||
<NewFolderSettings onClose={() => {}} onSuccess={() => {}} />
|
||||
) : state === "template" ? (
|
||||
<TemplateSettings
|
||||
templateId="example-template"
|
||||
onClose={() => {}}
|
||||
onDuplicate={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
) : state === "newTemplate" ? (
|
||||
<NewTemplateSettings onSuccess={() => {}} />
|
||||
) : state === "fromTemplate" ? (
|
||||
<CreatePageFromTemplateSettings
|
||||
templateId="example-template"
|
||||
onSuccess={() => {}}
|
||||
/>
|
||||
) : state === "newPage" ? (
|
||||
<NewPageSettings onSuccess={() => {}} />
|
||||
) : (
|
||||
<PageSettings
|
||||
pageId={$selectedPageId.get()!}
|
||||
onClose={() => {}}
|
||||
onDelete={() => {}}
|
||||
onDuplicate={() => {}}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Dialog open>
|
||||
<DialogContent css={{ width: 320, height: 800 }}>{content}</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
export const Tree = () => <PageStory state="tree" />;
|
||||
export const ContentTree = () => <PageStory state="tree" contentMode />;
|
||||
export const Folder = () => <PageStory state="folder" />;
|
||||
export const NewFolder = () => <PageStory state="newFolder" />;
|
||||
export const Template = () => <PageStory state="template" />;
|
||||
export const TemplateReadOnly = () => (
|
||||
<PageStory state="template" contentMode />
|
||||
);
|
||||
export const NewTemplate = () => <PageStory state="newTemplate" />;
|
||||
export const FromTemplate = () => <PageStory state="fromTemplate" />;
|
||||
export const FromTemplateContentMode = () => (
|
||||
<PageStory state="fromTemplate" contentMode />
|
||||
);
|
||||
export const NewPage = () => <PageStory state="newPage" />;
|
||||
export const Home = () => <PageStory state="home" />;
|
||||
export const Draft = () => <PageStory state="draft" />;
|
||||
export const TextDocument = () => <PageStory state="text" />;
|
||||
export const RedirectConflict = () => <PageStory state="redirect" />;
|
||||
export const Marketplace = () => <PageStory state="marketplace" />;
|
||||
export const BoundContent = () => <PageStory state="bound" contentMode />;
|
||||
@@ -16,7 +16,7 @@ const faviconDataUrl = `data:image/svg+xml,${encodeURIComponent(
|
||||
|
||||
export const SearchPreview = () => (
|
||||
<StorySection title="Search Preview">
|
||||
<Box css={{ width: 600, margin: 20 }}>
|
||||
<Box css={{ width: 600, margin: 20, background: "#fff" }}>
|
||||
<SearchPreviewComponent
|
||||
pageUrl="https://webstudio.is/blog-webstudios-architecture-an-overview"
|
||||
titleLink="Blog: Webstudio's Architecture - an overview"
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect } from "react";
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import {
|
||||
PublishValidationResults,
|
||||
type PublishValidationFinding,
|
||||
} from "./publish-validation-results";
|
||||
|
||||
export default {
|
||||
title: "Publish/Validation results",
|
||||
component: PublishValidationResults,
|
||||
};
|
||||
|
||||
const errorsAndWarnings: PublishValidationFinding[] = [
|
||||
{
|
||||
severity: "error",
|
||||
title: "Unable to complete publish validation",
|
||||
reportText: "ERROR: Unable to complete publish validation",
|
||||
},
|
||||
{
|
||||
severity: "warning",
|
||||
title:
|
||||
"Some project styles cannot be processed for publishing. Publishing can continue using base and font styles.",
|
||||
reportText:
|
||||
"Some project styles cannot be processed for publishing. Publishing can continue using base and font styles.",
|
||||
},
|
||||
];
|
||||
|
||||
const ValidationStory = ({
|
||||
findings,
|
||||
}: {
|
||||
findings: PublishValidationFinding[];
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
const open = () => {
|
||||
const button = Array.from(document.querySelectorAll("button")).find(
|
||||
(item) => item.textContent === "See issues"
|
||||
);
|
||||
if (button) {
|
||||
button.click();
|
||||
observer.disconnect();
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(open);
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
open();
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<StorySection title="Publish validation">
|
||||
<PublishValidationResults findings={findings} />
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const ErrorsAndWarnings = () => (
|
||||
<ValidationStory findings={errorsAndWarnings} />
|
||||
);
|
||||
export const WarningOnly = () => (
|
||||
<ValidationStory findings={[errorsAndWarnings[1]]} />
|
||||
);
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect } from "react";
|
||||
import { SafeModeButton } from "./safe-mode";
|
||||
|
||||
export default { title: "Builder/Safe mode", component: SafeModeButton };
|
||||
|
||||
// Open the iframe story with `safemode=true`; builderApi reads it at module load.
|
||||
export const Active = () => {
|
||||
useEffect(() => {
|
||||
if (
|
||||
new URLSearchParams(window.location.search).get("safemode") !== "true"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const open = () => {
|
||||
const button = document.querySelector<HTMLButtonElement>(
|
||||
'button[aria-label="Safe mode active"]'
|
||||
);
|
||||
if (button) {
|
||||
observer.disconnect();
|
||||
button.click();
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(open);
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
open();
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
return <SafeModeButton />;
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useState } from "react";
|
||||
import {
|
||||
createAssetQueryJsonSchema,
|
||||
createAssetResourceOpenApi,
|
||||
} from "@webstudio-is/protocol/asset-resource-api";
|
||||
import {
|
||||
createDefaultStructuredAssetQueryResourceConfiguration,
|
||||
createStructuredAssetQueryResourceBody,
|
||||
type Resource,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { AssetQueryForm } from "./asset-query-form";
|
||||
|
||||
export default {
|
||||
title: "Settings Panel/Asset query",
|
||||
component: AssetQueryForm,
|
||||
};
|
||||
const openApi = createAssetResourceOpenApi({
|
||||
builderSessionCookieName: "session",
|
||||
querySchemaReference: "/rest/assets/query-schema.json",
|
||||
});
|
||||
const querySchema = createAssetQueryJsonSchema({
|
||||
catalog: {
|
||||
format: "webstudio-builder-asset-field-catalog",
|
||||
version: 1,
|
||||
canonicalRevision: `sha256:${"a".repeat(64)}`,
|
||||
documentCount: 1,
|
||||
fields: {
|
||||
title: {
|
||||
queryPath: ["properties", "title"],
|
||||
types: ["string"],
|
||||
occurrences: 1,
|
||||
},
|
||||
draft: {
|
||||
queryPath: ["properties", "draft"],
|
||||
types: ["boolean"],
|
||||
occurrences: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const loaded: typeof fetch = async (input) =>
|
||||
Response.json(
|
||||
String(input).includes("query-schema.json") ? querySchema : openApi
|
||||
);
|
||||
const pending: typeof fetch = () => new Promise(() => {});
|
||||
const failed: typeof fetch = async () =>
|
||||
new Response(undefined, { status: 500 });
|
||||
const scope = {};
|
||||
const aliases = new Map<string, string>();
|
||||
const configuration = createDefaultStructuredAssetQueryResourceConfiguration();
|
||||
const resource: Resource = {
|
||||
id: "posts",
|
||||
name: "Posts",
|
||||
control: "system",
|
||||
method: "post",
|
||||
url: '"/$resources/assets"',
|
||||
headers: [],
|
||||
body: createStructuredAssetQueryResourceBody({
|
||||
...configuration,
|
||||
where: {
|
||||
all: [
|
||||
{ field: ["properties", "draft"], operator: "eq", value: "false" },
|
||||
{
|
||||
any: [
|
||||
{
|
||||
field: ["properties", "title"],
|
||||
operator: "eq",
|
||||
value: '"Example"',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
const invalid = { ...resource, body: "({ query: { where: 1 } })" };
|
||||
const Query = ({
|
||||
state,
|
||||
}: {
|
||||
state: "loaded" | "pending" | "error" | "invalid";
|
||||
}) => {
|
||||
const [source, setSource] = useState<HTMLDivElement | null>(null);
|
||||
return (
|
||||
<div style={{ display: "flex", width: 960, gap: 16 }}>
|
||||
<div style={{ width: 420 }}>
|
||||
<AssetQueryForm
|
||||
resource={state === "invalid" ? invalid : resource}
|
||||
scope={scope}
|
||||
aliases={aliases}
|
||||
sourceContainer={source}
|
||||
fetchDescription={
|
||||
state === "pending" ? pending : state === "error" ? failed : loaded
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div ref={setSource} style={{ flex: 1 }} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export const Loaded = () => <Query state="loaded" />;
|
||||
export const Pending = () => <Query state="pending" />;
|
||||
export const Error = () => <Query state="error" />;
|
||||
export const InvalidSavedQuery = () => <Query state="invalid" />;
|
||||
@@ -0,0 +1,333 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import {
|
||||
createAssetQueryJsonSchema,
|
||||
createAssetResourceOpenApi,
|
||||
} from "@webstudio-is/protocol/asset-resource-api";
|
||||
import {
|
||||
createDefaultStructuredAssetQueryResourceConfiguration,
|
||||
createStructuredAssetQueryResourceBody,
|
||||
type DataSource,
|
||||
type Resource,
|
||||
} from "@webstudio-is/sdk";
|
||||
import {
|
||||
assetsResourceUrl,
|
||||
assetsOpenApiUrl,
|
||||
currentDateResourceUrl,
|
||||
sitemapResourceUrl,
|
||||
} from "@webstudio-is/sdk/runtime";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$planFeatures,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$dataSources,
|
||||
$instances,
|
||||
$pages,
|
||||
$props,
|
||||
$resources,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { RequestFixture } from "~/shared/storybook/request-fixture";
|
||||
import { $variableToOpen } from "./variable-navigation";
|
||||
import { VariablePopoverTrigger } from "./variable-popover";
|
||||
|
||||
registerContainers();
|
||||
|
||||
export default {
|
||||
title: "Settings panel/Variable popover",
|
||||
component: VariablePopoverTrigger,
|
||||
};
|
||||
|
||||
const VariableStory = ({
|
||||
variable,
|
||||
resource,
|
||||
shadowed = false,
|
||||
invalidName = false,
|
||||
}: {
|
||||
variable: DataSource;
|
||||
resource?: Resource;
|
||||
shadowed?: boolean;
|
||||
invalidName?: boolean;
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
dataSources: $dataSources.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
props: $props.get(),
|
||||
resources: $resources.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
variableToOpen: $variableToOpen.get(),
|
||||
planFeatures: $planFeatures.get(),
|
||||
};
|
||||
const ancestor: DataSource = {
|
||||
id: "ancestor-variable",
|
||||
type: "variable",
|
||||
name: variable.name,
|
||||
scopeInstanceId: "body",
|
||||
value: { type: "string", value: "Parent value" },
|
||||
};
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
id: "body",
|
||||
type: "instance",
|
||||
component: "Body",
|
||||
children: [{ type: "id", value: "box" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"box",
|
||||
{ id: "box", type: "instance", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
$pages.set(createDefaultPages({ rootInstanceId: "body" }));
|
||||
$planFeatures.set({ ...previous.planFeatures, allowDynamicData: true });
|
||||
$props.set(new Map());
|
||||
$resources.set(new Map(resource ? [[resource.id, resource]] : []));
|
||||
$dataSources.set(
|
||||
new Map([
|
||||
[variable.id, variable],
|
||||
...(shadowed ? ([[ancestor.id, ancestor]] as const) : []),
|
||||
])
|
||||
);
|
||||
$selectedPageId.set("home");
|
||||
selectInstance(["box", "body"]);
|
||||
setReady(true);
|
||||
|
||||
return () => {
|
||||
$dataSources.set(previous.dataSources);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$props.set(previous.props);
|
||||
$resources.set(previous.resources);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$variableToOpen.set(previous.variableToOpen);
|
||||
$planFeatures.set(previous.planFeatures);
|
||||
};
|
||||
}, [variable, resource, shadowed]);
|
||||
|
||||
useEffect(() => {
|
||||
if (ready) {
|
||||
$variableToOpen.set({ id: variable.id });
|
||||
}
|
||||
}, [ready, variable.id]);
|
||||
|
||||
return (
|
||||
<StorySection title="Variable editor">
|
||||
<Box
|
||||
data-floating-panel-container
|
||||
css={{ width: theme.sizes.sidebarWidth, height: 700 }}
|
||||
>
|
||||
{ready && (
|
||||
<VariablePopoverTrigger
|
||||
variable={variable}
|
||||
onOpenChange={(open) => {
|
||||
if (open && invalidName) {
|
||||
requestAnimationFrame(() => {
|
||||
document
|
||||
.querySelector<HTMLInputElement>(
|
||||
'[data-variable-editor-dialog] input[name="name"]'
|
||||
)
|
||||
?.checkValidity();
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<button type="button">Edit variable</button>
|
||||
</VariablePopoverTrigger>
|
||||
)}
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
const valueStory = (value: DataSource & { type: "variable" }) => () => (
|
||||
<VariableStory variable={value} />
|
||||
);
|
||||
|
||||
export const String = valueStory({
|
||||
id: "story-variable",
|
||||
type: "variable",
|
||||
name: "title",
|
||||
scopeInstanceId: "box",
|
||||
value: { type: "string", value: "Example" },
|
||||
});
|
||||
|
||||
export const Number = valueStory({
|
||||
id: "story-variable",
|
||||
type: "variable",
|
||||
name: "count",
|
||||
scopeInstanceId: "box",
|
||||
value: { type: "number", value: 42 },
|
||||
});
|
||||
|
||||
export const Boolean = valueStory({
|
||||
id: "story-variable",
|
||||
type: "variable",
|
||||
name: "visible",
|
||||
scopeInstanceId: "box",
|
||||
value: { type: "boolean", value: true },
|
||||
});
|
||||
|
||||
export const Json = valueStory({
|
||||
id: "story-variable",
|
||||
type: "variable",
|
||||
name: "items",
|
||||
scopeInstanceId: "box",
|
||||
value: { type: "json", value: { first: "Example", second: 2 } },
|
||||
});
|
||||
|
||||
const resourceStory = (resource: Resource) => {
|
||||
const variable: DataSource = {
|
||||
id: "story-variable",
|
||||
type: "resource",
|
||||
name: resource.name,
|
||||
scopeInstanceId: "box",
|
||||
resourceId: resource.id,
|
||||
};
|
||||
return () => <VariableStory variable={variable} resource={resource} />;
|
||||
};
|
||||
|
||||
export const Http = resourceStory({
|
||||
id: "story-resource",
|
||||
name: "Products",
|
||||
method: "get",
|
||||
url: JSON.stringify("https://example.com/products"),
|
||||
headers: [],
|
||||
});
|
||||
|
||||
export const Graphql = resourceStory({
|
||||
id: "story-resource",
|
||||
name: "Products",
|
||||
control: "graphql",
|
||||
method: "post",
|
||||
url: JSON.stringify("https://example.com/graphql"),
|
||||
headers: [],
|
||||
});
|
||||
|
||||
const assetsResource: Resource = {
|
||||
id: "story-resource",
|
||||
name: "Assets",
|
||||
control: "system",
|
||||
method: "post",
|
||||
url: JSON.stringify(assetsResourceUrl),
|
||||
headers: [],
|
||||
body: createStructuredAssetQueryResourceBody(
|
||||
createDefaultStructuredAssetQueryResourceConfiguration()
|
||||
),
|
||||
};
|
||||
|
||||
const assetsOpenApi = createAssetResourceOpenApi({
|
||||
builderSessionCookieName: "session",
|
||||
querySchemaReference: "/rest/assets/query-schema.json",
|
||||
});
|
||||
const assetsQuerySchema = createAssetQueryJsonSchema({
|
||||
catalog: {
|
||||
format: "webstudio-builder-asset-field-catalog",
|
||||
version: 1,
|
||||
canonicalRevision: `sha256:${"a".repeat(64)}`,
|
||||
documentCount: 0,
|
||||
fields: {},
|
||||
},
|
||||
});
|
||||
const assetsRequest = (request: Request) => {
|
||||
if (request.url.includes("query-schema.json")) {
|
||||
return Response.json(assetsQuerySchema);
|
||||
}
|
||||
if (request.url.includes(assetsOpenApiUrl)) {
|
||||
return Response.json(assetsOpenApi);
|
||||
}
|
||||
};
|
||||
const assetsPending = (request: Request) =>
|
||||
request.url.includes(assetsOpenApiUrl)
|
||||
? new Promise<Response>(() => {})
|
||||
: undefined;
|
||||
const assetsError = (request: Request) =>
|
||||
request.url.includes(assetsOpenApiUrl)
|
||||
? new Response(undefined, { status: 500 })
|
||||
: undefined;
|
||||
const AssetsVariable = resourceStory(assetsResource);
|
||||
export const Assets = () => (
|
||||
<RequestFixture request={assetsRequest}>
|
||||
<AssetsVariable />
|
||||
</RequestFixture>
|
||||
);
|
||||
export const AssetsDescriptionPending = () => (
|
||||
<RequestFixture request={assetsPending}>
|
||||
<AssetsVariable />
|
||||
</RequestFixture>
|
||||
);
|
||||
export const AssetsDescriptionError = () => (
|
||||
<RequestFixture request={assetsError}>
|
||||
<AssetsVariable />
|
||||
</RequestFixture>
|
||||
);
|
||||
|
||||
export const Email = resourceStory({
|
||||
id: "story-resource",
|
||||
name: "Email",
|
||||
control: "email",
|
||||
method: "post",
|
||||
url: '""',
|
||||
headers: [],
|
||||
email: {},
|
||||
});
|
||||
|
||||
export const Sitemap = resourceStory({
|
||||
id: "story-resource",
|
||||
name: "Sitemap",
|
||||
control: "system",
|
||||
method: "get",
|
||||
url: JSON.stringify(sitemapResourceUrl),
|
||||
headers: [],
|
||||
});
|
||||
|
||||
export const CurrentDate = resourceStory({
|
||||
id: "story-resource",
|
||||
name: "Current date",
|
||||
control: "system",
|
||||
method: "get",
|
||||
url: JSON.stringify(currentDateResourceUrl),
|
||||
headers: [],
|
||||
});
|
||||
|
||||
const parameterVariable: DataSource = {
|
||||
id: "story-variable",
|
||||
type: "parameter",
|
||||
name: "query",
|
||||
scopeInstanceId: "box",
|
||||
};
|
||||
const shadowVariable: DataSource = {
|
||||
id: "story-variable",
|
||||
type: "variable",
|
||||
name: "title",
|
||||
scopeInstanceId: "box",
|
||||
value: { type: "string", value: "Child value" },
|
||||
};
|
||||
const invalidVariable: DataSource = {
|
||||
id: "story-variable",
|
||||
type: "variable",
|
||||
name: "",
|
||||
scopeInstanceId: "box",
|
||||
value: { type: "string", value: "Example" },
|
||||
};
|
||||
|
||||
export const Parameter = () => <VariableStory variable={parameterVariable} />;
|
||||
export const ShadowWarning = () => (
|
||||
<VariableStory variable={shadowVariable} shadowed />
|
||||
);
|
||||
export const InvalidName = () => (
|
||||
<VariableStory variable={invalidVariable} invalidName />
|
||||
);
|
||||
+64
-70
@@ -1,15 +1,14 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
StorySection,
|
||||
Text,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$breakpoints,
|
||||
$instances,
|
||||
$pages,
|
||||
$styles,
|
||||
@@ -18,29 +17,9 @@ import {
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { $selectedPageId, selectInstance } from "~/shared/nano-states";
|
||||
import { Section } from "./backdrop-filter";
|
||||
|
||||
registerContainers();
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
["box", { type: "instance", id: "box", component: "Box", children: [] }],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
homePageId: "homePageId",
|
||||
rootInstanceId: "box",
|
||||
})
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
selectInstance(["box"]);
|
||||
|
||||
const blurBackdropFilter: StyleDecl = {
|
||||
breakpointId: "base",
|
||||
@@ -96,56 +75,71 @@ const multipleBackdropFilters: StyleDecl = {
|
||||
},
|
||||
};
|
||||
|
||||
const WithBlurFilterVariant = () => {
|
||||
const BackdropFilterStory = ({ style }: { style?: StyleDecl }) => {
|
||||
useEffect(() => {
|
||||
$styles.set(
|
||||
new Map([[getStyleDeclKey(blurBackdropFilter), blurBackdropFilter]])
|
||||
const previous = {
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpointId: $selectedBreakpointId.get(),
|
||||
styleSources: $styleSources.get(),
|
||||
styleSourceSelections: $styleSourceSelections.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
styles: $styles.get(),
|
||||
};
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
}, []);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const WithMultipleFiltersVariant = () => {
|
||||
useEffect(() => {
|
||||
$styles.set(
|
||||
$instances.set(
|
||||
new Map([
|
||||
[getStyleDeclKey(multipleBackdropFilters), multipleBackdropFilters],
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
}, []);
|
||||
$pages.set(
|
||||
createDefaultPages({ homePageId: "homePageId", rootInstanceId: "box" })
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
$styles.set(
|
||||
style === undefined
|
||||
? new Map()
|
||||
: new Map([[getStyleDeclKey(style), style]])
|
||||
);
|
||||
selectInstance(["box"]);
|
||||
return () => {
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpointId);
|
||||
$styleSources.set(previous.styleSources);
|
||||
$styleSourceSelections.set(previous.styleSourceSelections);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$styles.set(previous.styles);
|
||||
};
|
||||
}, [style]);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
<StorySection title="Backdrop filters">
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const BackdropFilters = () => (
|
||||
<StorySection title="Backdrop filters">
|
||||
<Flex direction="column" gap="5">
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Default</Text>
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With blur filter</Text>
|
||||
<WithBlurFilterVariant />
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With multiple filters</Text>
|
||||
<WithMultipleFiltersVariant />
|
||||
</Flex>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export default {
|
||||
title: "Style panel/Backdrop Filters",
|
||||
title: "Style panel/Backdrop filters",
|
||||
component: Section,
|
||||
};
|
||||
|
||||
export const Empty = () => <BackdropFilterStory />;
|
||||
export const Blur = () => <BackdropFilterStory style={blurBackdropFilter} />;
|
||||
export const Multiple = () => (
|
||||
<BackdropFilterStory style={multipleBackdropFilters} />
|
||||
);
|
||||
+120
-125
@@ -1,16 +1,16 @@
|
||||
import { useEffect } from "react";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
StorySection,
|
||||
Text,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import type { StyleValue } from "@webstudio-is/css-engine";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$breakpoints,
|
||||
$instances,
|
||||
$pages,
|
||||
$styles,
|
||||
@@ -18,133 +18,128 @@ import {
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { BackgroundContent as BackgroundContentPanel } from "./background-content";
|
||||
import { $selectedPageId, selectInstance } from "~/shared/nano-states";
|
||||
import { useComputedStyleDecl } from "../../shared/model";
|
||||
import { setRepeatedStyleItem } from "../../shared/repeated-style";
|
||||
import { type StyleValue } from "@webstudio-is/css-engine";
|
||||
|
||||
registerContainers();
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
["box", { type: "instance", id: "box", component: "Box", children: [] }],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
homePageId: "homePageId",
|
||||
rootInstanceId: "box",
|
||||
})
|
||||
);
|
||||
|
||||
const defaultBackgroundImage: StyleDecl = {
|
||||
breakpointId: "base",
|
||||
styleSourceId: "local",
|
||||
property: "backgroundImage",
|
||||
value: {
|
||||
type: "layers",
|
||||
value: [{ type: "keyword", value: "none" }],
|
||||
},
|
||||
};
|
||||
|
||||
$styles.set(
|
||||
new Map([[getStyleDeclKey(defaultBackgroundImage), defaultBackgroundImage]])
|
||||
);
|
||||
|
||||
$selectedPageId.set("homePageId");
|
||||
selectInstance(["box"]);
|
||||
|
||||
const BackgroundStory = ({ styleValue }: { styleValue: StyleValue }) => {
|
||||
const backgroundImage = useComputedStyleDecl("background-image");
|
||||
type BackgroundLayer = Extract<StyleValue, { type: "layers" }>["value"][number];
|
||||
|
||||
const BackgroundStory = ({ styleValue }: { styleValue: BackgroundLayer }) => {
|
||||
useEffect(() => {
|
||||
setRepeatedStyleItem(backgroundImage, 0, styleValue);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
const previous = {
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpointId: $selectedBreakpointId.get(),
|
||||
styleSourceSelections: $styleSourceSelections.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
styles: $styles.get(),
|
||||
};
|
||||
const backgroundImage: StyleDecl = {
|
||||
breakpointId: "base",
|
||||
styleSourceId: "local",
|
||||
property: "backgroundImage",
|
||||
value: { type: "layers", value: [styleValue] },
|
||||
};
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({ homePageId: "homePageId", rootInstanceId: "box" })
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
$styles.set(new Map([[getStyleDeclKey(backgroundImage), backgroundImage]]));
|
||||
selectInstance(["box"]);
|
||||
return () => {
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpointId);
|
||||
$styleSourceSelections.set(previous.styleSourceSelections);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$styles.set(previous.styles);
|
||||
};
|
||||
}, [styleValue]);
|
||||
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<BackgroundContentPanel index={0} />
|
||||
</Box>
|
||||
<StorySection title="Background content">
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<BackgroundContentPanel index={0} />
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const BackgroundContent = () => (
|
||||
<StorySection title="Background content">
|
||||
<Flex direction="column" gap="5">
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Image (none)</Text>
|
||||
<BackgroundStory styleValue={{ type: "keyword", value: "none" }} />
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Linear gradient</Text>
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"linear-gradient(135deg, rgba(255,126,95,1) 0%, rgba(254,180,123,1) 35%, rgba(134,168,231,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Conic gradient</Text>
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"conic-gradient(from 0deg at 50% 50%, rgba(255,126,95,1) 0deg, rgba(254,180,123,1) 120deg, rgba(134,168,231,1) 240deg, rgba(255,126,95,1) 360deg)",
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Radial gradient</Text>
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"radial-gradient(circle at 50% 50%, rgba(255,126,95,1) 0%, rgba(254,180,123,1) 50%, rgba(134,168,231,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Solid</Text>
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"linear-gradient(0deg, rgba(56,189,248,1) 0%, rgba(56,189,248,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Repeating linear gradient</Text>
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"repeating-linear-gradient(45deg, rgba(255,0,0,1) 0%, rgba(0,0,255,1) 10%, rgba(255,0,0,1) 20%)",
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Multi-stop gradient</Text>
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"linear-gradient(90deg, rgba(255,0,0,1) 0%, rgba(255,165,0,1) 20%, rgba(255,255,0,1) 40%, rgba(0,128,0,1) 60%, rgba(0,0,255,1) 80%, rgba(128,0,128,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export default {
|
||||
title: "Style panel/Backgrounds",
|
||||
component: BackgroundContentPanel,
|
||||
};
|
||||
|
||||
export const None = () => (
|
||||
<BackgroundStory styleValue={{ type: "keyword", value: "none" }} />
|
||||
);
|
||||
export const LinearGradient = () => (
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"linear-gradient(135deg, rgba(255,126,95,1) 0%, rgba(254,180,123,1) 35%, rgba(134,168,231,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
export const ConicGradient = () => (
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"conic-gradient(from 0deg at 50% 50%, rgba(255,126,95,1) 0deg, rgba(254,180,123,1) 120deg, rgba(134,168,231,1) 240deg, rgba(255,126,95,1) 360deg)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
export const RadialGradient = () => (
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"radial-gradient(circle at 50% 50%, rgba(255,126,95,1) 0%, rgba(254,180,123,1) 50%, rgba(134,168,231,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
export const Solid = () => (
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"linear-gradient(0deg, rgba(56,189,248,1) 0%, rgba(56,189,248,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
export const RepeatingLinearGradient = () => (
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"repeating-linear-gradient(45deg, rgba(255,0,0,1) 0%, rgba(0,0,255,1) 10%, rgba(255,0,0,1) 20%)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
export const MultiStopGradient = () => (
|
||||
<BackgroundStory
|
||||
styleValue={{
|
||||
type: "unparsed",
|
||||
value:
|
||||
"linear-gradient(90deg, rgba(255,0,0,1) 0%, rgba(255,165,0,1) 20%, rgba(255,255,0,1) 40%, rgba(0,128,0,1) 60%, rgba(0,0,255,1) 80%, rgba(128,0,128,1) 100%)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
+81
-84
@@ -1,47 +1,25 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
StorySection,
|
||||
Text,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import {
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
$allSelectedInstanceSelectors,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instanceSelectionUpdate } from "~/shared/nano-states/instance-selection";
|
||||
import {
|
||||
$instances,
|
||||
$pages,
|
||||
$styles,
|
||||
$styleSources,
|
||||
$styleSourceSelections,
|
||||
$breakpoints,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { $selectedPageId, selectInstance } from "~/shared/nano-states";
|
||||
import { Section } from "./borders";
|
||||
|
||||
registerContainers();
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
["box", { type: "instance", id: "box", component: "Box", children: [] }],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
homePageId: "homePageId",
|
||||
rootInstanceId: "box",
|
||||
})
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
selectInstance(["box"]);
|
||||
|
||||
const solidBorderTop: StyleDecl = {
|
||||
breakpointId: "base",
|
||||
styleSourceId: "local",
|
||||
@@ -98,64 +76,83 @@ const borderRadius: StyleDecl = {
|
||||
value: { type: "unit", value: 8, unit: "px" },
|
||||
};
|
||||
|
||||
const WithSolidBorderVariant = () => {
|
||||
const StyleStory = ({ declarations }: { declarations: StyleDecl[] }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
$styles.set(
|
||||
const previous = {
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
styles: $styles.get(),
|
||||
sources: $styleSources.get(),
|
||||
selections: $styleSourceSelections.get(),
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpoint: $selectedBreakpointId.get(),
|
||||
selectedPage: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
selectionUpdate: $instanceSelectionUpdate.get(),
|
||||
};
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[getStyleDeclKey(solidBorderTop), solidBorderTop],
|
||||
[getStyleDeclKey(solidBorderRight), solidBorderRight],
|
||||
[getStyleDeclKey(solidBorderBottom), solidBorderBottom],
|
||||
[getStyleDeclKey(solidBorderLeft), solidBorderLeft],
|
||||
[getStyleDeclKey(borderWidthTop), borderWidthTop],
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
}, []);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const WithMixedBordersVariant = () => {
|
||||
useEffect(() => {
|
||||
$styles.set(
|
||||
new Map([
|
||||
[getStyleDeclKey(dashedBorderTop), dashedBorderTop],
|
||||
[getStyleDeclKey(dottedBorderBottom), dottedBorderBottom],
|
||||
[getStyleDeclKey(borderRadius), borderRadius],
|
||||
])
|
||||
$pages.set(
|
||||
createDefaultPages({ homePageId: "homePageId", rootInstanceId: "box" })
|
||||
);
|
||||
}, []);
|
||||
$selectedPageId.set("homePageId");
|
||||
$styles.set(
|
||||
new Map(declarations.map((value) => [getStyleDeclKey(value), value]))
|
||||
);
|
||||
selectInstance(["box"]);
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$styles.set(previous.styles);
|
||||
$styleSources.set(previous.sources);
|
||||
$styleSourceSelections.set(previous.selections);
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpoint);
|
||||
$selectedPageId.set(previous.selectedPage);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$instanceSelectionUpdate.set(previous.selectionUpdate);
|
||||
};
|
||||
}, [declarations]);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export const Borders = () => (
|
||||
<StorySection title="Borders">
|
||||
<Flex direction="column" gap="5">
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Default</Text>
|
||||
<StorySection title="Borders">
|
||||
{ready && (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With solid border</Text>
|
||||
<WithSolidBorderVariant />
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With mixed borders</Text>
|
||||
<WithMixedBordersVariant />
|
||||
</Flex>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export default {
|
||||
title: "Style panel/Borders",
|
||||
component: Section,
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
export default { title: "Style panel/Borders", component: Section };
|
||||
export const Default = () => <StyleStory declarations={[]} />;
|
||||
export const Solid = () => (
|
||||
<StyleStory
|
||||
declarations={[
|
||||
solidBorderTop,
|
||||
solidBorderRight,
|
||||
solidBorderBottom,
|
||||
solidBorderLeft,
|
||||
borderWidthTop,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
export const Mixed = () => (
|
||||
<StyleStory
|
||||
declarations={[dashedBorderTop, dottedBorderBottom, borderRadius]}
|
||||
/>
|
||||
);
|
||||
+66
-82
@@ -1,15 +1,14 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
StorySection,
|
||||
Text,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$breakpoints,
|
||||
$instances,
|
||||
$pages,
|
||||
$styles,
|
||||
@@ -18,29 +17,9 @@ import {
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { $selectedPageId, selectInstance } from "~/shared/nano-states";
|
||||
import { Section } from "./box-shadows";
|
||||
|
||||
registerContainers();
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
["box", { type: "instance", id: "box", component: "Box", children: [] }],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
homePageId: "homePageId",
|
||||
rootInstanceId: "box",
|
||||
})
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
selectInstance(["box"]);
|
||||
|
||||
const outerShadow: StyleDecl = {
|
||||
breakpointId: "base",
|
||||
@@ -128,65 +107,70 @@ const multipleShadows: StyleDecl = {
|
||||
},
|
||||
};
|
||||
|
||||
const WithOuterShadowVariant = () => {
|
||||
const BoxShadowStory = ({ style }: { style?: StyleDecl }) => {
|
||||
useEffect(() => {
|
||||
$styles.set(new Map([[getStyleDeclKey(outerShadow), outerShadow]]));
|
||||
}, []);
|
||||
const previous = {
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpointId: $selectedBreakpointId.get(),
|
||||
styleSources: $styleSources.get(),
|
||||
styleSourceSelections: $styleSourceSelections.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
styles: $styles.get(),
|
||||
};
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({ homePageId: "homePageId", rootInstanceId: "box" })
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
$styles.set(
|
||||
style === undefined
|
||||
? new Map()
|
||||
: new Map([[getStyleDeclKey(style), style]])
|
||||
);
|
||||
selectInstance(["box"]);
|
||||
return () => {
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpointId);
|
||||
$styleSources.set(previous.styleSources);
|
||||
$styleSourceSelections.set(previous.styleSourceSelections);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$styles.set(previous.styles);
|
||||
};
|
||||
}, [style]);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
<StorySection title="Box Shadows">
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
const WithInsetShadowVariant = () => {
|
||||
useEffect(() => {
|
||||
$styles.set(new Map([[getStyleDeclKey(insetShadow), insetShadow]]));
|
||||
}, []);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const WithMultipleShadowsVariant = () => {
|
||||
useEffect(() => {
|
||||
$styles.set(new Map([[getStyleDeclKey(multipleShadows), multipleShadows]]));
|
||||
}, []);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export const BoxShadows = () => (
|
||||
<StorySection title="Box Shadows">
|
||||
<Flex direction="column" gap="5">
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Default</Text>
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With outer shadow</Text>
|
||||
<WithOuterShadowVariant />
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With inset shadow</Text>
|
||||
<WithInsetShadowVariant />
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With multiple shadows</Text>
|
||||
<WithMultipleShadowsVariant />
|
||||
</Flex>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export default {
|
||||
title: "Style panel/Box Shadows",
|
||||
component: Section,
|
||||
};
|
||||
|
||||
export const Empty = () => <BoxShadowStory />;
|
||||
export const Outer = () => <BoxShadowStory style={outerShadow} />;
|
||||
export const Inset = () => <BoxShadowStory style={insetShadow} />;
|
||||
export const Multiple = () => <BoxShadowStory style={multipleShadows} />;
|
||||
@@ -1,15 +1,14 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
StorySection,
|
||||
Text,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$breakpoints,
|
||||
$instances,
|
||||
$pages,
|
||||
$styles,
|
||||
@@ -18,29 +17,9 @@ import {
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { $selectedPageId, selectInstance } from "~/shared/nano-states";
|
||||
import { Section } from "./filter";
|
||||
|
||||
registerContainers();
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
["box", { type: "instance", id: "box", component: "Box", children: [] }],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
homePageId: "homePageId",
|
||||
rootInstanceId: "box",
|
||||
})
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
selectInstance(["box"]);
|
||||
|
||||
const blurFilterStyle: StyleDecl = {
|
||||
breakpointId: "base",
|
||||
@@ -96,50 +75,67 @@ const multipleFilterStyles: StyleDecl = {
|
||||
},
|
||||
};
|
||||
|
||||
const WithBlurFilterVariant = () => {
|
||||
const FilterStory = ({ style }: { style?: StyleDecl }) => {
|
||||
useEffect(() => {
|
||||
$styles.set(new Map([[getStyleDeclKey(blurFilterStyle), blurFilterStyle]]));
|
||||
}, []);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const WithMultipleFiltersVariant = () => {
|
||||
useEffect(() => {
|
||||
$styles.set(
|
||||
new Map([[getStyleDeclKey(multipleFilterStyles), multipleFilterStyles]])
|
||||
const previous = {
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpointId: $selectedBreakpointId.get(),
|
||||
styleSources: $styleSources.get(),
|
||||
styleSourceSelections: $styleSourceSelections.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
styles: $styles.get(),
|
||||
};
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
}, []);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({ homePageId: "homePageId", rootInstanceId: "box" })
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
$styles.set(
|
||||
style === undefined
|
||||
? new Map()
|
||||
: new Map([[getStyleDeclKey(style), style]])
|
||||
);
|
||||
selectInstance(["box"]);
|
||||
return () => {
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpointId);
|
||||
$styleSources.set(previous.styleSources);
|
||||
$styleSourceSelections.set(previous.styleSourceSelections);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$styles.set(previous.styles);
|
||||
};
|
||||
}, [style]);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
<StorySection title="Filters">
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Filters = () => (
|
||||
<StorySection title="Filters">
|
||||
<Flex direction="column" gap="5">
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Default</Text>
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With blur filter</Text>
|
||||
<WithBlurFilterVariant />
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With multiple filters</Text>
|
||||
<WithMultipleFiltersVariant />
|
||||
</Flex>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
export const Empty = () => <FilterStory />;
|
||||
export const Single = () => <FilterStory style={blurFilterStyle} />;
|
||||
export const Multiple = () => <FilterStory style={multipleFilterStyles} />;
|
||||
|
||||
export default {
|
||||
title: "Style panel/Filters",
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, test } from "vitest";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import "@webstudio-is/design-system/global.css";
|
||||
import { Open } from "./grid-generator.stories";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const luminance = (value: string) => {
|
||||
const context = document.createElement("canvas").getContext("2d");
|
||||
if (context === null) {
|
||||
throw new Error("Expected canvas color evaluation");
|
||||
}
|
||||
context.fillStyle = value;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
const [red, green, blue] = context.getImageData(0, 0, 1, 1).data;
|
||||
const linear = (channel: number) => {
|
||||
const scaled = channel / 255;
|
||||
return scaled <= 0.04045
|
||||
? scaled / 12.92
|
||||
: ((scaled + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue);
|
||||
};
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"keeps grid cells and preset diagrams visible in %s mode",
|
||||
(mode) => {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<Open />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
|
||||
const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
|
||||
const cells = dialog?.querySelectorAll<HTMLButtonElement>("button");
|
||||
const preset = Array.from(cells ?? []).find((button) =>
|
||||
button.textContent?.includes("Fluid sidebar")
|
||||
);
|
||||
const preview = preset?.querySelector<HTMLElement>("div");
|
||||
const previewCell = preview?.querySelector<HTMLElement>("div");
|
||||
if (
|
||||
dialog === null ||
|
||||
cells === undefined ||
|
||||
preview === null ||
|
||||
preview === undefined ||
|
||||
previewCell === null ||
|
||||
previewCell === undefined
|
||||
) {
|
||||
throw new Error("Expected the open grid generator and preset preview");
|
||||
}
|
||||
|
||||
const gridPreview = container.querySelector<HTMLButtonElement>("button");
|
||||
const gridLine = gridPreview?.firstElementChild;
|
||||
if (
|
||||
gridPreview === null ||
|
||||
gridPreview === undefined ||
|
||||
gridLine === null ||
|
||||
gridLine === undefined
|
||||
) {
|
||||
throw new Error("Expected the grid preview and a cell line");
|
||||
}
|
||||
expect(getComputedStyle(gridPreview).outlineColor).toBe(
|
||||
getComputedStyle(gridLine).borderRightColor
|
||||
);
|
||||
expect(getComputedStyle(cells[0]).borderColor).not.toBe(
|
||||
getComputedStyle(cells[4]).borderColor
|
||||
);
|
||||
|
||||
for (const [border, background] of [
|
||||
[
|
||||
getComputedStyle(cells[4]).borderColor,
|
||||
getComputedStyle(cells[4]).backgroundColor,
|
||||
],
|
||||
[
|
||||
getComputedStyle(previewCell).borderColor,
|
||||
getComputedStyle(previewCell).backgroundColor,
|
||||
],
|
||||
]) {
|
||||
const surface = luminance(background);
|
||||
const stroke = luminance(border);
|
||||
const ratio =
|
||||
(Math.max(surface, stroke) + 0.05) /
|
||||
(Math.min(surface, stroke) + 0.05);
|
||||
expect(ratio).toBeGreaterThanOrEqual(2.2);
|
||||
expect(ratio).toBeLessThanOrEqual(2.65);
|
||||
}
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
document.documentElement.removeAttribute("data-color-scheme");
|
||||
}
|
||||
}
|
||||
);
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$breakpoints,
|
||||
$instances,
|
||||
$styles,
|
||||
$styleSourceSelections,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { GridGenerator } from "./grid-generator";
|
||||
|
||||
registerContainers();
|
||||
|
||||
export default {
|
||||
title: "Style panel/Grid generator",
|
||||
component: GridGenerator,
|
||||
};
|
||||
|
||||
export const Open = () => {
|
||||
const [open, setOpen] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpointId: $selectedBreakpointId.get(),
|
||||
styles: $styles.get(),
|
||||
styleSourceSelections: $styleSourceSelections.get(),
|
||||
instances: $instances.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
};
|
||||
const tracks: StyleDecl[] = (
|
||||
["gridTemplateColumns", "gridTemplateRows"] as const
|
||||
).map((property) => ({
|
||||
breakpointId: "base",
|
||||
styleSourceId: "local",
|
||||
property,
|
||||
value: { type: "unparsed", value: "1fr 1fr" },
|
||||
}));
|
||||
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styles.set(
|
||||
new Map(tracks.map((track) => [getStyleDeclKey(track), track]))
|
||||
);
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
$selectedPageId.set("");
|
||||
selectInstance(["box"]);
|
||||
|
||||
return () => {
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpointId);
|
||||
$styles.set(previous.styles);
|
||||
$styleSourceSelections.set(previous.styleSourceSelections);
|
||||
$instances.set(previous.instances);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<StorySection title="Grid generator">
|
||||
<Box
|
||||
data-floating-panel-container
|
||||
css={{
|
||||
width: theme.sizes.sidebarWidth,
|
||||
height: 720,
|
||||
marginLeft: 360,
|
||||
marginTop: 100,
|
||||
}}
|
||||
>
|
||||
<GridGenerator open={open} onOpenChange={setOpen} />
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
+9
-7
@@ -61,12 +61,14 @@ const getAxisTrackCount = (
|
||||
return parsedCount;
|
||||
};
|
||||
|
||||
const gridLineColor = `color-mix(in oklab, ${cssVar("--foreground-secondary")} 60%, ${cssVar("--background-floating")})`;
|
||||
|
||||
const selectorCellStyle = css({
|
||||
width: 16,
|
||||
height: 16,
|
||||
borderRadius: theme.borderRadius[3],
|
||||
backgroundColor: cssVar("--background-secondary"),
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
border: `1px solid ${gridLineColor}`,
|
||||
transition: "all 0.1s ease",
|
||||
"&:hover": {
|
||||
borderColor: cssVar("--border-focus"),
|
||||
@@ -227,7 +229,7 @@ const presetPreviewStyle = css({
|
||||
width: "100%",
|
||||
aspectRatio: "3 / 2",
|
||||
borderRadius: theme.borderRadius[2],
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
border: `1px solid ${gridLineColor}`,
|
||||
overflow: "hidden",
|
||||
});
|
||||
|
||||
@@ -268,7 +270,7 @@ const GridPresetsPicker = ({ onSelect }: GridPresetsPickerProps) => {
|
||||
css={{
|
||||
backgroundColor: cssVar("--background-secondary"),
|
||||
borderRadius: theme.borderRadius[1],
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
border: `1px solid ${gridLineColor}`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
@@ -305,11 +307,11 @@ const gridGeneratorButtonStyle = css({
|
||||
display: "grid",
|
||||
width: "100%",
|
||||
height: 60,
|
||||
outline: `1px solid ${cssVar("--border-default")}`,
|
||||
outline: `1px solid ${gridLineColor}`,
|
||||
borderRadius: theme.borderRadius[3],
|
||||
overflow: "hidden",
|
||||
cursor: "pointer",
|
||||
"&:focus-within, &[data-state=open]": {
|
||||
"&:focus-visible": {
|
||||
outline: `1px solid ${cssVar("--border-focus")}`,
|
||||
},
|
||||
"&:hover": {
|
||||
@@ -473,11 +475,11 @@ export const GridGenerator = ({ open, onOpenChange }: GridGeneratorProps) => {
|
||||
height: "100%",
|
||||
borderRight:
|
||||
col < displayColumnCount - 1 && !mergedRight
|
||||
? `1px solid ${cssVar("--border-default")}`
|
||||
? `1px solid ${gridLineColor}`
|
||||
: undefined,
|
||||
borderBottom:
|
||||
row < displayRowCount - 1 && !mergedBottom
|
||||
? `1px solid ${cssVar("--border-default")}`
|
||||
? `1px solid ${gridLineColor}`
|
||||
: undefined,
|
||||
}}
|
||||
/>
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, test } from "vitest";
|
||||
import "@webstudio-is/design-system/global.css";
|
||||
import { Tracks } from "./grid-settings.stories";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"keeps Grid settings sections on the panel surface in %s mode",
|
||||
(mode) => {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() => root.render(<Tracks />));
|
||||
|
||||
const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
|
||||
const section = dialog?.querySelector<HTMLElement>(
|
||||
'[data-floating-panel-container] > [data-state="open"]'
|
||||
);
|
||||
const stickyHeader = section?.querySelector<HTMLElement>(
|
||||
"[data-focus-scope-start] + [data-state]"
|
||||
);
|
||||
if (
|
||||
dialog === null ||
|
||||
section === null ||
|
||||
section === undefined ||
|
||||
stickyHeader === null ||
|
||||
stickyHeader === undefined
|
||||
) {
|
||||
throw new Error("Expected the open Grid settings panel and section");
|
||||
}
|
||||
|
||||
const panelBackground = getComputedStyle(dialog).backgroundColor;
|
||||
expect(getComputedStyle(section).backgroundColor).toBe(panelBackground);
|
||||
expect(getComputedStyle(stickyHeader).backgroundColor).toBe(
|
||||
panelBackground
|
||||
);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
document.documentElement.removeAttribute("data-color-scheme");
|
||||
}
|
||||
}
|
||||
);
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$breakpoints,
|
||||
$instances,
|
||||
$styles,
|
||||
$styleSourceSelections,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { CollapsibleProvider } from "~/builder/shared/collapsible-section";
|
||||
import { GridSettings } from "./grid-settings";
|
||||
|
||||
registerContainers();
|
||||
|
||||
export default { title: "Style panel/Grid settings", component: GridSettings };
|
||||
|
||||
const GridSettingsStory = ({ areas }: { areas: boolean }) => {
|
||||
const [open, setOpen] = useState(true);
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpointId: $selectedBreakpointId.get(),
|
||||
styles: $styles.get(),
|
||||
styleSourceSelections: $styleSourceSelections.get(),
|
||||
instances: $instances.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
};
|
||||
const values: [StyleDecl["property"], string][] = areas
|
||||
? [
|
||||
["gridTemplateColumns", "1fr 1fr"],
|
||||
["gridTemplateRows", "1fr 1fr"],
|
||||
["gridTemplateAreas", '"hero hero" "main sidebar"'],
|
||||
]
|
||||
: [
|
||||
["gridTemplateColumns", "1fr 1fr"],
|
||||
["gridTemplateRows", "1fr 1fr"],
|
||||
];
|
||||
const tracks: StyleDecl[] = values.map(([property, value]) => ({
|
||||
breakpointId: "base",
|
||||
styleSourceId: "local",
|
||||
property,
|
||||
value: { type: "unparsed", value },
|
||||
}));
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styles.set(
|
||||
new Map(tracks.map((track) => [getStyleDeclKey(track), track]))
|
||||
);
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
$selectedPageId.set("");
|
||||
selectInstance(["box"]);
|
||||
return () => {
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpointId);
|
||||
$styles.set(previous.styles);
|
||||
$styleSourceSelections.set(previous.styleSourceSelections);
|
||||
$instances.set(previous.instances);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
};
|
||||
}, [areas]);
|
||||
|
||||
return (
|
||||
<StorySection title="Grid settings">
|
||||
<Box
|
||||
data-floating-panel-container
|
||||
css={{
|
||||
width: theme.sizes.sidebarWidth,
|
||||
height: 720,
|
||||
marginLeft: 360,
|
||||
marginTop: 100,
|
||||
}}
|
||||
>
|
||||
<CollapsibleProvider sectionBackground stickyHeaders>
|
||||
<GridSettings open={open} onOpenChange={setOpen} />
|
||||
</CollapsibleProvider>
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Tracks = () => <GridSettingsStory areas={false} />;
|
||||
export const Areas = () => <GridSettingsStory areas />;
|
||||
+73
-82
@@ -1,47 +1,25 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
StorySection,
|
||||
Text,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import {
|
||||
$selectedBreakpointId,
|
||||
$selectedPageId,
|
||||
$allSelectedInstanceSelectors,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instanceSelectionUpdate } from "~/shared/nano-states/instance-selection";
|
||||
import {
|
||||
$instances,
|
||||
$pages,
|
||||
$styles,
|
||||
$styleSources,
|
||||
$styleSourceSelections,
|
||||
$breakpoints,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { $selectedPageId, selectInstance } from "~/shared/nano-states";
|
||||
import { Section } from "./outline";
|
||||
|
||||
registerContainers();
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
["box", { type: "instance", id: "box", component: "Box", children: [] }],
|
||||
])
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
homePageId: "homePageId",
|
||||
rootInstanceId: "box",
|
||||
})
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
selectInstance(["box"]);
|
||||
|
||||
const solidOutline: StyleDecl = {
|
||||
breakpointId: "base",
|
||||
styleSourceId: "local",
|
||||
@@ -77,62 +55,75 @@ const outlineOffset: StyleDecl = {
|
||||
value: { type: "unit", value: 4, unit: "px" },
|
||||
};
|
||||
|
||||
const WithSolidOutlineVariant = () => {
|
||||
const StyleStory = ({ declarations }: { declarations: StyleDecl[] }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
$styles.set(
|
||||
const previous = {
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
styles: $styles.get(),
|
||||
sources: $styleSources.get(),
|
||||
selections: $styleSourceSelections.get(),
|
||||
breakpoints: $breakpoints.get(),
|
||||
selectedBreakpoint: $selectedBreakpointId.get(),
|
||||
selectedPage: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
selectionUpdate: $instanceSelectionUpdate.get(),
|
||||
};
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[getStyleDeclKey(solidOutline), solidOutline],
|
||||
[getStyleDeclKey(outlineWidth), outlineWidth],
|
||||
[
|
||||
"box",
|
||||
{ type: "instance", id: "box", component: "Box", children: [] },
|
||||
],
|
||||
])
|
||||
);
|
||||
}, []);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const WithDashedOutlineVariant = () => {
|
||||
useEffect(() => {
|
||||
$styles.set(
|
||||
new Map([
|
||||
[getStyleDeclKey(dashedOutline), dashedOutline],
|
||||
[getStyleDeclKey(outlineColor), outlineColor],
|
||||
[getStyleDeclKey(outlineWidth), outlineWidth],
|
||||
[getStyleDeclKey(outlineOffset), outlineOffset],
|
||||
])
|
||||
$pages.set(
|
||||
createDefaultPages({ homePageId: "homePageId", rootInstanceId: "box" })
|
||||
);
|
||||
}, []);
|
||||
$selectedPageId.set("homePageId");
|
||||
$styles.set(
|
||||
new Map(declarations.map((value) => [getStyleDeclKey(value), value]))
|
||||
);
|
||||
selectInstance(["box"]);
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$styles.set(previous.styles);
|
||||
$styleSources.set(previous.sources);
|
||||
$styleSourceSelections.set(previous.selections);
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$selectedBreakpointId.set(previous.selectedBreakpoint);
|
||||
$selectedPageId.set(previous.selectedPage);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$instanceSelectionUpdate.set(previous.selectionUpdate);
|
||||
};
|
||||
}, [declarations]);
|
||||
return (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export const Outline = () => (
|
||||
<StorySection title="Outline">
|
||||
<Flex direction="column" gap="5">
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">Default</Text>
|
||||
<StorySection title="Outline">
|
||||
{ready && (
|
||||
<Box css={{ width: theme.sizes.sidebarWidth }}>
|
||||
<Section />
|
||||
</Box>
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With solid outline</Text>
|
||||
<WithSolidOutlineVariant />
|
||||
</Flex>
|
||||
<Flex direction="column" gap="5">
|
||||
<Text variant="labels">With dashed outline</Text>
|
||||
<WithDashedOutlineVariant />
|
||||
</Flex>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export default {
|
||||
title: "Style panel/Outline",
|
||||
component: Section,
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
export default { title: "Style panel/Outline", component: Section };
|
||||
export const Default = () => <StyleStory declarations={[]} />;
|
||||
export const Solid = () => (
|
||||
<StyleStory declarations={[solidOutline, outlineWidth]} />
|
||||
);
|
||||
export const Dashed = () => (
|
||||
<StyleStory
|
||||
declarations={[dashedOutline, outlineColor, outlineWidth, outlineOffset]}
|
||||
/>
|
||||
);
|
||||
@@ -4,6 +4,7 @@ import { act } from "react-dom/test-utils";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import "@webstudio-is/design-system/global.css";
|
||||
import { InputPopover } from "./input-popover";
|
||||
|
||||
(
|
||||
@@ -50,3 +51,44 @@ test("clearing spacing keeps the input focused instead of exposing canvas shortc
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"spacing popover uses the floating surface in %s mode",
|
||||
async (mode) => {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<InputPopover
|
||||
styleSource="local"
|
||||
property="paddingTop"
|
||||
value={{ type: "unit", value: 20, unit: "px" }}
|
||||
isOpen
|
||||
getActiveProperties={() => ["paddingTop"]}
|
||||
onClose={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(document.querySelector('[role="dialog"]')).not.toBeNull()
|
||||
);
|
||||
const reference = document.createElement("div");
|
||||
reference.style.background = "var(--background-floating-raised)";
|
||||
document.body.append(reference);
|
||||
expect(
|
||||
getComputedStyle(document.querySelector('[role="dialog"]')!)
|
||||
.backgroundColor
|
||||
).toBe(getComputedStyle(reference).backgroundColor);
|
||||
reference.remove();
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
document.documentElement.removeAttribute("data-color-scheme");
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -134,7 +134,6 @@ const PopoverContentStyled = styled(PopoverContent, {
|
||||
minHeight: 0,
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
borderRadius: theme.borderRadius[7],
|
||||
background: cssVar("--background-primary"),
|
||||
padding: theme.spacing[5],
|
||||
boxShadow: theme.shadows.menuDropShadow,
|
||||
animationDuration: "200ms",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { EditorDialog } from "~/shared/code-editor-base";
|
||||
import { CssFragmentEditorContent } from "./css-fragment";
|
||||
|
||||
export default {
|
||||
@@ -29,3 +30,19 @@ export const CSSFragmentEditor = () => (
|
||||
<CssFragmentEditorStory />
|
||||
</div>
|
||||
);
|
||||
|
||||
export const CSSValueDialog = () => (
|
||||
<EditorDialog
|
||||
open
|
||||
title="CSS value"
|
||||
content={
|
||||
<CssFragmentEditorContent
|
||||
value="1fr"
|
||||
showLineNumbers
|
||||
showShortcuts
|
||||
onChange={() => {}}
|
||||
onChangeComplete={() => {}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
);
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useEffect } from "react";
|
||||
import { $pendingTemplateNameConfirmation } from "~/shared/instance-utils/data";
|
||||
import { TemplateNameConfirmationDialog } from "./template-name-confirmation-dialog";
|
||||
|
||||
export default {
|
||||
title: "Builder/Template name confirmation",
|
||||
component: TemplateNameConfirmationDialog,
|
||||
};
|
||||
|
||||
const TemplateNameStory = ({ action }: { action: "rename" | "delete" }) => {
|
||||
useEffect(() => {
|
||||
const previous = $pendingTemplateNameConfirmation.get();
|
||||
$pendingTemplateNameConfirmation.set({
|
||||
operation:
|
||||
action === "rename"
|
||||
? {
|
||||
id: "instances.setLabel",
|
||||
input: { instanceId: "card", label: "Hero Card" },
|
||||
}
|
||||
: { id: "instances.delete", input: { instanceIds: ["card"] } },
|
||||
confirmation: {
|
||||
action,
|
||||
templates: [{ instanceId: "card", oldName: "Card" }],
|
||||
},
|
||||
});
|
||||
return () => $pendingTemplateNameConfirmation.set(previous);
|
||||
}, [action]);
|
||||
return <TemplateNameConfirmationDialog />;
|
||||
};
|
||||
|
||||
export const Rename = () => <TemplateNameStory action="rename" />;
|
||||
export const Delete = () => <TemplateNameStory action="delete" />;
|
||||
@@ -0,0 +1,226 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
|
||||
import { AssetRevisionConflictError } from "@webstudio-is/content-engine/asset-content-repository";
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import { $assets } from "~/shared/sync/data-stores";
|
||||
import { $authPermit } from "~/shared/nano-states";
|
||||
import {
|
||||
createAssetContentBridge,
|
||||
getAssetContentBridge,
|
||||
__testing__ as bridgeTesting,
|
||||
} from "~/shared/asset-content-bridge.client";
|
||||
import { CreateTextFileDialog } from "./create-text-file-dialog";
|
||||
import { TextFileEditor } from "./text-file-editor";
|
||||
|
||||
const asset: Asset = {
|
||||
id: "story-text-file",
|
||||
projectId: "story-project",
|
||||
name: "notes.txt",
|
||||
format: "txt",
|
||||
type: "file",
|
||||
size: 36,
|
||||
meta: {},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Asset Manager/Text file editor",
|
||||
component: TextFileEditor,
|
||||
};
|
||||
|
||||
const markdownAsset: Asset = {
|
||||
...asset,
|
||||
id: "story-markdown-file",
|
||||
name: "article.md",
|
||||
format: "md",
|
||||
};
|
||||
const mdxSource = "# Article\n\nMDX preview content.";
|
||||
const mdxAsset: Asset = {
|
||||
...asset,
|
||||
id: "story-mdx-file",
|
||||
name: "article.mdx",
|
||||
format: "mdx",
|
||||
size: new TextEncoder().encode(mdxSource).byteLength,
|
||||
};
|
||||
|
||||
const EditorStory = ({
|
||||
state,
|
||||
}: {
|
||||
state: "loaded" | "error" | "readOnly" | "markdown" | "markdownReadOnly";
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previousAssets = $assets.get();
|
||||
const previousPermit = $authPermit.get();
|
||||
const previousFetch = window.fetch;
|
||||
const currentAsset = state.startsWith("markdown") ? markdownAsset : asset;
|
||||
$assets.set(new Map([[currentAsset.id, currentAsset]]));
|
||||
$authPermit.set("own");
|
||||
window.fetch = async (input, init) => {
|
||||
if (String(input).includes(`/cgi/asset/${currentAsset.name}`)) {
|
||||
return state === "error"
|
||||
? new Response("", { status: 404 })
|
||||
: new Response(
|
||||
state.startsWith("markdown")
|
||||
? "# Article\n\nA Markdown preview.\n"
|
||||
: "Text file preview\nSecond line\n"
|
||||
);
|
||||
}
|
||||
return previousFetch(input, init);
|
||||
};
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$assets.set(previousAssets);
|
||||
$authPermit.set(previousPermit);
|
||||
window.fetch = previousFetch;
|
||||
};
|
||||
}, [state]);
|
||||
return (
|
||||
<StorySection title="Text file editor">
|
||||
{ready && (
|
||||
<TextFileEditor
|
||||
assetId={state.startsWith("markdown") ? markdownAsset.id : asset.id}
|
||||
readOnly={state === "readOnly" || state === "markdownReadOnly"}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Loaded = () => <EditorStory state="loaded" />;
|
||||
export const ReadOnly = () => <EditorStory state="readOnly" />;
|
||||
export const LoadError = () => <EditorStory state="error" />;
|
||||
export const Markdown = () => <EditorStory state="markdown" />;
|
||||
export const MarkdownReadOnly = () => <EditorStory state="markdownReadOnly" />;
|
||||
|
||||
const MdxStory = ({
|
||||
state,
|
||||
}: {
|
||||
state: "loaded" | "readOnly" | "failed" | "conflicting";
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
const previousAssets = $assets.get();
|
||||
const previousPermit = $authPermit.get();
|
||||
let previousBridge: ReturnType<typeof getAssetContentBridge> | undefined;
|
||||
try {
|
||||
previousBridge = getAssetContentBridge();
|
||||
} catch {
|
||||
// Storybook has no Asset content bridge until this fixture installs one.
|
||||
}
|
||||
const session = createAssetContentSession({
|
||||
repository: {
|
||||
readContent: async () => ({
|
||||
asset: mdxAsset,
|
||||
data: (async function* () {
|
||||
yield new TextEncoder().encode(mdxSource);
|
||||
})(),
|
||||
}),
|
||||
updateContent: async () => {
|
||||
if (state === "conflicting") {
|
||||
throw new AssetRevisionConflictError(
|
||||
"This file changed elsewhere. Reload before continuing."
|
||||
);
|
||||
}
|
||||
if (state === "failed") {
|
||||
throw new Error("Unable to save this file.");
|
||||
}
|
||||
return mdxAsset;
|
||||
},
|
||||
},
|
||||
authorize: () => true,
|
||||
debounceMilliseconds: 60_000,
|
||||
});
|
||||
bridgeTesting.initBridge(
|
||||
createAssetContentBridge({
|
||||
origin: window.location.origin,
|
||||
request: fetch,
|
||||
authorize: () => true,
|
||||
requireReload: () => {},
|
||||
getContentSession: () => session,
|
||||
})
|
||||
);
|
||||
$assets.set(new Map([[mdxAsset.id, mdxAsset]]));
|
||||
$authPermit.set("own");
|
||||
const prepare = async () => {
|
||||
await session.open(mdxAsset.id);
|
||||
if (state === "failed" || state === "conflicting") {
|
||||
session.save(mdxAsset.id, "# Updated article");
|
||||
await session.flush(mdxAsset.id).catch(() => {});
|
||||
}
|
||||
if (!disposed) {
|
||||
setReady(true);
|
||||
}
|
||||
};
|
||||
void prepare();
|
||||
return () => {
|
||||
disposed = true;
|
||||
session.dispose();
|
||||
$assets.set(previousAssets);
|
||||
$authPermit.set(previousPermit);
|
||||
if (previousBridge) {
|
||||
bridgeTesting.initBridge(previousBridge);
|
||||
} else {
|
||||
bridgeTesting.clearBridge();
|
||||
}
|
||||
};
|
||||
}, [state]);
|
||||
return (
|
||||
<StorySection title="MDX content editor">
|
||||
{ready && (
|
||||
<TextFileEditor
|
||||
assetId={mdxAsset.id}
|
||||
readOnly={state === "readOnly"}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Mdx = () => <MdxStory state="loaded" />;
|
||||
export const MdxReadOnly = () => <MdxStory state="readOnly" />;
|
||||
export const MdxSaveError = () => <MdxStory state="failed" />;
|
||||
export const MdxConflict = () => <MdxStory state="conflicting" />;
|
||||
|
||||
const CreateStory = ({
|
||||
state,
|
||||
}: {
|
||||
state: "default" | "invalid" | "disabled";
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
if (state !== "invalid") {
|
||||
return;
|
||||
}
|
||||
const showError = () => {
|
||||
const button = Array.from(document.querySelectorAll("button")).find(
|
||||
(item) => item.textContent === "Create file"
|
||||
);
|
||||
if (button) {
|
||||
observer.disconnect();
|
||||
button.click();
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(showError);
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
showError();
|
||||
return () => observer.disconnect();
|
||||
}, [state]);
|
||||
return (
|
||||
<CreateTextFileDialog
|
||||
open
|
||||
defaultName={state === "invalid" ? "image.png" : "untitled.md"}
|
||||
disabled={state === "disabled"}
|
||||
onOpenChange={() => {}}
|
||||
onCreated={() => {}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export const Create = () => <CreateStory state="default" />;
|
||||
export const CreateInvalidExtension = () => <CreateStory state="invalid" />;
|
||||
export const CreateDisabled = () => <CreateStory state="disabled" />;
|
||||
@@ -0,0 +1,246 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, StorySection } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { coreMetas, type Instance } from "@webstudio-is/sdk";
|
||||
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
|
||||
import { $collaborators } from "@webstudio-is/sync-client";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$builderMode,
|
||||
$canvasToolsVisible,
|
||||
$collaborativeInstanceRect,
|
||||
$collaborativeInstanceSelector,
|
||||
$dragAndDropState,
|
||||
$hoveredInstanceOutline,
|
||||
$hoveredInstanceSelector,
|
||||
$instanceContextMenu,
|
||||
$registeredComponentMetas,
|
||||
$selectedInstanceOutlines,
|
||||
$selectedPageId,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instanceSelectionUpdate } from "~/shared/nano-states/instance-selection";
|
||||
import { $instances, $pages, $props } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$canvasRect,
|
||||
$canvasScrollbarSize,
|
||||
$canvasWidth,
|
||||
$isStylePanelGridVisible,
|
||||
$workspaceRect,
|
||||
} from "~/builder/shared/nano-states";
|
||||
import { $ephemeralStyles } from "~/canvas/stores";
|
||||
import { CanvasTools } from "./canvas-tools";
|
||||
|
||||
type State =
|
||||
| "selected"
|
||||
| "slot"
|
||||
| "hovered"
|
||||
| "collaborator"
|
||||
| "dragging"
|
||||
| "menu";
|
||||
|
||||
export default {
|
||||
title: "Canvas tools/Composed overlays",
|
||||
component: CanvasTools,
|
||||
};
|
||||
|
||||
const boxRect = new DOMRect(200, 130, 300, 200);
|
||||
const selector = ["box", "body"];
|
||||
|
||||
const CanvasStory = ({
|
||||
state,
|
||||
surface,
|
||||
}: {
|
||||
state: State;
|
||||
surface: "bright" | "dark";
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
builderMode: $builderMode.get(),
|
||||
visible: $canvasToolsVisible.get(),
|
||||
canvasWidth: $canvasWidth.get(),
|
||||
workspaceRect: $workspaceRect.get(),
|
||||
canvasRect: $canvasRect.get(),
|
||||
scrollbar: $canvasScrollbarSize.get(),
|
||||
gridVisible: $isStylePanelGridVisible.get(),
|
||||
ephemeralStyles: $ephemeralStyles.get(),
|
||||
selected: $selectedInstanceOutlines.get(),
|
||||
hovered: $hoveredInstanceOutline.get(),
|
||||
hoveredSelector: $hoveredInstanceSelector.get(),
|
||||
collaboratorRect: $collaborativeInstanceRect.get(),
|
||||
collaboratorSelector: $collaborativeInstanceSelector.get(),
|
||||
collaborators: $collaborators.get(),
|
||||
drag: $dragAndDropState.get(),
|
||||
contextMenu: $instanceContextMenu.get(),
|
||||
allSelected: $allSelectedInstanceSelectors.get(),
|
||||
selectionUpdate: $instanceSelectionUpdate.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
props: $props.get(),
|
||||
metas: $registeredComponentMetas.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
};
|
||||
const instances: Instance[] = [
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: [{ type: "id", value: state === "slot" ? "slot" : "box" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "slot",
|
||||
component: "Slot",
|
||||
children: [{ type: "id", value: "box" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "box",
|
||||
component: "Box",
|
||||
label: "Card",
|
||||
children: [],
|
||||
},
|
||||
];
|
||||
const currentSelector =
|
||||
state === "slot" ? ["box", "slot", "body"] : selector;
|
||||
$builderMode.set("design");
|
||||
$canvasToolsVisible.set(true);
|
||||
$canvasWidth.set(900);
|
||||
$workspaceRect.set(new DOMRect(0, 0, 900, 600));
|
||||
$canvasRect.set(new DOMRect(0, 0, 900, 600));
|
||||
$canvasScrollbarSize.set({ width: 0, height: 0 });
|
||||
$isStylePanelGridVisible.set(false);
|
||||
$ephemeralStyles.set([]);
|
||||
$instances.set(
|
||||
new Map(instances.map((instance) => [instance.id, instance]))
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
|
||||
);
|
||||
$props.set(new Map());
|
||||
$registeredComponentMetas.set(
|
||||
new Map(Object.entries({ ...coreMetas, ...baseComponentMetas }))
|
||||
);
|
||||
$selectedPageId.set("home");
|
||||
$selectedInstanceOutlines.set(
|
||||
state === "selected" || state === "slot"
|
||||
? [{ instanceId: "box", selector: currentSelector, rect: boxRect }]
|
||||
: []
|
||||
);
|
||||
$hoveredInstanceOutline.set(
|
||||
state === "hovered" ? { instanceId: "box", rect: boxRect } : undefined
|
||||
);
|
||||
$hoveredInstanceSelector.set(
|
||||
state === "hovered" ? currentSelector : undefined
|
||||
);
|
||||
$collaborativeInstanceRect.set(
|
||||
state === "collaborator" ? boxRect : undefined
|
||||
);
|
||||
$collaborativeInstanceSelector.set(
|
||||
state === "collaborator" ? currentSelector : undefined
|
||||
);
|
||||
const collaborators = new Map($collaborators.get());
|
||||
collaborators.clear();
|
||||
if (state === "collaborator") {
|
||||
collaborators.set("alex", {
|
||||
name: "Alex",
|
||||
pageId: "home",
|
||||
selectedInstanceIds: currentSelector,
|
||||
pointerPosition: { x: 0, y: 0, xRatio: 0.52, yRatio: 0.42 },
|
||||
});
|
||||
}
|
||||
$collaborators.set(collaborators);
|
||||
$dragAndDropState.set(
|
||||
state === "dragging"
|
||||
? {
|
||||
isDragging: true,
|
||||
dropTarget: {
|
||||
itemSelector: ["body"],
|
||||
indexWithinChildren: 0,
|
||||
placement: {
|
||||
closestChildIndex: 0,
|
||||
indexAdjustment: 0,
|
||||
childrenOrientation: { type: "vertical", reverse: false },
|
||||
},
|
||||
},
|
||||
placementIndicator: {
|
||||
parentRect: { left: 100, top: 100, width: 500, height: 400 },
|
||||
type: "between-children",
|
||||
x: 200,
|
||||
y: 350,
|
||||
length: 300,
|
||||
direction: "horizontal",
|
||||
},
|
||||
}
|
||||
: { isDragging: false }
|
||||
);
|
||||
$instanceContextMenu.set(
|
||||
state === "menu"
|
||||
? { position: { x: 300, y: 230 }, instanceSelector: currentSelector }
|
||||
: undefined
|
||||
);
|
||||
setReady(true);
|
||||
return () => {
|
||||
$builderMode.set(previous.builderMode);
|
||||
$canvasToolsVisible.set(previous.visible);
|
||||
$canvasWidth.set(previous.canvasWidth);
|
||||
$workspaceRect.set(previous.workspaceRect);
|
||||
$canvasRect.set(previous.canvasRect);
|
||||
$canvasScrollbarSize.set(previous.scrollbar);
|
||||
$isStylePanelGridVisible.set(previous.gridVisible);
|
||||
$ephemeralStyles.set(previous.ephemeralStyles);
|
||||
$selectedInstanceOutlines.set(previous.selected);
|
||||
$hoveredInstanceOutline.set(previous.hovered);
|
||||
$hoveredInstanceSelector.set(previous.hoveredSelector);
|
||||
$collaborativeInstanceRect.set(previous.collaboratorRect);
|
||||
$collaborativeInstanceSelector.set(previous.collaboratorSelector);
|
||||
$collaborators.set(previous.collaborators);
|
||||
$dragAndDropState.set(previous.drag);
|
||||
$instanceContextMenu.set(previous.contextMenu);
|
||||
$instances.set(previous.instances);
|
||||
$allSelectedInstanceSelectors.set(previous.allSelected);
|
||||
$instanceSelectionUpdate.set(previous.selectionUpdate);
|
||||
$pages.set(previous.pages);
|
||||
$props.set(previous.props);
|
||||
$registeredComponentMetas.set(previous.metas);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
return (
|
||||
<StorySection title="Canvas tools">
|
||||
<Box
|
||||
css={{
|
||||
position: "relative",
|
||||
width: 900,
|
||||
height: 600,
|
||||
backgroundColor: surface === "bright" ? "#fff" : "#151515",
|
||||
}}
|
||||
>
|
||||
{ready && <CanvasTools />}
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const SelectedBright = () => (
|
||||
<CanvasStory state="selected" surface="bright" />
|
||||
);
|
||||
export const SelectedDark = () => (
|
||||
<CanvasStory state="selected" surface="dark" />
|
||||
);
|
||||
export const SelectedSlot = () => <CanvasStory state="slot" surface="bright" />;
|
||||
export const HoveredBright = () => (
|
||||
<CanvasStory state="hovered" surface="bright" />
|
||||
);
|
||||
export const HoveredDark = () => <CanvasStory state="hovered" surface="dark" />;
|
||||
export const CollaboratorBright = () => (
|
||||
<CanvasStory state="collaborator" surface="bright" />
|
||||
);
|
||||
export const CollaboratorDark = () => (
|
||||
<CanvasStory state="collaborator" surface="dark" />
|
||||
);
|
||||
export const Dragging = () => <CanvasStory state="dragging" surface="bright" />;
|
||||
export const InstanceContextMenu = () => (
|
||||
<CanvasStory state="menu" surface="bright" />
|
||||
);
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box } from "@webstudio-is/design-system";
|
||||
import { $collaborators } from "@webstudio-is/sync-client";
|
||||
import {
|
||||
$collaborativeInstanceSelector,
|
||||
$selectedPageId,
|
||||
} from "~/shared/nano-states";
|
||||
import { $canvasRect } from "~/builder/shared/nano-states";
|
||||
import { CollaborativeCursors } from "./collaborative-cursors";
|
||||
|
||||
export default {
|
||||
title: "Canvas tools/Collaborative cursors",
|
||||
component: CollaborativeCursors,
|
||||
};
|
||||
|
||||
const PaletteStory = ({ surface }: { surface: "bright" | "dark" }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
collaborators: $collaborators.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
collaborativeSelector: $collaborativeInstanceSelector.get(),
|
||||
canvasRect: $canvasRect.get(),
|
||||
};
|
||||
const collaborators = new Map($collaborators.get());
|
||||
collaborators.clear();
|
||||
for (let index = 0; index < 50; index += 1) {
|
||||
const xRatio = ((index % 10) + 1) / 12;
|
||||
const yRatio = (Math.floor(index / 10) + 1) / 6;
|
||||
collaborators.set(`client-${index}`, {
|
||||
name: `Editor ${index + 1}`,
|
||||
pageId: "home",
|
||||
pointerPosition: { x: 0, y: 0, xRatio, yRatio },
|
||||
});
|
||||
}
|
||||
$selectedPageId.set("home");
|
||||
$canvasRect.set(undefined);
|
||||
$collaborators.set(collaborators);
|
||||
setReady(true);
|
||||
return () => {
|
||||
$collaborators.set(previous.collaborators);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$collaborativeInstanceSelector.set(previous.collaborativeSelector);
|
||||
$canvasRect.set(previous.canvasRect);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box
|
||||
css={{
|
||||
position: "fixed",
|
||||
inset: 0,
|
||||
backgroundColor: surface === "bright" ? "#fff" : "#151515",
|
||||
}}
|
||||
/>
|
||||
{ready && <CollaborativeCursors />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const BrightPalette = () => <PaletteStory surface="bright" />;
|
||||
export const DarkPalette = () => <PaletteStory surface="dark" />;
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
StorySection,
|
||||
TooltipProvider,
|
||||
cssVar,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { MediaBadge } from "./media-badge";
|
||||
import { Toolbar } from "./text-toolbar";
|
||||
|
||||
export default {
|
||||
title: "Canvas tools/Floating surfaces",
|
||||
};
|
||||
|
||||
export const TextToolbar = () => (
|
||||
<StorySection title="Text toolbar">
|
||||
<div
|
||||
style={{
|
||||
position: "relative",
|
||||
width: 500,
|
||||
height: 180,
|
||||
background: cssVar("--background-primary"),
|
||||
}}
|
||||
>
|
||||
<TooltipProvider>
|
||||
<Toolbar
|
||||
scale={100}
|
||||
state={{
|
||||
selectionRect: new DOMRect(150, 100, 80, 20),
|
||||
isBold: false,
|
||||
isItalic: false,
|
||||
isSuperscript: false,
|
||||
isSubscript: false,
|
||||
isLink: false,
|
||||
isSpan: false,
|
||||
}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export const TextToolbarFormatted = () => (
|
||||
<StorySection title="Formatted text toolbar">
|
||||
<div
|
||||
style={{
|
||||
position: "relative",
|
||||
width: 500,
|
||||
height: 180,
|
||||
background: cssVar("--background-primary"),
|
||||
}}
|
||||
>
|
||||
<TooltipProvider>
|
||||
<Toolbar
|
||||
scale={100}
|
||||
state={{
|
||||
selectionRect: new DOMRect(150, 100, 80, 20),
|
||||
isBold: true,
|
||||
isItalic: true,
|
||||
isSuperscript: true,
|
||||
isSubscript: false,
|
||||
isLink: true,
|
||||
isSpan: true,
|
||||
}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export const WorkspaceMediaBadge = () => {
|
||||
useEffect(() => {
|
||||
const previousBreakpoints = $breakpoints.get();
|
||||
const previousSelectedId = $selectedBreakpointId.get();
|
||||
$breakpoints.set(
|
||||
new Map([["tablet", { id: "tablet", label: "Tablet", maxWidth: 991 }]])
|
||||
);
|
||||
$selectedBreakpointId.set("tablet");
|
||||
return () => {
|
||||
$breakpoints.set(previousBreakpoints);
|
||||
$selectedBreakpointId.set(previousSelectedId);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<StorySection title="Workspace media badge">
|
||||
<div
|
||||
style={{
|
||||
width: 500,
|
||||
height: 260,
|
||||
background: `light-dark(
|
||||
color-mix(in oklab, ${cssVar("--background-secondary")} 94%, ${cssVar("--foreground-primary")}),
|
||||
color-mix(in oklab, ${cssVar("--background-primary")} 96%, ${cssVar("--foreground-primary")})
|
||||
)`,
|
||||
}}
|
||||
>
|
||||
<div style={{ position: "relative", marginLeft: 120, height: 180 }}>
|
||||
<MediaBadge />
|
||||
</div>
|
||||
</div>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useEffect } from "react";
|
||||
import { Box, StorySection } from "@webstudio-is/design-system";
|
||||
import { $gridCellData } from "~/shared/nano-states";
|
||||
import {
|
||||
$canvasWidth,
|
||||
$gridEditingArea,
|
||||
$gridEditingTrack,
|
||||
$workspaceRect,
|
||||
} from "~/builder/shared/nano-states";
|
||||
import { $ephemeralStyles } from "~/canvas/stores";
|
||||
import { GridGuides } from "./grid-guides";
|
||||
|
||||
export default { title: "Canvas tools/Grid guides", component: GridGuides };
|
||||
|
||||
const GridStory = ({
|
||||
surface,
|
||||
state,
|
||||
}: {
|
||||
surface: "bright" | "dark";
|
||||
state: "plain" | "areas" | "track" | "area";
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
gridCellData: $gridCellData.get(),
|
||||
canvasWidth: $canvasWidth.get(),
|
||||
workspaceRect: $workspaceRect.get(),
|
||||
editingArea: $gridEditingArea.get(),
|
||||
editingTrack: $gridEditingTrack.get(),
|
||||
ephemeralStyles: $ephemeralStyles.get(),
|
||||
};
|
||||
$canvasWidth.set(800);
|
||||
$workspaceRect.set(new DOMRect(0, 0, 800, 500));
|
||||
$ephemeralStyles.set([]);
|
||||
$gridCellData.set({
|
||||
instanceId: "grid",
|
||||
bcr: { left: 100, top: 80 },
|
||||
untransformedWidth: 540,
|
||||
untransformedHeight: 300,
|
||||
columnCount: 3,
|
||||
rowCount: 2,
|
||||
implicitColumnStart: 3,
|
||||
implicitRowStart: 2,
|
||||
resolvedCssText: [
|
||||
"display: grid",
|
||||
"width: 540px",
|
||||
"height: 300px",
|
||||
"grid-template-columns: repeat(3, 1fr)",
|
||||
"grid-template-rows: repeat(2, 1fr)",
|
||||
`grid-template-areas: ${state === "plain" ? "none" : '"hero hero menu" "main main menu"'}`,
|
||||
].join("; "),
|
||||
});
|
||||
$gridEditingTrack.set(
|
||||
state === "track" ? { type: "column", index: 1 } : undefined
|
||||
);
|
||||
$gridEditingArea.set(
|
||||
state === "area"
|
||||
? { columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 }
|
||||
: undefined
|
||||
);
|
||||
return () => {
|
||||
$gridCellData.set(previous.gridCellData);
|
||||
$canvasWidth.set(previous.canvasWidth);
|
||||
$workspaceRect.set(previous.workspaceRect);
|
||||
$gridEditingArea.set(previous.editingArea);
|
||||
$gridEditingTrack.set(previous.editingTrack);
|
||||
$ephemeralStyles.set(previous.ephemeralStyles);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
return (
|
||||
<StorySection title="Grid guides">
|
||||
<Box
|
||||
css={{
|
||||
position: "relative",
|
||||
width: 800,
|
||||
height: 500,
|
||||
backgroundColor: surface === "bright" ? "#fff" : "#151515",
|
||||
}}
|
||||
>
|
||||
<GridGuides />
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const BrightCells = () => <GridStory surface="bright" state="plain" />;
|
||||
export const DarkCells = () => <GridStory surface="dark" state="plain" />;
|
||||
export const BrightAreas = () => <GridStory surface="bright" state="areas" />;
|
||||
export const DarkAreas = () => <GridStory surface="dark" state="areas" />;
|
||||
export const TrackHighlight = () => <GridStory surface="dark" state="track" />;
|
||||
export const AreaHighlight = () => <GridStory surface="bright" state="area" />;
|
||||
@@ -10,7 +10,7 @@ const labelStyle = css({
|
||||
});
|
||||
|
||||
const badgeStyle = css({
|
||||
background: cssVar("--background-primary"),
|
||||
background: `color-mix(in oklab, ${cssVar("--background-secondary")} 85%, ${cssVar("--foreground-primary")})`,
|
||||
color: cssVar("--foreground-primary"),
|
||||
px: theme.spacing[3],
|
||||
py: theme.spacing[2],
|
||||
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, StorySection } from "@webstudio-is/design-system";
|
||||
import {
|
||||
blockBodyComponent,
|
||||
blockComponent,
|
||||
blockTemplateComponent,
|
||||
coreMetas,
|
||||
elementComponent,
|
||||
type Instance,
|
||||
} from "@webstudio-is/sdk";
|
||||
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$blockChildOutline,
|
||||
$builderMode,
|
||||
$modifierKeys,
|
||||
$registeredComponentMetas,
|
||||
$textEditingInstanceSelector,
|
||||
$textEditorContextMenu,
|
||||
execTextEditorContextMenuCommand,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instanceSelectionUpdate } from "~/shared/nano-states/instance-selection";
|
||||
import { $instances, $props } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$canvasRect,
|
||||
$canvasScrollbarSize,
|
||||
$canvasWidth,
|
||||
$workspaceRect,
|
||||
} from "~/builder/shared/nano-states";
|
||||
import {
|
||||
BlockChildHoveredInstanceOutline,
|
||||
TemplatesMenu,
|
||||
} from "./block-instance-outline";
|
||||
import { TextEditorContextMenu } from "../block-editor-context-menu";
|
||||
|
||||
export default {
|
||||
title: "Canvas tools/Content block outline",
|
||||
component: BlockChildHoveredInstanceOutline,
|
||||
};
|
||||
|
||||
const BlockStory = ({
|
||||
state,
|
||||
}: {
|
||||
state: "add" | "delete" | "menu" | "slash" | "slashEmpty";
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
blockChildOutline: $blockChildOutline.get(),
|
||||
builderMode: $builderMode.get(),
|
||||
modifierKeys: $modifierKeys.get(),
|
||||
metas: $registeredComponentMetas.get(),
|
||||
instances: $instances.get(),
|
||||
props: $props.get(),
|
||||
allSelected: $allSelectedInstanceSelectors.get(),
|
||||
selectionUpdate: $instanceSelectionUpdate.get(),
|
||||
textEditing: $textEditingInstanceSelector.get(),
|
||||
textMenu: $textEditorContextMenu.get(),
|
||||
canvasWidth: $canvasWidth.get(),
|
||||
workspaceRect: $workspaceRect.get(),
|
||||
canvasRect: $canvasRect.get(),
|
||||
scrollbar: $canvasScrollbarSize.get(),
|
||||
};
|
||||
const instances: Instance[] = [
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: [{ type: "id", value: "block" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "block",
|
||||
component: blockComponent,
|
||||
children: [
|
||||
{ type: "id", value: "templates" },
|
||||
{ type: "id", value: "content" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "templates",
|
||||
component: blockTemplateComponent,
|
||||
children: [
|
||||
{ type: "id", value: "heading" },
|
||||
{ type: "id", value: "paragraph" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "heading",
|
||||
component: elementComponent,
|
||||
tag: "h2",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "paragraph",
|
||||
component: elementComponent,
|
||||
tag: "p",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "content",
|
||||
component: blockBodyComponent,
|
||||
children: [{ type: "id", value: "current" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "current",
|
||||
component: elementComponent,
|
||||
tag: "p",
|
||||
children: [{ type: "text", value: "Article text" }],
|
||||
},
|
||||
];
|
||||
$instances.set(
|
||||
new Map(instances.map((instance) => [instance.id, instance]))
|
||||
);
|
||||
$props.set(new Map());
|
||||
$registeredComponentMetas.set(
|
||||
new Map(Object.entries({ ...coreMetas, ...baseComponentMetas }))
|
||||
);
|
||||
$builderMode.set("content");
|
||||
$modifierKeys.set({ altKey: state === "delete" });
|
||||
$canvasWidth.set(800);
|
||||
$workspaceRect.set(new DOMRect(0, 0, 800, 500));
|
||||
$canvasRect.set(new DOMRect(0, 0, 800, 500));
|
||||
$canvasScrollbarSize.set({ width: 0, height: 0 });
|
||||
$blockChildOutline.set({
|
||||
selector: ["current", "content", "block", "body"],
|
||||
hoveredSelector: ["current", "content", "block", "body"],
|
||||
rect: new DOMRect(220, 170, 260, 170),
|
||||
});
|
||||
if (state === "slash" || state === "slashEmpty") {
|
||||
$textEditingInstanceSelector.set({
|
||||
selector: ["current", "content", "block", "body"],
|
||||
reason: "left",
|
||||
});
|
||||
$textEditorContextMenu.set({
|
||||
cursorRect: new DOMRect(300, 240, 2, 20),
|
||||
replaceAnchor: false,
|
||||
});
|
||||
}
|
||||
setReady(true);
|
||||
const filterTimer =
|
||||
state === "slashEmpty"
|
||||
? window.setTimeout(() => {
|
||||
execTextEditorContextMenuCommand({
|
||||
type: "filter",
|
||||
value: "no matching template",
|
||||
});
|
||||
}, 250)
|
||||
: undefined;
|
||||
return () => {
|
||||
if (filterTimer !== undefined) {
|
||||
window.clearTimeout(filterTimer);
|
||||
}
|
||||
$blockChildOutline.set(previous.blockChildOutline);
|
||||
$builderMode.set(previous.builderMode);
|
||||
$modifierKeys.set(previous.modifierKeys);
|
||||
$registeredComponentMetas.set(previous.metas);
|
||||
$instances.set(previous.instances);
|
||||
$allSelectedInstanceSelectors.set(previous.allSelected);
|
||||
$instanceSelectionUpdate.set(previous.selectionUpdate);
|
||||
$textEditingInstanceSelector.set(previous.textEditing);
|
||||
$textEditorContextMenu.set(previous.textMenu);
|
||||
$props.set(previous.props);
|
||||
$canvasWidth.set(previous.canvasWidth);
|
||||
$workspaceRect.set(previous.workspaceRect);
|
||||
$canvasRect.set(previous.canvasRect);
|
||||
$canvasScrollbarSize.set(previous.scrollbar);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
return (
|
||||
<StorySection title="Content block outline">
|
||||
<Box
|
||||
css={{
|
||||
position: "relative",
|
||||
width: 800,
|
||||
height: 500,
|
||||
backgroundColor: "#fff",
|
||||
}}
|
||||
>
|
||||
{ready &&
|
||||
(state === "slash" || state === "slashEmpty" ? (
|
||||
<TextEditorContextMenu />
|
||||
) : state === "menu" ? (
|
||||
<TemplatesMenu
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
anchor={["current", "content", "block", "body"]}
|
||||
triggerTooltipContent={<>Insert block</>}
|
||||
templates={[
|
||||
[
|
||||
$instances.get().get("heading")!,
|
||||
["heading", "templates", "block", "body"],
|
||||
],
|
||||
[
|
||||
$instances.get().get("paragraph")!,
|
||||
["paragraph", "templates", "block", "body"],
|
||||
],
|
||||
]}
|
||||
value={undefined}
|
||||
onValueChangeComplete={() => {}}
|
||||
modal
|
||||
inert={false}
|
||||
preventFocusOnHover={false}
|
||||
>
|
||||
<button type="button">Insert block</button>
|
||||
</TemplatesMenu>
|
||||
) : (
|
||||
<BlockChildHoveredInstanceOutline />
|
||||
))}
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Insert = () => <BlockStory state="add" />;
|
||||
export const Delete = () => <BlockStory state="delete" />;
|
||||
export const TemplatesMenuOpen = () => <BlockStory state="menu" />;
|
||||
export const SlashMenu = () => <BlockStory state="slash" />;
|
||||
export const SlashMenuNoResults = () => <BlockStory state="slashEmpty" />;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect } from "react";
|
||||
import { Box, StorySection } from "@webstudio-is/design-system";
|
||||
import { $isResizingCanvas, $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { $canvasWidth, $workspaceRect } from "~/builder/shared/nano-states";
|
||||
import { ResizeHandles } from "./resize-handles";
|
||||
|
||||
export default {
|
||||
title: "Canvas tools/Resize handles",
|
||||
component: ResizeHandles,
|
||||
};
|
||||
|
||||
const ResizeStory = ({
|
||||
surface,
|
||||
resizing,
|
||||
}: {
|
||||
surface: "bright" | "dark";
|
||||
resizing: boolean;
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
resizing: $isResizingCanvas.get(),
|
||||
breakpointId: $selectedBreakpointId.get(),
|
||||
breakpoints: $breakpoints.get(),
|
||||
canvasWidth: $canvasWidth.get(),
|
||||
workspaceRect: $workspaceRect.get(),
|
||||
};
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$canvasWidth.set(600);
|
||||
$workspaceRect.set(new DOMRect(0, 0, 800, 500));
|
||||
$isResizingCanvas.set(resizing);
|
||||
return () => {
|
||||
$isResizingCanvas.set(previous.resizing);
|
||||
$selectedBreakpointId.set(previous.breakpointId);
|
||||
$breakpoints.set(previous.breakpoints);
|
||||
$canvasWidth.set(previous.canvasWidth);
|
||||
$workspaceRect.set(previous.workspaceRect);
|
||||
};
|
||||
}, [resizing]);
|
||||
|
||||
return (
|
||||
<StorySection title="Canvas resize handles">
|
||||
<Box
|
||||
css={{
|
||||
position: "relative",
|
||||
width: 600,
|
||||
height: 420,
|
||||
backgroundColor: surface === "bright" ? "#fff" : "#151515",
|
||||
}}
|
||||
>
|
||||
<ResizeHandles />
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const BrightIdle = () => (
|
||||
<ResizeStory surface="bright" resizing={false} />
|
||||
);
|
||||
export const DarkIdle = () => <ResizeStory surface="dark" resizing={false} />;
|
||||
export const BrightResizing = () => <ResizeStory surface="bright" resizing />;
|
||||
export const DarkResizing = () => <ResizeStory surface="dark" resizing />;
|
||||
@@ -63,7 +63,7 @@ type ToolbarProps = {
|
||||
scale: number;
|
||||
};
|
||||
|
||||
const Toolbar = ({ state, scale }: ToolbarProps) => {
|
||||
export const Toolbar = ({ state, scale }: ToolbarProps) => {
|
||||
const isWithinLink = useStore($isWithinLink);
|
||||
|
||||
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -111,7 +111,7 @@ const Toolbar = ({ state, scale }: ToolbarProps) => {
|
||||
top: 0,
|
||||
left: 0,
|
||||
pointerEvents: "auto",
|
||||
background: cssVar("--background-primary"),
|
||||
background: cssVar("--background-floating-raised"),
|
||||
padding: theme.spacing[3],
|
||||
borderRadius: theme.borderRadius[6],
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { $instanceSelectionUpdate } from "~/shared/nano-states/instance-selection";
|
||||
import type { WritableAtom } from "nanostores";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import {
|
||||
getStyleDeclKey,
|
||||
type Instance,
|
||||
type StyleDecl,
|
||||
} from "@webstudio-is/sdk";
|
||||
import * as metas from "@webstudio-is/sdk-components-react/metas";
|
||||
import { cssVar } from "@webstudio-is/design-system";
|
||||
import {
|
||||
$instances,
|
||||
$project,
|
||||
$pages,
|
||||
$breakpoints,
|
||||
$styleSources,
|
||||
$styleSourceSelections,
|
||||
$styles,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$registeredComponentMetas,
|
||||
$selectedPageId,
|
||||
$selectedBreakpointId,
|
||||
$allSelectedInstanceSelectors,
|
||||
$selectedInstanceRenderState,
|
||||
$canvasIframeState,
|
||||
$authPermit,
|
||||
$builderMode,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import {
|
||||
$activeInspectorPanel,
|
||||
$dataLoadingState,
|
||||
$activeSidebarPanel,
|
||||
setActiveSidebarPanel,
|
||||
} from "./shared/nano-states";
|
||||
import { $settings } from "./shared/client-settings";
|
||||
import { Inspector } from "./inspector";
|
||||
import { SidebarLeft } from "./sidebar-left/sidebar-left";
|
||||
import { Footer } from "./features/footer/footer";
|
||||
|
||||
registerContainers();
|
||||
export default { title: "Builder/Panels", component: Inspector };
|
||||
const preserve = <T,>(store: WritableAtom<T>) => {
|
||||
const previous = store.get();
|
||||
return () => store.set(previous);
|
||||
};
|
||||
type View =
|
||||
| "style"
|
||||
| "settings"
|
||||
| "empty"
|
||||
| "multiple"
|
||||
| "notMounted"
|
||||
| "advanced"
|
||||
| "focus"
|
||||
| "list"
|
||||
| "content"
|
||||
| "components"
|
||||
| "assets"
|
||||
| "sidebar"
|
||||
| "footer";
|
||||
const PanelStory = ({ view }: { view: View }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previousSidebar = $activeSidebarPanel.get();
|
||||
const restore = [
|
||||
preserve($dataLoadingState),
|
||||
preserve($canvasIframeState),
|
||||
preserve($project),
|
||||
preserve($instances),
|
||||
preserve($pages),
|
||||
preserve($breakpoints),
|
||||
preserve($styleSources),
|
||||
preserve($styleSourceSelections),
|
||||
preserve($styles),
|
||||
preserve($registeredComponentMetas),
|
||||
preserve($selectedPageId),
|
||||
preserve($selectedBreakpointId),
|
||||
preserve($allSelectedInstanceSelectors),
|
||||
preserve($instanceSelectionUpdate),
|
||||
preserve($selectedInstanceRenderState),
|
||||
preserve($authPermit),
|
||||
preserve($builderMode),
|
||||
preserve($activeInspectorPanel),
|
||||
() => setActiveSidebarPanel(previousSidebar),
|
||||
preserve($settings),
|
||||
];
|
||||
const pages = createDefaultPages({ rootInstanceId: "body" });
|
||||
const instances: Instance[] = [
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: [{ type: "id", value: "box" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "box",
|
||||
component: view === "list" ? "List" : "Box",
|
||||
children: [{ type: "id", value: "text" }],
|
||||
},
|
||||
{
|
||||
type: "instance",
|
||||
id: "text",
|
||||
component: "Text",
|
||||
children: [{ type: "text", value: "Example" }],
|
||||
},
|
||||
];
|
||||
$registeredComponentMetas.set(new Map(Object.entries(metas)));
|
||||
$instances.set(
|
||||
new Map(instances.map((instance) => [instance.id, instance]))
|
||||
);
|
||||
$pages.set(pages);
|
||||
$selectedPageId.set(pages.homePageId);
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "Base" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$styleSources.set(new Map([["local", { id: "local", type: "local" }]]));
|
||||
$styleSourceSelections.set(
|
||||
new Map([["box", { instanceId: "box", values: ["local"] }]])
|
||||
);
|
||||
const declarations: StyleDecl[] = [
|
||||
{
|
||||
breakpointId: "base",
|
||||
styleSourceId: "local",
|
||||
property: "paddingTop",
|
||||
value: { type: "unit", value: 24, unit: "px" },
|
||||
},
|
||||
];
|
||||
$styles.set(
|
||||
new Map(declarations.map((value) => [getStyleDeclKey(value), value]))
|
||||
);
|
||||
$project.set({ id: "panel-story", title: "Example" } as Project);
|
||||
$authPermit.set("own");
|
||||
$builderMode.set(view === "content" ? "content" : "design");
|
||||
$settings.set({
|
||||
...$settings.get(),
|
||||
stylePanelMode:
|
||||
view === "advanced" || view === "focus" ? view : "default",
|
||||
});
|
||||
$activeInspectorPanel.set(
|
||||
view === "settings" || view === "content" ? "settings" : "style"
|
||||
);
|
||||
setActiveSidebarPanel(
|
||||
view === "components" || view === "assets" ? view : "none"
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
if (view === "empty") {
|
||||
$allSelectedInstanceSelectors.set([]);
|
||||
}
|
||||
if (view === "multiple") {
|
||||
$allSelectedInstanceSelectors.set([
|
||||
["box", "body"],
|
||||
["text", "box", "body"],
|
||||
]);
|
||||
}
|
||||
$selectedInstanceRenderState.set(
|
||||
view === "notMounted" ? "notMounted" : "mounted"
|
||||
);
|
||||
$dataLoadingState.set("loaded");
|
||||
$canvasIframeState.set("ready");
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
for (const reset of restore) {
|
||||
reset();
|
||||
}
|
||||
};
|
||||
}, [view]);
|
||||
if (!ready) {
|
||||
return;
|
||||
}
|
||||
if (view === "footer") {
|
||||
return <Footer />;
|
||||
}
|
||||
if (view === "sidebar" || view === "components" || view === "assets") {
|
||||
return (
|
||||
<div style={{ display: "flex", width: 40, height: 800 }}>
|
||||
<SidebarLeft publish={() => {}} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: 280,
|
||||
height: 850,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
background: cssVar("--background-primary"),
|
||||
}}
|
||||
>
|
||||
<Inspector navigatorLayout="undocked" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export const Style = () => <PanelStory view="style" />;
|
||||
export const Settings = () => <PanelStory view="settings" />;
|
||||
export const Empty = () => <PanelStory view="empty" />;
|
||||
export const Multiple = () => <PanelStory view="multiple" />;
|
||||
export const NotMounted = () => <PanelStory view="notMounted" />;
|
||||
export const Advanced = () => <PanelStory view="advanced" />;
|
||||
export const FocusMode = () => <PanelStory view="focus" />;
|
||||
export const ListItem = () => <PanelStory view="list" />;
|
||||
export const ContentMode = () => <PanelStory view="content" />;
|
||||
export const Components = () => <PanelStory view="components" />;
|
||||
export const Assets = () => <PanelStory view="assets" />;
|
||||
export const Sidebar = () => <PanelStory view="sidebar" />;
|
||||
export const Breadcrumbs = () => <PanelStory view="footer" />;
|
||||
@@ -0,0 +1,196 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import type { AssetFolder } from "@webstudio-is/sdk";
|
||||
import {
|
||||
createAssetFolderFixture,
|
||||
createAssetFoldersFixture,
|
||||
} from "@webstudio-is/sdk/testing";
|
||||
import { $assetFolders, $pages, $project } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
AssetFolderSettingsDialog,
|
||||
CreateAssetFolderDialog,
|
||||
MoveAssetManagerItemsDialog,
|
||||
} from "./asset-folder-dialogs";
|
||||
|
||||
const folder = createAssetFolderFixture({ id: "posts", name: "Posts" });
|
||||
const otherFolder = createAssetFolderFixture({
|
||||
id: "existing",
|
||||
name: "Existing",
|
||||
});
|
||||
|
||||
type State =
|
||||
| "new"
|
||||
| "new-ready"
|
||||
| "collection-option"
|
||||
| "duplicate"
|
||||
| "existing"
|
||||
| "setup-pending"
|
||||
| "setup-error"
|
||||
| "setup-success"
|
||||
| "settings"
|
||||
| "settings-no-delete"
|
||||
| "delete-confirmation"
|
||||
| "move"
|
||||
| "move-blocked";
|
||||
|
||||
const whenFound = (
|
||||
selector: string,
|
||||
onFound: (element: HTMLElement) => void
|
||||
) => {
|
||||
const observer = new MutationObserver(() => {
|
||||
const element = document.querySelector<HTMLElement>(selector);
|
||||
if (element !== null) {
|
||||
observer.disconnect();
|
||||
onFound(element);
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
const element = document.querySelector<HTMLElement>(selector);
|
||||
if (element !== null) {
|
||||
observer.disconnect();
|
||||
onFound(element);
|
||||
}
|
||||
return () => observer.disconnect();
|
||||
};
|
||||
|
||||
const FolderStory = ({ state }: { state: State }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [open, setOpen] = useState(true);
|
||||
const setupAttempts = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
folders: $assetFolders.get(),
|
||||
pages: $pages.get(),
|
||||
project: $project.get(),
|
||||
};
|
||||
$assetFolders.set(createAssetFoldersFixture(folder, otherFolder));
|
||||
$pages.set(createDefaultPages({ rootInstanceId: "body" }));
|
||||
$project.set({ id: "project" } as never);
|
||||
setReady(true);
|
||||
return () => {
|
||||
$assetFolders.set(previous.folders);
|
||||
$pages.set(previous.pages);
|
||||
$project.set(previous.project);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!ready ||
|
||||
!["duplicate", "new-ready", "collection-option"].includes(state)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
return whenFound("#asset-folder-name", (element) => {
|
||||
const input = element as HTMLInputElement;
|
||||
Object.getOwnPropertyDescriptor(
|
||||
HTMLInputElement.prototype,
|
||||
"value"
|
||||
)?.set?.call(input, state === "duplicate" ? "Existing" : "New folder");
|
||||
input.dispatchEvent(new InputEvent("input", { bubbles: true }));
|
||||
if (state === "collection-option") {
|
||||
document
|
||||
.querySelector<HTMLButtonElement>("#asset-folder-content-collection")
|
||||
?.click();
|
||||
}
|
||||
});
|
||||
}, [ready, state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || !state.startsWith("setup-")) {
|
||||
return;
|
||||
}
|
||||
return whenFound('[role="dialog"]', () => {
|
||||
Array.from(document.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((button) => button.textContent === "Use as content collection")
|
||||
?.click();
|
||||
});
|
||||
}, [ready, state]);
|
||||
|
||||
const createCollection = async (): Promise<AssetFolder> => {
|
||||
if (state === "setup-pending") {
|
||||
return new Promise<AssetFolder>(() => {});
|
||||
}
|
||||
if (state === "setup-error" && setupAttempts.current++ === 0) {
|
||||
throw new Error("The collection could not be created.");
|
||||
}
|
||||
return folder;
|
||||
};
|
||||
|
||||
if (!ready || !open) {
|
||||
return <StorySection title="Asset folder dialog">{null}</StorySection>;
|
||||
}
|
||||
|
||||
return (
|
||||
<StorySection title="Asset folder dialog">
|
||||
{state === "settings" ||
|
||||
state === "settings-no-delete" ||
|
||||
state === "delete-confirmation" ? (
|
||||
<AssetFolderSettingsDialog
|
||||
folder={folder}
|
||||
open
|
||||
onOpenChange={setOpen}
|
||||
canDelete={state !== "settings-no-delete"}
|
||||
initialDeleteConfirmation={state === "delete-confirmation"}
|
||||
onUseAsCollection={() => {}}
|
||||
/>
|
||||
) : state === "move" || state === "move-blocked" ? (
|
||||
<MoveAssetManagerItemsDialog
|
||||
initialFolderId={folder.id}
|
||||
canMove={() => state === "move"}
|
||||
onMove={() => {}}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
) : (
|
||||
<CreateAssetFolderDialog
|
||||
open
|
||||
onOpenChange={setOpen}
|
||||
onConfigureCollection={() => {}}
|
||||
currentFolderId={undefined}
|
||||
existingFolder={
|
||||
["new", "new-ready", "collection-option", "duplicate"].includes(
|
||||
state
|
||||
)
|
||||
? undefined
|
||||
: folder
|
||||
}
|
||||
createFolder={() => ({ folderId: "created" })}
|
||||
createCollection={createCollection}
|
||||
/>
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Asset Manager/Folder dialogs",
|
||||
component: CreateAssetFolderDialog,
|
||||
};
|
||||
|
||||
export const NewFolder = () => <FolderStory state="new" />;
|
||||
export const NewFolderReady = () => <FolderStory state="new-ready" />;
|
||||
export const CollectionOptionSelected = () => (
|
||||
<FolderStory state="collection-option" />
|
||||
);
|
||||
export const DuplicateName = () => <FolderStory state="duplicate" />;
|
||||
export const ExistingFolderSetup = () => <FolderStory state="existing" />;
|
||||
export const CollectionSetupPending = () => (
|
||||
<FolderStory state="setup-pending" />
|
||||
);
|
||||
export const CollectionSetupErrorAndRetry = () => (
|
||||
<FolderStory state="setup-error" />
|
||||
);
|
||||
export const CollectionSetupSuccess = () => (
|
||||
<FolderStory state="setup-success" />
|
||||
);
|
||||
export const FolderSettings = () => <FolderStory state="settings" />;
|
||||
export const FolderSettingsNoDelete = () => (
|
||||
<FolderStory state="settings-no-delete" />
|
||||
);
|
||||
export const DeleteConfirmation = () => (
|
||||
<FolderStory state="delete-confirmation" />
|
||||
);
|
||||
export const MoveAllowed = () => <FolderStory state="move" />;
|
||||
export const MoveBlocked = () => <FolderStory state="move-blocked" />;
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
createDefaultCollectionConfig,
|
||||
parseCollectionConfig,
|
||||
} from "@webstudio-is/content-engine";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import { $authPermit } from "~/shared/nano-states";
|
||||
import { $assets } from "~/shared/sync/data-stores";
|
||||
import { CollectionEntrySettingsDialog } from "./collection-entry-settings-dialog";
|
||||
|
||||
const asset: Asset = {
|
||||
id: "post",
|
||||
projectId: "project",
|
||||
name: "post.mdx",
|
||||
filename: "post",
|
||||
folderId: "posts",
|
||||
type: "file",
|
||||
format: "mdx",
|
||||
size: 1,
|
||||
meta: {},
|
||||
createdAt: "2026-09-08T00:00:00Z",
|
||||
};
|
||||
const collection = {
|
||||
status: "ready" as const,
|
||||
folderId: "posts",
|
||||
configAsset: asset,
|
||||
templateAsset: asset,
|
||||
templateProperties: {},
|
||||
config: parseCollectionConfig(createDefaultCollectionConfig()),
|
||||
};
|
||||
const validSource = "---\ntitle: Old\nslug: post\ndraft: false\n---\nBody";
|
||||
const invalidSource = "---\ntitle: \nslug: different\ndraft: yes\n---\nBody";
|
||||
|
||||
type State =
|
||||
| "loading"
|
||||
| "read-error"
|
||||
| "loaded"
|
||||
| "validation"
|
||||
| "saving"
|
||||
| "save-error"
|
||||
| "uncertain-save"
|
||||
| "discard"
|
||||
| "canvas-unavailable";
|
||||
|
||||
const whenFound = (
|
||||
selector: string,
|
||||
onFound: (element: HTMLElement) => void
|
||||
) => {
|
||||
const found = document.querySelector<HTMLElement>(selector);
|
||||
if (found !== null) {
|
||||
onFound(found);
|
||||
return () => {};
|
||||
}
|
||||
const observer = new MutationObserver(() => {
|
||||
const element = document.querySelector<HTMLElement>(selector);
|
||||
if (element !== null) {
|
||||
observer.disconnect();
|
||||
onFound(element);
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
return () => observer.disconnect();
|
||||
};
|
||||
|
||||
const EntryStory = ({ state }: { state: State }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [open, setOpen] = useState(true);
|
||||
const readAttempt = useRef(0);
|
||||
const saveAttempt = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const previousAssets = $assets.get();
|
||||
const previousPermit = $authPermit.get();
|
||||
$assets.set(new Map([[asset.id, asset]]));
|
||||
$authPermit.set("own");
|
||||
setReady(true);
|
||||
return () => {
|
||||
$assets.set(previousAssets);
|
||||
$authPermit.set(previousPermit);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!ready ||
|
||||
!["saving", "save-error", "uncertain-save", "discard"].includes(state)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
return whenFound("#collection-entry-title", (element) => {
|
||||
const input = element as HTMLInputElement;
|
||||
const setValue = Object.getOwnPropertyDescriptor(
|
||||
HTMLInputElement.prototype,
|
||||
"value"
|
||||
)?.set;
|
||||
setValue?.call(input, "Updated");
|
||||
input.dispatchEvent(new InputEvent("input", { bubbles: true }));
|
||||
});
|
||||
}, [ready, state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || state !== "discard") {
|
||||
return;
|
||||
}
|
||||
return whenFound('[role="alert"]', () => {
|
||||
Array.from(document.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((button) => button.textContent === "Edit file")
|
||||
?.click();
|
||||
});
|
||||
}, [ready, state]);
|
||||
|
||||
const readSource = async () => {
|
||||
if (state === "loading") {
|
||||
return new Promise<string>(() => {});
|
||||
}
|
||||
if (state === "read-error" && readAttempt.current++ === 0) {
|
||||
throw new Error("The entry could not be loaded.");
|
||||
}
|
||||
return state === "validation" ? invalidSource : validSource;
|
||||
};
|
||||
const updateContent = async () => {
|
||||
if (state === "saving") {
|
||||
return new Promise<Asset>(() => {});
|
||||
}
|
||||
if (state === "uncertain-save" || state === "discard") {
|
||||
throw Object.assign(new Error("The entry could not be saved."), {
|
||||
code: "ASSET_UPDATE_COMMIT_UNCERTAIN",
|
||||
});
|
||||
}
|
||||
if (state === "save-error" && saveAttempt.current++ === 0) {
|
||||
throw new Error("The entry could not be saved.");
|
||||
}
|
||||
return asset;
|
||||
};
|
||||
|
||||
return (
|
||||
<StorySection title="Entry settings">
|
||||
{ready && open && (
|
||||
<CollectionEntrySettingsDialog
|
||||
asset={asset}
|
||||
collection={collection}
|
||||
readSource={readSource}
|
||||
updateContent={updateContent}
|
||||
onClose={() => setOpen(false)}
|
||||
onOpenFile={() => setOpen(false)}
|
||||
onOpenCanvas={
|
||||
state === "canvas-unavailable" ? undefined : () => setOpen(false)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Asset Manager/Collection entry settings",
|
||||
component: CollectionEntrySettingsDialog,
|
||||
};
|
||||
|
||||
export const Loading = () => <EntryStory state="loading" />;
|
||||
export const ReadErrorAndRetry = () => <EntryStory state="read-error" />;
|
||||
export const Loaded = () => <EntryStory state="loaded" />;
|
||||
export const Validation = () => <EntryStory state="validation" />;
|
||||
export const Saving = () => <EntryStory state="saving" />;
|
||||
export const SaveErrorAndRetry = () => <EntryStory state="save-error" />;
|
||||
export const UncertainSave = () => <EntryStory state="uncertain-save" />;
|
||||
export const DiscardConfirmation = () => <EntryStory state="discard" />;
|
||||
export const CanvasUnavailable = () => (
|
||||
<EntryStory state="canvas-unavailable" />
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import {
|
||||
$assets,
|
||||
$pages,
|
||||
$projectSettings,
|
||||
$props,
|
||||
$styles,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import {
|
||||
DeleteUnusedAssetsDialog,
|
||||
openDeleteUnusedAssetsDialog,
|
||||
} from "./delete-unused-assets";
|
||||
|
||||
registerContainers();
|
||||
|
||||
const createFile = (id: string): Asset => ({
|
||||
id,
|
||||
projectId: "project",
|
||||
name: `${id}.txt`,
|
||||
filename: id,
|
||||
type: "file",
|
||||
format: "txt",
|
||||
size: 1,
|
||||
meta: {},
|
||||
createdAt: "2026-09-08T00:00:00Z",
|
||||
});
|
||||
|
||||
const UnusedAssetsStory = ({
|
||||
state,
|
||||
}: {
|
||||
state: "empty" | "populated" | "deselected";
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
assets: $assets.get(),
|
||||
pages: $pages.get(),
|
||||
projectSettings: $projectSettings.get(),
|
||||
props: $props.get(),
|
||||
styles: $styles.get(),
|
||||
};
|
||||
const files =
|
||||
state === "empty" ? [] : [createFile("first"), createFile("second")];
|
||||
$assets.set(new Map(files.map((file) => [file.id, file])));
|
||||
$pages.set(createDefaultPages({ rootInstanceId: "body" }));
|
||||
$projectSettings.set({ meta: {}, compiler: {} });
|
||||
$props.set(new Map());
|
||||
$styles.set(new Map());
|
||||
setReady(true);
|
||||
return () => {
|
||||
$assets.set(previous.assets);
|
||||
$pages.set(previous.pages);
|
||||
$projectSettings.set(previous.projectSettings);
|
||||
$props.set(previous.props);
|
||||
$styles.set(previous.styles);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready) {
|
||||
return;
|
||||
}
|
||||
openDeleteUnusedAssetsDialog();
|
||||
if (state !== "deselected") {
|
||||
return;
|
||||
}
|
||||
const observer = new MutationObserver(() => {
|
||||
const selectAll = document.querySelector<HTMLButtonElement>(
|
||||
"#select-all-unused-assets"
|
||||
);
|
||||
if (selectAll !== null) {
|
||||
observer.disconnect();
|
||||
selectAll.click();
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
return () => observer.disconnect();
|
||||
}, [ready, state]);
|
||||
|
||||
return (
|
||||
<StorySection title="Delete unused assets">
|
||||
{ready && <DeleteUnusedAssetsDialog />}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Asset Manager/Delete unused assets",
|
||||
component: DeleteUnusedAssetsDialog,
|
||||
};
|
||||
|
||||
export const Empty = () => <UnusedAssetsStory state="empty" />;
|
||||
export const Populated = () => <UnusedAssetsStory state="populated" />;
|
||||
export const AllDeselected = () => <UnusedAssetsStory state="deselected" />;
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
Box,
|
||||
InputField,
|
||||
StorySection,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { validatePrimitiveValue } from "@webstudio-is/project-build/runtime";
|
||||
import { $builderMode } from "~/shared/nano-states";
|
||||
import {
|
||||
BindingControl,
|
||||
BindingPopover,
|
||||
type BindingVariant,
|
||||
} from "./binding-popover";
|
||||
|
||||
export default {
|
||||
title: "Builder/Binding popover",
|
||||
component: BindingPopover,
|
||||
};
|
||||
|
||||
const BindingStory = ({
|
||||
variant,
|
||||
value,
|
||||
error = false,
|
||||
removable = true,
|
||||
}: {
|
||||
variant: BindingVariant;
|
||||
value?: string;
|
||||
error?: boolean;
|
||||
removable?: boolean;
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const previousMode = $builderMode.get();
|
||||
$builderMode.set("design");
|
||||
setReady(true);
|
||||
return () => $builderMode.set(previousMode);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (ready) {
|
||||
containerRef.current
|
||||
?.querySelector<HTMLButtonElement>("button[data-variant]")
|
||||
?.click();
|
||||
}
|
||||
}, [ready]);
|
||||
|
||||
return (
|
||||
<StorySection title="Binding">
|
||||
<Box
|
||||
ref={containerRef}
|
||||
data-floating-panel-container
|
||||
css={{
|
||||
width: theme.sizes.sidebarWidth,
|
||||
height: 720,
|
||||
marginLeft: 360,
|
||||
marginTop: 100,
|
||||
}}
|
||||
>
|
||||
<BindingControl>
|
||||
<InputField aria-label="Value" value="Example" readOnly />
|
||||
<BindingPopover
|
||||
scope={{ title: "Example" }}
|
||||
aliases={new Map([["title", "title"]])}
|
||||
variant={variant}
|
||||
value={value}
|
||||
validate={
|
||||
error
|
||||
? (value) => validatePrimitiveValue(value, "Value")
|
||||
: undefined
|
||||
}
|
||||
onChange={() => {}}
|
||||
onRemove={removable ? () => {} : undefined}
|
||||
/>
|
||||
</BindingControl>
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Default = () => <BindingStory variant="default" />;
|
||||
export const Bound = () => <BindingStory variant="bound" value="title" />;
|
||||
export const Error = () => <BindingStory variant="bound" value="({})" error />;
|
||||
export const ResetDisabled = () => (
|
||||
<BindingStory variant="bound" value="title" removable={false} />
|
||||
);
|
||||
@@ -28,7 +28,12 @@ type Label = string;
|
||||
const sectionStyle = css({
|
||||
variants: {
|
||||
background: {
|
||||
true: { background: cssVar("--background-primary") },
|
||||
true: {
|
||||
background: cssVar("--background-primary"),
|
||||
"[data-floating-panel] &": {
|
||||
background: cssVar("--background-floating"),
|
||||
},
|
||||
},
|
||||
},
|
||||
sticky: {
|
||||
true: { position: "sticky", bottom: 0, zIndex: 1 },
|
||||
@@ -41,6 +46,9 @@ const sectionStyle = css({
|
||||
zIndex: 1,
|
||||
background: cssVar("--background-primary"),
|
||||
},
|
||||
"[data-floating-panel] & > [data-focus-scope-start] + [data-state]": {
|
||||
background: cssVar("--background-floating"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useEffect } from "react";
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import type { StyleSource } from "@webstudio-is/sdk";
|
||||
import {
|
||||
$styleSourceSelections,
|
||||
$styleSources,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import {
|
||||
DeleteStyleSourceDialog,
|
||||
DeleteUnusedTokensDialog,
|
||||
RenameStyleSourceDialog,
|
||||
openDeleteUnusedTokensDialog,
|
||||
} from "./style-source-actions";
|
||||
|
||||
export default { title: "Style panel/Style source actions" };
|
||||
|
||||
const token = { id: "primary", name: "Primary", type: "token" } as const;
|
||||
const otherToken = {
|
||||
id: "secondary",
|
||||
name: "Secondary",
|
||||
type: "token",
|
||||
} as const;
|
||||
|
||||
const ActionsStory = ({
|
||||
state,
|
||||
}: {
|
||||
state: "delete" | "rename" | "rename-invalid" | "unused-empty" | "unused";
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
styleSources: $styleSources.get(),
|
||||
selections: $styleSourceSelections.get(),
|
||||
};
|
||||
$styleSources.set(
|
||||
new Map<string, StyleSource>(
|
||||
state === "unused-empty"
|
||||
? []
|
||||
: [
|
||||
[
|
||||
token.id,
|
||||
state === "rename-invalid" ? { ...token, name: "" } : token,
|
||||
],
|
||||
[otherToken.id, otherToken],
|
||||
]
|
||||
)
|
||||
);
|
||||
$styleSourceSelections.set(new Map());
|
||||
if (state.startsWith("unused")) {
|
||||
openDeleteUnusedTokensDialog();
|
||||
}
|
||||
if (state === "rename-invalid") {
|
||||
const showError = () => {
|
||||
const button = Array.from(document.querySelectorAll("button")).find(
|
||||
(item) => item.textContent === "Rename"
|
||||
);
|
||||
if (button) {
|
||||
observer.disconnect();
|
||||
button.click();
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(showError);
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
showError();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
$styleSources.set(previous.styleSources);
|
||||
$styleSourceSelections.set(previous.selections);
|
||||
};
|
||||
}
|
||||
return () => {
|
||||
if (state.startsWith("unused")) {
|
||||
const close = Array.from(document.querySelectorAll("button")).find(
|
||||
(item) =>
|
||||
item.textContent === "Close" || item.textContent === "Cancel"
|
||||
);
|
||||
close?.click();
|
||||
}
|
||||
$styleSources.set(previous.styleSources);
|
||||
$styleSourceSelections.set(previous.selections);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
const styleSource = {
|
||||
id: token.id,
|
||||
name: state === "rename-invalid" ? "" : token.name,
|
||||
};
|
||||
return (
|
||||
<StorySection title="Style source actions">
|
||||
{state === "delete" && (
|
||||
<DeleteStyleSourceDialog
|
||||
styleSource={styleSource}
|
||||
onClose={() => {}}
|
||||
onConfirm={() => {}}
|
||||
/>
|
||||
)}
|
||||
{(state === "rename" || state === "rename-invalid") && (
|
||||
<RenameStyleSourceDialog
|
||||
styleSource={styleSource}
|
||||
onClose={() => {}}
|
||||
onConfirm={() => {}}
|
||||
/>
|
||||
)}
|
||||
{state.startsWith("unused") && <DeleteUnusedTokensDialog />}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const DeleteToken = () => <ActionsStory state="delete" />;
|
||||
export const RenameToken = () => <ActionsStory state="rename" />;
|
||||
export const RenameValidation = () => <ActionsStory state="rename-invalid" />;
|
||||
export const NoUnusedTokens = () => <ActionsStory state="unused-empty" />;
|
||||
export const UnusedTokens = () => <ActionsStory state="unused" />;
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import {
|
||||
blockComponent,
|
||||
blockTemplateComponent,
|
||||
blockBodyComponent,
|
||||
type Instance,
|
||||
} from "@webstudio-is/sdk";
|
||||
import {
|
||||
componentAttribute,
|
||||
idAttribute,
|
||||
selectorIdAttribute,
|
||||
} from "@webstudio-is/react-sdk";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$builderMode,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances } from "~/shared/sync/data-stores";
|
||||
import { Block } from "./block";
|
||||
import { BlockBody } from "./block-body";
|
||||
import { BlockTemplate } from "./block-template";
|
||||
|
||||
export default {
|
||||
title: "Canvas/Content block editor states",
|
||||
component: Block,
|
||||
};
|
||||
|
||||
type State =
|
||||
| "missing"
|
||||
| "noTemplates"
|
||||
| "empty"
|
||||
| "selectedTemplate"
|
||||
| "emptyBody";
|
||||
|
||||
const BlockStory = ({
|
||||
state,
|
||||
surface,
|
||||
}: {
|
||||
state: State;
|
||||
surface: "bright" | "dark";
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previousInstances = $instances.get();
|
||||
const previousMode = $builderMode.get();
|
||||
const previousSelection = $allSelectedInstanceSelectors.get();
|
||||
const instances: Instance[] = [
|
||||
{
|
||||
id: "block",
|
||||
type: "instance",
|
||||
component: blockComponent,
|
||||
children:
|
||||
state === "noTemplates" ? [] : [{ type: "id", value: "templates" }],
|
||||
},
|
||||
{
|
||||
id: "templates",
|
||||
type: "instance",
|
||||
component: blockTemplateComponent,
|
||||
children: [],
|
||||
},
|
||||
];
|
||||
$instances.set(
|
||||
new Map(
|
||||
(state === "missing" ? [] : instances).map((instance) => [
|
||||
instance.id,
|
||||
instance,
|
||||
])
|
||||
)
|
||||
);
|
||||
$builderMode.set("design");
|
||||
$allSelectedInstanceSelectors.set(
|
||||
state === "selectedTemplate" ? [["templates", "block"]] : []
|
||||
);
|
||||
setReady(true);
|
||||
return () => {
|
||||
$instances.set(previousInstances);
|
||||
$allSelectedInstanceSelectors.set(previousSelection);
|
||||
$builderMode.set(previousMode);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
return (
|
||||
<StorySection title="Content block editor">
|
||||
<div
|
||||
style={{
|
||||
padding: 32,
|
||||
width: 560,
|
||||
minHeight: 220,
|
||||
background: surface === "bright" ? "#fff" : "#151515",
|
||||
color: surface === "bright" ? "#151515" : "#fff",
|
||||
}}
|
||||
>
|
||||
{ready &&
|
||||
(state === "emptyBody" ? (
|
||||
<BlockBody
|
||||
{...{
|
||||
[componentAttribute]: blockBodyComponent,
|
||||
[idAttribute]: "body",
|
||||
[selectorIdAttribute]: "body,block",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<Block
|
||||
{...{
|
||||
[idAttribute]: "block",
|
||||
[selectorIdAttribute]: "block",
|
||||
[componentAttribute]: blockComponent,
|
||||
}}
|
||||
>
|
||||
<BlockTemplate
|
||||
{...{
|
||||
[idAttribute]: "templates",
|
||||
[selectorIdAttribute]: "templates,block",
|
||||
[componentAttribute]: blockTemplateComponent,
|
||||
instanceSelector: ["templates", "block"],
|
||||
}}
|
||||
>
|
||||
{state === "selectedTemplate" && <p>Template content</p>}
|
||||
</BlockTemplate>
|
||||
{state === "selectedTemplate" && (
|
||||
<BlockBody
|
||||
{...{
|
||||
[idAttribute]: "body",
|
||||
[selectorIdAttribute]: "body,block",
|
||||
[componentAttribute]: blockBodyComponent,
|
||||
instanceSelector: ["body", "block"],
|
||||
}}
|
||||
>
|
||||
<p>Entry content</p>
|
||||
</BlockBody>
|
||||
)}
|
||||
</Block>
|
||||
))}
|
||||
</div>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const MissingInstanceBright = () => (
|
||||
<BlockStory state="missing" surface="bright" />
|
||||
);
|
||||
export const MissingInstanceDark = () => (
|
||||
<BlockStory state="missing" surface="dark" />
|
||||
);
|
||||
export const MissingTemplatesBright = () => (
|
||||
<BlockStory state="noTemplates" surface="bright" />
|
||||
);
|
||||
export const MissingTemplatesDark = () => (
|
||||
<BlockStory state="noTemplates" surface="dark" />
|
||||
);
|
||||
export const EmptyEditableBright = () => (
|
||||
<BlockStory state="empty" surface="bright" />
|
||||
);
|
||||
export const EmptyEditableDark = () => (
|
||||
<BlockStory state="empty" surface="dark" />
|
||||
);
|
||||
export const SelectedTemplateBright = () => (
|
||||
<BlockStory state="selectedTemplate" surface="bright" />
|
||||
);
|
||||
export const SelectedTemplateDark = () => (
|
||||
<BlockStory state="selectedTemplate" surface="dark" />
|
||||
);
|
||||
export const EmptyBodyBright = () => (
|
||||
<BlockStory state="emptyBody" surface="bright" />
|
||||
);
|
||||
export const EmptyBodyDark = () => (
|
||||
<BlockStory state="emptyBody" surface="dark" />
|
||||
);
|
||||
@@ -1,3 +1,4 @@
|
||||
import { RequestFixture } from "~/shared/storybook/request-fixture";
|
||||
import type { StoryFn } from "@storybook/react";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router-dom";
|
||||
import type { Workspace } from "@webstudio-is/project";
|
||||
@@ -120,3 +121,58 @@ export const Leave: StoryFn = () => {
|
||||
);
|
||||
return <RouterProvider router={router} />;
|
||||
};
|
||||
|
||||
const membersRequest =
|
||||
(maxSeats: number, empty = false) =>
|
||||
(request: Request) =>
|
||||
new URL(request.url).pathname === "/trpc/workspace.listMembers"
|
||||
? Response.json([
|
||||
{
|
||||
result: {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
owner: { email: "owner@example.com" },
|
||||
members: empty
|
||||
? []
|
||||
: [
|
||||
{
|
||||
email: "member@example.com",
|
||||
userId: "member",
|
||||
relation: "designers",
|
||||
},
|
||||
],
|
||||
pendingInvites: empty
|
||||
? []
|
||||
: [
|
||||
{
|
||||
email: "pending@example.com",
|
||||
notificationId: "pending",
|
||||
relation: "viewers",
|
||||
},
|
||||
],
|
||||
maxSeats,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
])
|
||||
: undefined;
|
||||
const membersAvailable = membersRequest(5);
|
||||
const membersOverCapacity = membersRequest(0);
|
||||
const membersEmpty = membersRequest(5, true);
|
||||
export const MembersLoaded = () => (
|
||||
<RequestFixture request={membersAvailable}>
|
||||
<ManageMembersOwner />
|
||||
</RequestFixture>
|
||||
);
|
||||
export const MembersOverCapacity = () => (
|
||||
<RequestFixture request={membersOverCapacity}>
|
||||
<ManageMembersOwner />
|
||||
</RequestFixture>
|
||||
);
|
||||
export const MembersEmpty = () => (
|
||||
<RequestFixture request={membersEmpty}>
|
||||
<ManageMembersOwner />
|
||||
</RequestFixture>
|
||||
);
|
||||
@@ -282,3 +282,49 @@ test("keeps editor chrome in form dialogs but removes it in editor dialogs", ()
|
||||
expect(getComputedStyle(fullEditor!).borderLeftWidth).toBe("0px");
|
||||
expect(getComputedStyle(fullEditor!).paddingLeft).toBe("0px");
|
||||
});
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"keeps the CSS editor shortcut footer on the dialog surface in %s mode",
|
||||
(mode) => {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
act(() => {
|
||||
root.render(
|
||||
<EditorDialog
|
||||
open
|
||||
title="CSS value"
|
||||
content={
|
||||
<EditorContent
|
||||
value="1fr"
|
||||
showShortcuts
|
||||
onChange={() => {}}
|
||||
onChangeComplete={() => {}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
|
||||
const footer = dialog
|
||||
?.querySelector<HTMLElement>(".cm-editor")
|
||||
?.parentElement?.querySelector<HTMLElement>(":scope > div:first-child");
|
||||
if (dialog === null || footer === null || footer === undefined) {
|
||||
throw new Error("Expected the CSS editor dialog and shortcut footer");
|
||||
}
|
||||
|
||||
const context = document.createElement("canvas").getContext("2d");
|
||||
if (context === null) {
|
||||
throw new Error("Expected canvas color evaluation");
|
||||
}
|
||||
context.fillStyle = getComputedStyle(dialog).backgroundColor;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
const surface = context.getImageData(0, 0, 1, 1).data;
|
||||
context.fillStyle = getComputedStyle(footer).backgroundColor;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
const underFooter = context.getImageData(0, 0, 1, 1).data;
|
||||
|
||||
for (const channel of [0, 1, 2]) {
|
||||
expect(Math.abs(underFooter[channel] - surface[channel])).toBeLessThan(2);
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -192,6 +192,9 @@ const shortcutStyle = css({
|
||||
width: "100%",
|
||||
paddingInline: theme.spacing[3],
|
||||
background: `oklch(from ${cssVar("--background-primary")} l c h / 50%)`,
|
||||
"[data-editor-dialog-content] &": {
|
||||
background: `oklch(from ${cssVar("--background-floating")} l c h / 50%)`,
|
||||
},
|
||||
zIndex: 1,
|
||||
pointerEvents: "none",
|
||||
});
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Suspense, useState } from "react";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router-dom";
|
||||
import { ErrorBoundary } from "./error-boundary";
|
||||
export default { title: "Error boundary", component: ErrorBoundary };
|
||||
const RouteError = ({
|
||||
status = 404,
|
||||
unexpected = false,
|
||||
}: {
|
||||
status?: number;
|
||||
unexpected?: boolean;
|
||||
}) => {
|
||||
const [router] = useState(() =>
|
||||
createMemoryRouter([
|
||||
{
|
||||
path: "/",
|
||||
loader: () => {
|
||||
if (unexpected) {
|
||||
throw new Error("Example unexpected failure");
|
||||
}
|
||||
throw Response.json(
|
||||
{
|
||||
message: "Example request failed",
|
||||
description: "Please try again later.",
|
||||
},
|
||||
{ status }
|
||||
);
|
||||
},
|
||||
errorElement: (
|
||||
<Suspense>
|
||||
<ErrorBoundary />
|
||||
</Suspense>
|
||||
),
|
||||
},
|
||||
])
|
||||
);
|
||||
return <RouterProvider router={router} />;
|
||||
};
|
||||
export const NotFound = () => <RouteError />;
|
||||
export const Forbidden = () => <RouteError status={403} />;
|
||||
export const ServerError = () => <RouteError status={500} />;
|
||||
export const Unexpected = () => <RouteError unexpected />;
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
DesignTokenImportDialog,
|
||||
showDesignTokenImportDialog,
|
||||
} from "./design-token-import-dialog";
|
||||
import {
|
||||
TokenConflictDialog,
|
||||
showTokenConflictDialog,
|
||||
} from "./token-conflict-dialog";
|
||||
import {
|
||||
RootStyleConflictDialog,
|
||||
showRootStyleConflictDialog,
|
||||
} from "./root-style-conflict-dialog";
|
||||
|
||||
export default { title: "Import dialogs" };
|
||||
|
||||
export const ImportTokens = () => {
|
||||
useEffect(() => {
|
||||
showDesignTokenImportDialog();
|
||||
}, []);
|
||||
return <DesignTokenImportDialog />;
|
||||
};
|
||||
|
||||
export const TokenConflict = () => {
|
||||
useEffect(() => {
|
||||
showTokenConflictDialog([
|
||||
{ tokenName: "Primary" },
|
||||
{ tokenName: "Heading" },
|
||||
]);
|
||||
}, []);
|
||||
return <TokenConflictDialog />;
|
||||
};
|
||||
|
||||
export const GlobalStyleConflict = () => {
|
||||
useEffect(() => {
|
||||
showRootStyleConflictDialog([
|
||||
{
|
||||
existingStyle: {
|
||||
styleSourceId: "existing",
|
||||
breakpointId: "base",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "blue" },
|
||||
},
|
||||
incomingStyle: {
|
||||
styleSourceId: "incoming",
|
||||
breakpointId: "base",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
},
|
||||
breakpointLabel: "Base",
|
||||
},
|
||||
]);
|
||||
}, []);
|
||||
return <RootStyleConflictDialog />;
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { LogoutPage } from "./logout.client";
|
||||
import { RequestFixture } from "./storybook/request-fixture";
|
||||
|
||||
const pendingLogout = (request: Request) => {
|
||||
if (new URL(request.url).pathname === "/storybook/logout") {
|
||||
return new Promise<Response>(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
export default { title: "Logout" };
|
||||
|
||||
export const Pending = () => (
|
||||
<RequestFixture request={pendingLogout}>
|
||||
<LogoutPage logoutUrls={["/storybook/logout"]} />
|
||||
</RequestFixture>
|
||||
);
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { useEffect, useState, type ComponentProps } from "react";
|
||||
import { createBrowserRouter, RouterProvider } from "react-router-dom";
|
||||
import { $authPermit, $builderMode, $planFeatures } from "~/shared/nano-states";
|
||||
import { $project, $projectSettings } from "~/shared/sync/data-stores";
|
||||
import { RequestFixture } from "../storybook/request-fixture";
|
||||
import type { SectionName } from "~/shared/nano-states/project-settings";
|
||||
import { ProjectSettingsDialog } from "./project-settings";
|
||||
|
||||
export default {
|
||||
title: "Project settings/States",
|
||||
component: ProjectSettingsDialog,
|
||||
};
|
||||
|
||||
type Props = {
|
||||
section: SectionName;
|
||||
readOnly?: boolean;
|
||||
invalid?: boolean;
|
||||
pro?: boolean;
|
||||
backups?: "loaded" | "pending" | "error";
|
||||
status?: ComponentProps<typeof ProjectSettingsDialog>["status"];
|
||||
};
|
||||
const Settings = ({
|
||||
section,
|
||||
readOnly = false,
|
||||
invalid = false,
|
||||
pro = false,
|
||||
status,
|
||||
}: Props) => {
|
||||
const [currentSection, setCurrentSection] = useState(section);
|
||||
useEffect(() => {
|
||||
const previous = [
|
||||
$authPermit.get(),
|
||||
$builderMode.get(),
|
||||
$projectSettings.get(),
|
||||
$project.get(),
|
||||
$planFeatures.get(),
|
||||
] as const;
|
||||
$project.set({
|
||||
id: "storybook-project",
|
||||
title: "My Project",
|
||||
marketplaceApprovalStatus: "UNLISTED",
|
||||
} as Project);
|
||||
$authPermit.set("own");
|
||||
$planFeatures.set({ ...$planFeatures.get(), canRestoreBackups: pro });
|
||||
$builderMode.set(readOnly ? "content" : "design");
|
||||
$projectSettings.set({
|
||||
meta: invalid
|
||||
? { contactEmail: "invalid", emailSender: "invalid", auth: "invalid" }
|
||||
: {},
|
||||
compiler: {},
|
||||
});
|
||||
return () => {
|
||||
$authPermit.set(previous[0]);
|
||||
$builderMode.set(previous[1]);
|
||||
$projectSettings.set(previous[2]);
|
||||
$project.set(previous[3]);
|
||||
$planFeatures.set(previous[4]);
|
||||
};
|
||||
}, [readOnly, invalid, pro]);
|
||||
return (
|
||||
<ProjectSettingsDialog
|
||||
currentSection={currentSection}
|
||||
onSectionChange={setCurrentSection}
|
||||
status={status}
|
||||
projectId="storybook-project"
|
||||
/>
|
||||
);
|
||||
};
|
||||
const backupResponses = {
|
||||
loaded: () =>
|
||||
Response.json([
|
||||
{
|
||||
result: {
|
||||
data: {
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
buildId: "example-build",
|
||||
createdAt: "2026-11-01T12:00:00Z",
|
||||
domains: "example.com",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
]),
|
||||
pending: () => new Promise<Response>(() => {}),
|
||||
error: () =>
|
||||
Response.json(
|
||||
[
|
||||
{
|
||||
error: {
|
||||
message: "Example request failed",
|
||||
code: -32603,
|
||||
data: { code: "INTERNAL_SERVER_ERROR", httpStatus: 500 },
|
||||
},
|
||||
},
|
||||
],
|
||||
{ status: 500 }
|
||||
),
|
||||
empty: () =>
|
||||
Response.json([{ result: { data: { success: true, data: [] } } }]),
|
||||
};
|
||||
const SettingsStory = (props: Props) => {
|
||||
const [router] = useState(() =>
|
||||
createBrowserRouter([
|
||||
{ path: "*", loader: () => null, element: <Settings {...props} /> },
|
||||
])
|
||||
);
|
||||
const [request] = useState(
|
||||
() => (request: Request) =>
|
||||
new URL(request.url).pathname === "/trpc/project.publishedBuilds"
|
||||
? backupResponses[props.backups ?? "empty"]()
|
||||
: undefined
|
||||
);
|
||||
return (
|
||||
<RequestFixture request={request}>
|
||||
<RouterProvider router={router} />
|
||||
</RequestFixture>
|
||||
);
|
||||
};
|
||||
export const Emails = () => <SettingsStory section="emails" />;
|
||||
export const EmailErrors = () => <SettingsStory section="emails" invalid />;
|
||||
export const Agents = () => <SettingsStory section="agents" />;
|
||||
export const Publishing = () => <SettingsStory section="publish" />;
|
||||
export const Marketplace = () => <SettingsStory section="marketplace" />;
|
||||
export const Authentication = () => <SettingsStory section="auth" />;
|
||||
export const AuthenticationError = () => (
|
||||
<SettingsStory section="auth" invalid />
|
||||
);
|
||||
export const Backups = () => <SettingsStory section="backups" />;
|
||||
export const Loading = () => (
|
||||
<SettingsStory section="general" status="loading" />
|
||||
);
|
||||
export const ReadOnly = () => <SettingsStory section="general" readOnly />;
|
||||
|
||||
export const BackupsAvailable = () => (
|
||||
<SettingsStory section="backups" backups="loaded" pro />
|
||||
);
|
||||
export const BackupsUpgrade = () => (
|
||||
<SettingsStory section="backups" backups="loaded" />
|
||||
);
|
||||
export const BackupsPending = () => (
|
||||
<SettingsStory section="backups" backups="pending" pro />
|
||||
);
|
||||
export const BackupsError = () => (
|
||||
<SettingsStory section="backups" backups="error" pro />
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import {
|
||||
setRequestFixture,
|
||||
type RequestFixture as Handler,
|
||||
} from "../../../../../.storybook/request-fixtures";
|
||||
|
||||
/** Keep clients real; provide local HTTP responses before mounting their UI. */
|
||||
export const RequestFixture = ({
|
||||
request,
|
||||
children,
|
||||
}: {
|
||||
request: Handler;
|
||||
children: ReactNode;
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const restore = setRequestFixture(request);
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
restore();
|
||||
};
|
||||
}, [request]);
|
||||
return ready ? children : null;
|
||||
};
|
||||
@@ -37,9 +37,12 @@ scheme derivation bounds rather than maintaining a second theme or semantic
|
||||
color set. Cross-hue variants mix in `oklab`, so the neutral family cannot
|
||||
rotate an intent into another color family.
|
||||
|
||||
Default chromatic fills keep the same bounded luminance in both schemes. Dark
|
||||
mode derives lighter foreground and focus variants from the same color family
|
||||
and uses light content on strong chromatic fills.
|
||||
Default chromatic fills use the same lightness and chroma bounds in both schemes.
|
||||
All intent text uses one shared lightness bound per scheme. Floating surfaces
|
||||
share the same mixing recipe with a weight for each level. These private scheme
|
||||
values can feed derived or semantic colors; components still consume only
|
||||
semantic colors. Dark mode uses lighter intent text and light content on strong
|
||||
chromatic fills.
|
||||
|
||||
## Theme parameters
|
||||
|
||||
@@ -60,10 +63,9 @@ parameter is commented at its declaration in [`colors.css`](colors.css).
|
||||
|
||||
Theme colors support opaque, context-independent CSS colors such as hex,
|
||||
`rgb()`, and `oklch()` values. Alpha colors and context-dependent keywords such
|
||||
as `currentColor` are outside the contract. The recipe converts chromatic
|
||||
inputs into the display gamut, limits their OKLCH source to `0.2–0.8` lightness
|
||||
and `0.3` chroma, then caps relative luminance by scaling XYZ toward black.
|
||||
Neutral chroma is limited to `0.02`.
|
||||
as `currentColor` are outside the contract. The recipe converts chromatic inputs into the display gamut and limits fill
|
||||
lightness to `0.2–0.48` and chroma to `0.3`. Intent text uses lightness `0.48`
|
||||
in light mode and `0.75` in dark mode. Neutral chroma is limited to `0.02`.
|
||||
|
||||
The default light and dark outputs are regression tested. Custom theme values
|
||||
can produce lower-contrast combinations, so theme authors must verify the
|
||||
@@ -120,18 +122,19 @@ styled("button", {
|
||||
|
||||
The package extends Craft's core registry only for reusable component needs:
|
||||
|
||||
| Family | Meaning and required pairing |
|
||||
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `inverse` | A surface with reversed polarity; pair `--background-inverse` with `--foreground-on-inverse`. |
|
||||
| `accent` | Interactive emphasis; pair a strong accent background with `--foreground-on-accent`. |
|
||||
| `text-selection` | Strong text selection shared by native fields and code editors; pair `--background-text-selection` with `--foreground-on-text-selection`. |
|
||||
| `accent-secondary` | Secondary interactive emphasis; use the foreground on surfaces and pair the strong background with `--foreground-on-accent-secondary`. |
|
||||
| `positive` | Successful outcomes; pair strong or subtle backgrounds with their registered foreground. |
|
||||
| `negative` | Errors and destructive actions; pair strong or subtle backgrounds with their registered foreground. |
|
||||
| `warning` | Caution; pair the subtle background with the warning foreground and border. |
|
||||
| `informative` | Neutral information; pair the subtle background with the informative foreground and border. |
|
||||
| `interaction` | Translucent hover and pressed feedback composed over regular surfaces. |
|
||||
| `on-inverse` | Translucent hover and pressed feedback composed over inverse surfaces. |
|
||||
| Family | Meaning and required pairing |
|
||||
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `floating` | Dialogs, raised menus and popovers, then nested menus. Each level gets darker in light mode and lighter in dark mode. Borders and shadows separate them from their surroundings. Shared intent foregrounds work on every level. |
|
||||
| `inverse` | A surface with reversed polarity; pair `--background-inverse` with `--foreground-on-inverse`. |
|
||||
| `accent` | Interactive emphasis; pair a strong accent background with `--foreground-on-accent`. |
|
||||
| `text-selection` | Strong text selection shared by native fields and code editors; pair `--background-text-selection` with `--foreground-on-text-selection`. |
|
||||
| `accent-secondary` | Secondary interactive emphasis; use the foreground on surfaces and pair the strong background with `--foreground-on-accent-secondary`. |
|
||||
| `positive` | Successful outcomes; pair strong or subtle backgrounds with their registered foreground. |
|
||||
| `negative` | Errors and destructive actions; pair strong or subtle backgrounds with their registered foreground. |
|
||||
| `warning` | Caution; pair the subtle background with the warning foreground and border. |
|
||||
| `informative` | Neutral information; pair the subtle background with the informative foreground and border. |
|
||||
| `interaction` | Translucent hover and pressed feedback composed over regular surfaces. |
|
||||
| `on-inverse` | Translucent hover and pressed feedback composed over inverse surfaces. |
|
||||
|
||||
`--overlay-scrim` always derives from a dark version of the neutral theme
|
||||
color, so it dims content in both schemes rather than following foreground
|
||||
@@ -176,24 +179,19 @@ derive a local composition from them instead of being added to the brand API.
|
||||
|
||||
## Validation and type generation
|
||||
|
||||
Type generation parses CSS structurally and rejects:
|
||||
|
||||
- Empty color layers or mismatched light and dark scheme bounds.
|
||||
- Missing variable references.
|
||||
- References across forbidden architectural layers.
|
||||
- Unused theme parameters, scheme bounds, or derived colors.
|
||||
- Standalone semantic color literals.
|
||||
- Circular color references.
|
||||
- Semantic names outside the Craft grammar.
|
||||
- Color variables declared outside the owned root selectors.
|
||||
Type generation parses CSS structurally. It rejects color variables outside the
|
||||
owned root selectors, nested color declarations, duplicate selectors or
|
||||
declarations, missing variable references, and circular references in either
|
||||
scheme. It does not enforce authoring choices such as which layers may reference
|
||||
each other or whether every private variable is used.
|
||||
|
||||
TypeScript rejects unknown semantic names and unbranded private names passed to
|
||||
`cssVar()`.
|
||||
|
||||
Chromium browser tests load the real stylesheet, freeze every default semantic
|
||||
color in both schemes, and verify the default foreground/background contracts.
|
||||
They also protect the neutral hierarchy, stable chromatic fills, on-color
|
||||
content, and interaction overlays.
|
||||
Chromium browser tests load the real stylesheet and verify the default
|
||||
foreground/background contracts. They also check that all nine theme controls
|
||||
affect their intended outputs in both schemes, plus the neutral hierarchy,
|
||||
stable chromatic fills, on-color content, and interaction overlays.
|
||||
|
||||
The generator emits `ThemeVariableName` for public theme inputs and
|
||||
`SemanticColorName` for semantic colors in
|
||||
|
||||
+3
@@ -14,6 +14,9 @@ export type ThemeVariableName =
|
||||
export type SemanticColorName =
|
||||
| "--background-primary"
|
||||
| "--background-secondary"
|
||||
| "--background-floating"
|
||||
| "--background-floating-raised"
|
||||
| "--background-floating-nested"
|
||||
| "--background-disabled"
|
||||
| "--background-inverse"
|
||||
| "--background-accent"
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import "./colors.css";
|
||||
import type { SemanticColorName } from "./__generated__/css-variable-names";
|
||||
import type {
|
||||
SemanticColorName,
|
||||
ThemeVariableName,
|
||||
} from "./__generated__/css-variable-names";
|
||||
import { getColorContrast } from "./color-contrast";
|
||||
import type { ColorMode } from "./color-source-utils";
|
||||
|
||||
const readColor = (name: string) => {
|
||||
const sample = document.createElement("span");
|
||||
@@ -24,100 +26,6 @@ const readColor = (name: string) => {
|
||||
return color;
|
||||
};
|
||||
|
||||
const expectedDefaultColors = {
|
||||
light: {
|
||||
"--background-primary": "#feffff",
|
||||
"--background-secondary": "#e8eaeb",
|
||||
"--background-disabled": "#f7f8f9",
|
||||
"--background-inverse": "#11181c",
|
||||
"--background-accent": "#096cff",
|
||||
"--background-text-selection": "#096cff",
|
||||
"--background-accent-secondary": "#ab38d4",
|
||||
"--background-positive": "#008849",
|
||||
"--background-positive-subtle": "#e4f1e9",
|
||||
"--background-negative": "#dc2929",
|
||||
"--background-negative-subtle": "#ffe9e6",
|
||||
"--background-warning-subtle": "#f8edad",
|
||||
"--background-informative-subtle": "#e3effd",
|
||||
"--foreground-primary": "#11181c",
|
||||
"--foreground-secondary": "#595f63",
|
||||
"--foreground-disabled": "#898d90",
|
||||
"--foreground-on-inverse": "#feffff",
|
||||
"--foreground-on-accent": "#feffff",
|
||||
"--foreground-on-accent-secondary": "#feffff",
|
||||
"--foreground-on-positive": "#feffff",
|
||||
"--foreground-on-negative": "#feffff",
|
||||
"--foreground-on-text-selection": "#feffff",
|
||||
"--foreground-accent": "#096cff",
|
||||
"--foreground-accent-secondary": "#ab38d4",
|
||||
"--foreground-positive": "#0b7b45",
|
||||
"--foreground-negative": "#c52a28",
|
||||
"--foreground-warning": "#6f6100",
|
||||
"--foreground-informative": "#0a6bc7",
|
||||
"--border-default": "#e5e6e7",
|
||||
"--border-focus": "#297aff",
|
||||
"--border-negative": "#c52a28",
|
||||
"--border-warning": "#f5d90a",
|
||||
"--border-informative": "#bcd7f8",
|
||||
"--overlay-interaction-hover": "#00000010",
|
||||
"--overlay-interaction-pressed": "#0000001c",
|
||||
"--overlay-on-inverse-hover": "#ffffff10",
|
||||
"--overlay-on-inverse-pressed": "#ffffff1c",
|
||||
"--overlay-scrim": "#11171ba8",
|
||||
},
|
||||
dark: {
|
||||
"--background-primary": "#151617",
|
||||
"--background-secondary": "#222425",
|
||||
"--background-disabled": "#191b1b",
|
||||
"--background-inverse": "#e6e8e9",
|
||||
"--background-accent": "#096cff",
|
||||
"--background-text-selection": "#439cff",
|
||||
"--background-accent-secondary": "#ab38d4",
|
||||
"--background-positive": "#008849",
|
||||
"--background-positive-subtle": "#18221d",
|
||||
"--background-negative": "#dc2929",
|
||||
"--background-negative-subtle": "#2b1c1b",
|
||||
"--background-warning-subtle": "#2d2c1f",
|
||||
"--background-informative-subtle": "#1a2839",
|
||||
"--foreground-primary": "#e6e8e9",
|
||||
"--foreground-secondary": "#959798",
|
||||
"--foreground-disabled": "#6a6c6d",
|
||||
"--foreground-on-inverse": "#151617",
|
||||
"--foreground-on-accent": "#fdffff",
|
||||
"--foreground-on-accent-secondary": "#fdffff",
|
||||
"--foreground-on-positive": "#fdffff",
|
||||
"--foreground-on-negative": "#fdffff",
|
||||
"--foreground-on-text-selection": "#151617",
|
||||
"--foreground-accent": "#a0c1f6",
|
||||
"--foreground-accent-secondary": "#da6bff",
|
||||
"--foreground-positive": "#abcab5",
|
||||
"--foreground-negative": "#ff594f",
|
||||
"--foreground-warning": "#c4c1a5",
|
||||
"--foreground-informative": "#a9c6e8",
|
||||
"--border-default": "#252627",
|
||||
"--border-focus": "#1a6df2",
|
||||
"--border-negative": "#ff594f",
|
||||
"--border-warning": "#f5d90a",
|
||||
"--border-informative": "#1b314c",
|
||||
"--overlay-interaction-hover": "#ffffff10",
|
||||
"--overlay-interaction-pressed": "#ffffff1c",
|
||||
"--overlay-on-inverse-hover": "#00000010",
|
||||
"--overlay-on-inverse-pressed": "#0000001c",
|
||||
"--overlay-scrim": "#11171ba8",
|
||||
},
|
||||
} as const satisfies Record<ColorMode, Record<SemanticColorName, string>>;
|
||||
|
||||
const parseHex = (hex: string) => {
|
||||
const channels = hex.slice(1).match(/.{2}/g);
|
||||
if (channels === null) {
|
||||
throw new Error(`Invalid expected color: ${hex}`);
|
||||
}
|
||||
if (channels.length === 3) {
|
||||
channels.push("ff");
|
||||
}
|
||||
return channels.map((channel) => Number.parseInt(channel, 16));
|
||||
};
|
||||
|
||||
const getRelativeLuminance = (color: Uint8ClampedArray) => {
|
||||
const channels = Array.from(color.slice(0, 3), (channel) => {
|
||||
const value = channel / 255;
|
||||
@@ -139,37 +47,6 @@ const getContrastRatio = (
|
||||
};
|
||||
|
||||
describe("Craft color contrast", () => {
|
||||
test("default semantic colors stay unchanged", () => {
|
||||
const root = document.documentElement;
|
||||
const previousMode = root.getAttribute("data-color-scheme");
|
||||
|
||||
try {
|
||||
for (const mode of ["light", "dark"] as const) {
|
||||
root.dataset.colorScheme = mode;
|
||||
for (const [name, expectedHex] of Object.entries(
|
||||
expectedDefaultColors[mode]
|
||||
)) {
|
||||
const actual = Array.from(readColor(name));
|
||||
const expected = parseHex(expectedHex);
|
||||
for (const [index, expectedChannel] of expected.entries()) {
|
||||
expect
|
||||
.soft(
|
||||
Math.abs(actual[index] - expectedChannel),
|
||||
`${mode} ${name} channel ${index}: ${actual.join(", ")} versus ${expected.join(", ")}`
|
||||
)
|
||||
.toBeLessThanOrEqual(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (previousMode === null) {
|
||||
root.removeAttribute("data-color-scheme");
|
||||
} else {
|
||||
root.setAttribute("data-color-scheme", previousMode);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("default secondary colors preserve a clear visual hierarchy", () => {
|
||||
const root = document.documentElement;
|
||||
const previousMode = root.getAttribute("data-color-scheme");
|
||||
@@ -179,6 +56,9 @@ describe("Craft color contrast", () => {
|
||||
root.dataset.colorScheme = mode;
|
||||
const background = readColor("--background-primary");
|
||||
const surface = readColor("--background-secondary");
|
||||
const floating = readColor("--background-floating");
|
||||
const raised = readColor("--background-floating-raised");
|
||||
const nested = readColor("--background-floating-nested");
|
||||
const primaryForeground = readColor("--foreground-primary");
|
||||
const secondaryForeground = readColor("--foreground-secondary");
|
||||
const primaryContrast = getContrastRatio(primaryForeground, background);
|
||||
@@ -191,6 +71,28 @@ describe("Craft color contrast", () => {
|
||||
getContrastRatio(surface, background),
|
||||
`${mode} secondary surface`
|
||||
).toBeGreaterThanOrEqual(1.15);
|
||||
const floatingContrast = getContrastRatio(floating, background);
|
||||
expect(
|
||||
floatingContrast,
|
||||
`${mode} floating surface`
|
||||
).toBeGreaterThanOrEqual(mode === "light" ? 1.01 : 1.05);
|
||||
expect(
|
||||
floatingContrast,
|
||||
`${mode} floating surface`
|
||||
).toBeLessThanOrEqual(mode === "light" ? 1.05 : 1.18);
|
||||
expect(
|
||||
getContrastRatio(nested, background),
|
||||
`${mode} nested surface`
|
||||
).toBeLessThanOrEqual(mode === "light" ? 1.1 : 1.55);
|
||||
if (mode === "light") {
|
||||
expect(floating[0]).toBeLessThan(background[0]);
|
||||
expect(raised[0]).toBeLessThan(floating[0]);
|
||||
expect(nested[0]).toBeLessThan(raised[0]);
|
||||
} else {
|
||||
expect(floating[0]).toBeGreaterThan(background[0]);
|
||||
expect(raised[0]).toBeGreaterThan(floating[0]);
|
||||
expect(nested[0]).toBeGreaterThan(raised[0]);
|
||||
}
|
||||
expect(
|
||||
secondaryContrast,
|
||||
`${mode} secondary foreground`
|
||||
@@ -238,15 +140,24 @@ describe("Craft color contrast", () => {
|
||||
root.dataset.colorScheme = mode;
|
||||
const primary = readColor("--background-primary");
|
||||
const disabledBackground = readColor("--background-disabled");
|
||||
const raisedBackground = readColor("--background-floating-raised");
|
||||
const disabled = readColor("--foreground-disabled");
|
||||
const secondary = readColor("--foreground-secondary");
|
||||
|
||||
for (const background of [primary, disabledBackground]) {
|
||||
for (const background of [
|
||||
primary,
|
||||
disabledBackground,
|
||||
raisedBackground,
|
||||
]) {
|
||||
expect(
|
||||
getContrastRatio(disabled, background),
|
||||
`${mode} disabled content`
|
||||
).toBeGreaterThanOrEqual(3);
|
||||
}
|
||||
expect(
|
||||
getContrastRatio(disabled, raisedBackground),
|
||||
`${mode} disabled content on raised surfaces`
|
||||
).toBeLessThanOrEqual(3.4);
|
||||
expect(getContrastRatio(disabled, primary), mode).toBeLessThan(
|
||||
getContrastRatio(secondary, primary)
|
||||
);
|
||||
@@ -298,56 +209,137 @@ describe("Craft color contrast", () => {
|
||||
});
|
||||
}
|
||||
|
||||
test("theme color hue and chroma control derived semantic colors", () => {
|
||||
test("restores the scheme and removes temporary DOM when color evaluation fails", () => {
|
||||
const root = document.documentElement;
|
||||
const sample = document.createElement("span");
|
||||
sample.style.color = "var(--background-accent)";
|
||||
document.body.append(sample);
|
||||
|
||||
const accentBefore = getComputedStyle(sample).color;
|
||||
root.style.setProperty("--theme-color-accent", "oklch(50% 0.18 300)");
|
||||
const accentAfter = getComputedStyle(sample).color;
|
||||
|
||||
sample.style.color = "var(--background-primary)";
|
||||
const neutralBefore = getComputedStyle(sample).color;
|
||||
root.style.setProperty("--theme-color-neutral", "oklch(50% 0.02 300)");
|
||||
const neutralAfter = getComputedStyle(sample).color;
|
||||
|
||||
expect.soft(accentAfter).not.toBe(accentBefore);
|
||||
expect.soft(neutralAfter).not.toBe(neutralBefore);
|
||||
|
||||
root.style.removeProperty("--theme-color-accent");
|
||||
root.style.removeProperty("--theme-color-neutral");
|
||||
sample.remove();
|
||||
});
|
||||
|
||||
test("theme contrast parameters affect their primary outputs", () => {
|
||||
const root = document.documentElement;
|
||||
const relationships = {
|
||||
content: "--foreground-primary",
|
||||
surface: "--background-secondary",
|
||||
border: "--border-default",
|
||||
} as const;
|
||||
const previousMode = root.getAttribute("data-color-scheme");
|
||||
const previousBackground = root.style.getPropertyValue(
|
||||
"--background-primary"
|
||||
);
|
||||
const previousBodyNodes = Array.from(document.body.childNodes);
|
||||
root.style.setProperty("--background-primary", "transparent");
|
||||
|
||||
try {
|
||||
for (const [relationship, semanticColor] of Object.entries(
|
||||
relationships
|
||||
)) {
|
||||
const parameter = `--theme-contrast-${relationship}`;
|
||||
root.style.setProperty(parameter, "0%");
|
||||
const soft = Array.from(readColor(semanticColor));
|
||||
root.style.setProperty(parameter, "100%");
|
||||
const strong = Array.from(readColor(semanticColor));
|
||||
|
||||
expect(strong, relationship).not.toEqual(soft);
|
||||
}
|
||||
expect(() => getColorContrast("dark")).toThrow();
|
||||
expect(root.getAttribute("data-color-scheme")).toBe(previousMode);
|
||||
expect(Array.from(document.body.childNodes)).toEqual(previousBodyNodes);
|
||||
} finally {
|
||||
for (const relationship of Object.keys(relationships)) {
|
||||
root.style.removeProperty(`--theme-contrast-${relationship}`);
|
||||
root.style.setProperty("--background-primary", previousBackground);
|
||||
}
|
||||
});
|
||||
|
||||
test("vivid theme preserves negative text and nested surface contrast", () => {
|
||||
const root = document.documentElement;
|
||||
const previousMode = root.getAttribute("data-color-scheme");
|
||||
const theme = {
|
||||
"--theme-color-neutral": "oklch(45% 0.02 300)",
|
||||
"--theme-color-negative": "oklch(60% 0.3 20)",
|
||||
"--theme-contrast-content": "100%",
|
||||
"--theme-contrast-surface": "100%",
|
||||
};
|
||||
|
||||
try {
|
||||
for (const [name, value] of Object.entries(theme)) {
|
||||
root.style.setProperty(name, value);
|
||||
}
|
||||
for (const mode of ["light", "dark"] as const) {
|
||||
root.dataset.colorScheme = mode;
|
||||
for (const result of getColorContrast(mode)) {
|
||||
if (result.foreground === "--foreground-negative") {
|
||||
expect(
|
||||
result.ratio,
|
||||
`${mode} on ${result.background}`
|
||||
).toBeGreaterThanOrEqual(result.minimum);
|
||||
}
|
||||
}
|
||||
}
|
||||
root.dataset.colorScheme = "dark";
|
||||
expect(Array.from(readColor("--background-floating-nested"))).not.toEqual(
|
||||
Array.from(readColor("--background-secondary"))
|
||||
);
|
||||
} finally {
|
||||
for (const name of Object.keys(theme)) {
|
||||
root.style.removeProperty(name);
|
||||
}
|
||||
if (previousMode === null) {
|
||||
root.removeAttribute("data-color-scheme");
|
||||
} else {
|
||||
root.setAttribute("data-color-scheme", previousMode);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"all theme controls affect their intended outputs in %s mode",
|
||||
(mode) => {
|
||||
const root = document.documentElement;
|
||||
const previousMode = root.getAttribute("data-color-scheme");
|
||||
const controls = {
|
||||
"--theme-color-neutral": {
|
||||
value: "oklch(50% 0.02 300)",
|
||||
output: "--foreground-primary",
|
||||
},
|
||||
"--theme-color-accent": {
|
||||
value: "oklch(50% 0.18 300)",
|
||||
output: "--background-accent",
|
||||
},
|
||||
"--theme-color-positive": {
|
||||
value: "oklch(50% 0.18 300)",
|
||||
output: "--background-positive",
|
||||
},
|
||||
"--theme-color-negative": {
|
||||
value: "oklch(50% 0.18 300)",
|
||||
output: "--background-negative",
|
||||
},
|
||||
"--theme-color-warning": {
|
||||
value: "oklch(50% 0.18 300)",
|
||||
output: "--foreground-warning",
|
||||
},
|
||||
"--theme-color-informative": {
|
||||
value: "oklch(50% 0.18 300)",
|
||||
output: "--foreground-informative",
|
||||
},
|
||||
"--theme-contrast-content": {
|
||||
value: "100%",
|
||||
output: "--foreground-primary",
|
||||
},
|
||||
"--theme-contrast-surface": {
|
||||
value: "100%",
|
||||
output: "--background-secondary",
|
||||
},
|
||||
"--theme-contrast-border": {
|
||||
value: "100%",
|
||||
output: "--border-default",
|
||||
},
|
||||
} satisfies Record<
|
||||
ThemeVariableName,
|
||||
{ value: string; output: SemanticColorName }
|
||||
>;
|
||||
|
||||
try {
|
||||
root.dataset.colorScheme = mode;
|
||||
for (const [parameter, { value, output }] of Object.entries(controls)) {
|
||||
const previousValue = root.style.getPropertyValue(parameter);
|
||||
try {
|
||||
const before = Array.from(readColor(output));
|
||||
root.style.setProperty(parameter, value);
|
||||
expect(
|
||||
Array.from(readColor(output)),
|
||||
`${mode} ${parameter}`
|
||||
).not.toEqual(before);
|
||||
} finally {
|
||||
root.style.setProperty(parameter, previousValue);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (previousMode === null) {
|
||||
root.removeAttribute("data-color-scheme");
|
||||
} else {
|
||||
root.setAttribute("data-color-scheme", previousMode);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
test("intent variants retain their semantic color family", () => {
|
||||
const root = document.documentElement;
|
||||
const previousMode = root.getAttribute("data-color-scheme");
|
||||
|
||||
@@ -10,16 +10,29 @@ export type ColorContrastResult = {
|
||||
};
|
||||
|
||||
const contrastContracts = [
|
||||
["--foreground-primary", "--background-primary", 4.5],
|
||||
["--foreground-secondary", "--background-primary", 4.5],
|
||||
...(
|
||||
[
|
||||
"--foreground-primary",
|
||||
"--foreground-secondary",
|
||||
"--foreground-accent",
|
||||
"--foreground-accent-secondary",
|
||||
"--foreground-positive",
|
||||
"--foreground-negative",
|
||||
"--foreground-warning",
|
||||
"--foreground-informative",
|
||||
] as const
|
||||
).flatMap((foreground) =>
|
||||
(
|
||||
[
|
||||
"--background-primary",
|
||||
"--background-floating",
|
||||
"--background-floating-raised",
|
||||
"--background-floating-nested",
|
||||
] as const
|
||||
).map((background) => [foreground, background, 4.5] as const)
|
||||
),
|
||||
["--foreground-primary", "--background-secondary", 4.5],
|
||||
["--foreground-secondary", "--background-secondary", 4.5],
|
||||
["--foreground-accent", "--background-primary", 4.5],
|
||||
["--foreground-accent-secondary", "--background-primary", 4.5],
|
||||
["--foreground-positive", "--background-primary", 4.5],
|
||||
["--foreground-negative", "--background-primary", 4.5],
|
||||
["--foreground-warning", "--background-primary", 4.5],
|
||||
["--foreground-informative", "--background-primary", 4.5],
|
||||
["--foreground-on-text-selection", "--background-text-selection", 4.5],
|
||||
// Text selection appears on both regular surfaces and secondary editor fields.
|
||||
["--background-text-selection", "--background-primary", 3],
|
||||
@@ -37,19 +50,12 @@ const contrastContracts = [
|
||||
["--foreground-secondary", "--background-informative-subtle", 4.5],
|
||||
["--foreground-negative", "--background-informative-subtle", 4.5],
|
||||
["--border-focus", "--background-secondary", 3],
|
||||
] as const satisfies readonly (readonly [
|
||||
] satisfies readonly (readonly [
|
||||
SemanticColorName,
|
||||
SemanticColorName,
|
||||
number,
|
||||
])[];
|
||||
|
||||
const contrastColorNames = new Set<SemanticColorName>(
|
||||
contrastContracts.flatMap(([foreground, background]) => [
|
||||
foreground,
|
||||
background,
|
||||
])
|
||||
);
|
||||
|
||||
export const colorContrastContractCount = contrastContracts.length;
|
||||
|
||||
const toLinearChannel = (channel: number) => {
|
||||
@@ -62,51 +68,22 @@ const getLuminance = (color: Uint8ClampedArray) =>
|
||||
0.7152 * toLinearChannel(color[1]) +
|
||||
0.0722 * toLinearChannel(color[2]);
|
||||
|
||||
const createColorReader = () => {
|
||||
const samples = new Map<SemanticColorName, HTMLElement>();
|
||||
const container = document.createElement("div");
|
||||
container.hidden = true;
|
||||
for (const name of contrastColorNames) {
|
||||
const sample = document.createElement("span");
|
||||
sample.style.color = cssVar(name);
|
||||
container.append(sample);
|
||||
samples.set(name, sample);
|
||||
}
|
||||
document.body.append(container);
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true });
|
||||
if (context === null) {
|
||||
container.remove();
|
||||
throw new Error("Canvas color evaluation is unavailable");
|
||||
}
|
||||
|
||||
const read = (name: SemanticColorName) => {
|
||||
const sample = samples.get(name);
|
||||
if (sample === undefined) {
|
||||
throw new Error(`Unknown contrast color: ${name}`);
|
||||
}
|
||||
context.clearRect(0, 0, 1, 1);
|
||||
context.fillStyle = getComputedStyle(sample).color;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
const color = context.getImageData(0, 0, 1, 1).data;
|
||||
if (color[3] !== 255) {
|
||||
throw new Error(`${name} must resolve to an opaque color`);
|
||||
}
|
||||
return color;
|
||||
};
|
||||
|
||||
return { read, dispose: () => container.remove() };
|
||||
};
|
||||
|
||||
const createColorContrastReader = () => {
|
||||
export const getColorContrast = (mode: ColorMode): ColorContrastResult[] => {
|
||||
const root = document.documentElement;
|
||||
const previousMode = root.getAttribute("data-color-scheme");
|
||||
const reader = createColorReader();
|
||||
const sample = document.createElement("span");
|
||||
sample.hidden = true;
|
||||
document.body.append(sample);
|
||||
|
||||
try {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true });
|
||||
if (context === null) {
|
||||
throw new Error("Canvas color evaluation is unavailable");
|
||||
}
|
||||
|
||||
const read = (mode: ColorMode): ColorContrastResult[] => {
|
||||
root.setAttribute("data-color-scheme", mode);
|
||||
const luminances = new Map<SemanticColorName, number>();
|
||||
const readLuminance = (name: SemanticColorName) => {
|
||||
@@ -114,7 +91,15 @@ const createColorContrastReader = () => {
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
const value = getLuminance(reader.read(name));
|
||||
sample.style.color = cssVar(name);
|
||||
context.clearRect(0, 0, 1, 1);
|
||||
context.fillStyle = getComputedStyle(sample).color;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
const color = context.getImageData(0, 0, 1, 1).data;
|
||||
if (color[3] !== 255) {
|
||||
throw new Error(`${name} must resolve to an opaque color`);
|
||||
}
|
||||
const value = getLuminance(color);
|
||||
luminances.set(name, value);
|
||||
return value;
|
||||
};
|
||||
@@ -131,27 +116,12 @@ const createColorContrastReader = () => {
|
||||
ratio: (lighter + 0.05) / (darker + 0.05),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const dispose = () => {
|
||||
reader.dispose();
|
||||
} finally {
|
||||
sample.remove();
|
||||
if (previousMode === null) {
|
||||
root.removeAttribute("data-color-scheme");
|
||||
} else {
|
||||
root.setAttribute("data-color-scheme", previousMode);
|
||||
}
|
||||
};
|
||||
|
||||
return { read, dispose };
|
||||
};
|
||||
|
||||
export const getColorContrast = (mode: ColorMode): ColorContrastResult[] => {
|
||||
const reader = createColorContrastReader();
|
||||
try {
|
||||
return reader.read(mode);
|
||||
} finally {
|
||||
reader.dispose();
|
||||
}
|
||||
};
|
||||
|
||||
export const __testing__ = { createColorContrastReader };
|
||||
@@ -89,7 +89,6 @@ describe("Craft color CSS source", () => {
|
||||
expect(Object.keys(colors.scheme.light)).toEqual(
|
||||
Object.keys(colors.scheme.dark)
|
||||
);
|
||||
expect(Object.keys(colors.derived)).toHaveLength(31);
|
||||
expect(colors.derived).toHaveProperty("focus");
|
||||
expect(Object.keys(colors.semantic)).toEqual([
|
||||
"background",
|
||||
@@ -102,7 +101,12 @@ describe("Craft color CSS source", () => {
|
||||
(count, category) => count + Object.keys(category).length,
|
||||
0
|
||||
)
|
||||
).toBe(38);
|
||||
).toBe(41);
|
||||
expect(colors.semantic.background).toHaveProperty("floating");
|
||||
expect(colors.semantic.background).toHaveProperty("floating-raised");
|
||||
expect(colors.semantic.background).toHaveProperty("floating-nested");
|
||||
expect(colors.semantic.foreground).toHaveProperty("accent");
|
||||
expect(colors.semantic.foreground).not.toHaveProperty("accent-floating");
|
||||
expect(colors.semantic.background).toHaveProperty("text-selection");
|
||||
expect(colors.semantic.foreground).toHaveProperty("on-text-selection");
|
||||
expect(colors.semantic.background).toHaveProperty("positive-subtle");
|
||||
@@ -117,9 +121,9 @@ describe("Craft color CSS source", () => {
|
||||
const extendedSource = addRootDeclarations(source, {
|
||||
"--theme-color-custom": "oklch(50% 0.1 300)",
|
||||
"--color-custom":
|
||||
"oklch(from var(--theme-color-custom) var(--scheme-chromatic-luminance-max) c h)",
|
||||
"oklch(from var(--theme-color-custom) clamp(0.2, l, 0.48) c h)",
|
||||
"--foreground-custom":
|
||||
"color-mix(in oklab, var(--color-custom) 86%, var(--color-foreground))",
|
||||
"oklch(from var(--color-custom) var(--scheme-foreground-soft-lightness) c h)",
|
||||
});
|
||||
const colors = parseColorSource(extendedSource);
|
||||
|
||||
@@ -153,16 +157,18 @@ describe("Craft color CSS source", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects standalone semantic color literals", () => {
|
||||
const invalidSource = replaceDeclaration({
|
||||
test("accepts standalone semantic color literals", () => {
|
||||
const customSource = replaceDeclaration({
|
||||
css: source,
|
||||
property: "--background-primary",
|
||||
value: "oklch(50% 0.2 250)",
|
||||
});
|
||||
|
||||
expect(() => parseColorSource(invalidSource)).toThrow(
|
||||
"--background-primary must derive from another color variable"
|
||||
);
|
||||
expect(
|
||||
getCssVariableReferences(
|
||||
parseColorSource(customSource).semantic.background.primary
|
||||
)
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("rejects circular semantic references", () => {
|
||||
@@ -197,4 +203,26 @@ describe("Craft color CSS source", () => {
|
||||
`--scheme-background-lightness references missing variable --scheme-missing`
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects duplicate root selectors and declarations", () => {
|
||||
expect(() => parseColorSource(`${source}\n:root {}`)).toThrow(
|
||||
"Duplicate color selector: :root"
|
||||
);
|
||||
const duplicate = addRootDeclarations(source, {
|
||||
"--color-background": "var(--theme-color-neutral)",
|
||||
});
|
||||
expect(() => parseColorSource(duplicate)).toThrow(
|
||||
"Duplicate color declaration: --color-background"
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects cycles introduced by a dark scheme override", () => {
|
||||
const cycle = replaceDeclaration({
|
||||
css: source,
|
||||
selector: ':root[data-color-scheme="dark"]',
|
||||
property: "--scheme-background-lightness",
|
||||
value: "var(--color-background)",
|
||||
});
|
||||
expect(() => parseColorSource(cycle)).toThrow("Circular color reference");
|
||||
});
|
||||
});
|
||||
@@ -1,167 +1,24 @@
|
||||
import * as csstree from "css-tree";
|
||||
|
||||
const colorCategories = [
|
||||
"background",
|
||||
"foreground",
|
||||
"border",
|
||||
"overlay",
|
||||
] as const;
|
||||
|
||||
const rootSelector = ":root";
|
||||
const darkRootSelector = ':root[data-color-scheme="dark"]';
|
||||
const colorVariableSelectors = new Set([rootSelector, darkRootSelector]);
|
||||
|
||||
type ColorCategory = (typeof colorCategories)[number];
|
||||
|
||||
export type ColorSource = {
|
||||
theme: {
|
||||
color: Record<string, string>;
|
||||
contrast: Record<string, string>;
|
||||
};
|
||||
scheme: {
|
||||
light: Record<string, string>;
|
||||
dark: Record<string, string>;
|
||||
};
|
||||
derived: Record<string, string>;
|
||||
semantic: Record<ColorCategory, Record<string, string>>;
|
||||
};
|
||||
const ownedSelectors = new Set([rootSelector, darkRootSelector]);
|
||||
|
||||
export type ColorMode = "light" | "dark";
|
||||
|
||||
const generateValue = (value: csstree.CssNode) =>
|
||||
csstree.generate(value).trim();
|
||||
|
||||
const getDeclarations = (rule: csstree.Rule) => {
|
||||
const declarations: Record<string, string> = {};
|
||||
rule.block.children.forEach((node) => {
|
||||
if (
|
||||
node.type !== "Declaration" ||
|
||||
node.property.startsWith("--") === false
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (node.property in declarations) {
|
||||
throw new Error(`Duplicate color declaration: ${node.property}`);
|
||||
}
|
||||
declarations[node.property] = generateValue(node.value);
|
||||
});
|
||||
return declarations;
|
||||
};
|
||||
|
||||
const selectDeclarations = (
|
||||
stylesheet: csstree.StyleSheet,
|
||||
selector: string
|
||||
) => {
|
||||
let declarations: Record<string, string> | undefined;
|
||||
stylesheet.children.forEach((node) => {
|
||||
if (node.type !== "Rule" || csstree.generate(node.prelude) !== selector) {
|
||||
return;
|
||||
}
|
||||
if (declarations !== undefined) {
|
||||
throw new Error(`Duplicate color selector: ${selector}`);
|
||||
}
|
||||
declarations = getDeclarations(node);
|
||||
});
|
||||
if (declarations === undefined) {
|
||||
throw new Error(`Missing color selector: ${selector}`);
|
||||
}
|
||||
return declarations;
|
||||
};
|
||||
|
||||
const validateDeclarationSelectors = (stylesheet: csstree.StyleSheet) => {
|
||||
const topLevelRules = new Set<csstree.Rule>();
|
||||
stylesheet.children.forEach((node) => {
|
||||
if (node.type === "Rule") {
|
||||
topLevelRules.add(node);
|
||||
}
|
||||
});
|
||||
|
||||
csstree.walk(stylesheet, {
|
||||
visit: "Rule",
|
||||
enter(node) {
|
||||
if (node.type !== "Rule") {
|
||||
return;
|
||||
}
|
||||
let hasColorVariables = false;
|
||||
node.block.children.forEach((child) => {
|
||||
if (child.type === "Declaration" && child.property.startsWith("--")) {
|
||||
hasColorVariables = true;
|
||||
}
|
||||
});
|
||||
if (hasColorVariables === false) {
|
||||
return;
|
||||
}
|
||||
if (topLevelRules.has(node) === false) {
|
||||
throw new Error(
|
||||
"Color variables may be declared only in top-level root selectors"
|
||||
);
|
||||
}
|
||||
const selector = csstree.generate(node.prelude);
|
||||
if (colorVariableSelectors.has(selector) === false) {
|
||||
throw new Error(`Color variables may not be declared in ${selector}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const getGroup = (declarations: Record<string, string>, prefix: string) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(declarations)
|
||||
.filter(([name]) => name.startsWith(prefix))
|
||||
.map(([name, value]) => [name.slice(prefix.length), value])
|
||||
);
|
||||
|
||||
const prefixDeclarations = (
|
||||
prefix: string,
|
||||
declarations: Record<string, string>
|
||||
) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(declarations).map(([name, value]) => [
|
||||
`${prefix}${name}`,
|
||||
value,
|
||||
])
|
||||
);
|
||||
|
||||
const expectValues = (label: string, values: Record<string, string>) => {
|
||||
if (Object.keys(values).length === 0) {
|
||||
throw new Error(`${label} must define at least one value`);
|
||||
}
|
||||
};
|
||||
|
||||
const expectSameNames = (
|
||||
label: string,
|
||||
first: Record<string, string>,
|
||||
second: Record<string, string>
|
||||
) => {
|
||||
const firstNames = Object.keys(first).sort();
|
||||
const secondNames = Object.keys(second).sort();
|
||||
if (
|
||||
firstNames.length !== secondNames.length ||
|
||||
firstNames.some((name, index) => name !== secondNames[index])
|
||||
) {
|
||||
throw new Error(
|
||||
`${label} must define the same values; received ${firstNames.join(", ")} and ${secondNames.join(", ")}`
|
||||
);
|
||||
}
|
||||
};
|
||||
type Declaration = { value: string; references: string[] };
|
||||
type Declarations = Map<string, Declaration>;
|
||||
|
||||
export const getCssVariableReferences = (value: string) => {
|
||||
const references: string[] = [];
|
||||
const ast = csstree.parse(value, { context: "value" });
|
||||
csstree.walk(ast, {
|
||||
csstree.walk(csstree.parse(value, { context: "value" }), {
|
||||
visit: "Function",
|
||||
enter(node) {
|
||||
if (node.type !== "Function") {
|
||||
return;
|
||||
}
|
||||
if (node.name !== "var") {
|
||||
if (node.type !== "Function" || node.name !== "var") {
|
||||
return;
|
||||
}
|
||||
const first = node.children.first;
|
||||
if (
|
||||
first?.type !== "Identifier" ||
|
||||
first.name.startsWith("--") === false
|
||||
) {
|
||||
if (first?.type !== "Identifier" || !first.name.startsWith("--")) {
|
||||
throw new Error(`Invalid color variable reference in: ${value}`);
|
||||
}
|
||||
references.push(first.name);
|
||||
@@ -170,39 +27,17 @@ export const getCssVariableReferences = (value: string) => {
|
||||
return references;
|
||||
};
|
||||
|
||||
const validateReferences = ({
|
||||
declarations,
|
||||
names,
|
||||
allowedPrefixes,
|
||||
requireReference,
|
||||
}: {
|
||||
declarations: Record<string, string>;
|
||||
names: ReadonlySet<string>;
|
||||
allowedPrefixes: readonly string[];
|
||||
requireReference?: boolean;
|
||||
}) => {
|
||||
for (const [name, value] of Object.entries(declarations)) {
|
||||
const references = getCssVariableReferences(value);
|
||||
if (requireReference && references.length === 0) {
|
||||
throw new Error(`${name} must derive from another color variable`);
|
||||
}
|
||||
const validateGraph = (declarations: Declarations) => {
|
||||
for (const [name, { references }] of declarations) {
|
||||
for (const reference of references) {
|
||||
if (
|
||||
allowedPrefixes.some((prefix) => reference.startsWith(prefix)) === false
|
||||
) {
|
||||
throw new Error(`${name} cannot reference ${reference}`);
|
||||
}
|
||||
if (names.has(reference) === false) {
|
||||
if (!declarations.has(reference)) {
|
||||
throw new Error(`${name} references missing variable ${reference}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const validateCycles = (declarations: Record<string, string>) => {
|
||||
const visited = new Set<string>();
|
||||
const visiting: string[] = [];
|
||||
|
||||
const visit = (name: string) => {
|
||||
if (visited.has(name)) {
|
||||
return;
|
||||
@@ -214,171 +49,104 @@ const validateCycles = (declarations: Record<string, string>) => {
|
||||
);
|
||||
}
|
||||
visiting.push(name);
|
||||
for (const reference of getCssVariableReferences(declarations[name])) {
|
||||
if (reference in declarations) {
|
||||
visit(reference);
|
||||
}
|
||||
for (const reference of declarations.get(name)?.references ?? []) {
|
||||
visit(reference);
|
||||
}
|
||||
visiting.pop();
|
||||
visited.add(name);
|
||||
};
|
||||
|
||||
for (const name of Object.keys(declarations)) {
|
||||
for (const name of declarations.keys()) {
|
||||
visit(name);
|
||||
}
|
||||
};
|
||||
|
||||
const validateConsumed = ({
|
||||
label,
|
||||
declarations,
|
||||
consumers,
|
||||
}: {
|
||||
label: string;
|
||||
declarations: Record<string, string>;
|
||||
consumers: Record<string, string>;
|
||||
}) => {
|
||||
const consumed = new Set(
|
||||
Object.values(consumers).flatMap(getCssVariableReferences)
|
||||
const getGroup = (declarations: Declarations, prefix: string) =>
|
||||
Object.fromEntries(
|
||||
[...declarations]
|
||||
.filter(([name]) => name.startsWith(prefix))
|
||||
.map(([name, { value }]) => [name.slice(prefix.length), value])
|
||||
);
|
||||
const unused = Object.keys(declarations).filter(
|
||||
(name) => consumed.has(name) === false
|
||||
);
|
||||
if (unused.length > 0) {
|
||||
throw new Error(`Unused ${label}: ${unused.join(", ")}`);
|
||||
}
|
||||
};
|
||||
|
||||
const validateSemanticName = (name: string) => {
|
||||
if (/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) === false) {
|
||||
throw new Error(`Invalid Craft semantic color name: ${name}`);
|
||||
}
|
||||
};
|
||||
|
||||
export const parseColorSource = (css: string): ColorSource => {
|
||||
export const parseColorSource = (css: string) => {
|
||||
const stylesheet = csstree.parse(css);
|
||||
if (stylesheet.type !== "StyleSheet") {
|
||||
throw new Error("Color source must be a stylesheet");
|
||||
}
|
||||
validateDeclarationSelectors(stylesheet);
|
||||
const lightDeclarations = selectDeclarations(stylesheet, rootSelector);
|
||||
const darkDeclarations = selectDeclarations(stylesheet, darkRootSelector);
|
||||
|
||||
const themeColor = getGroup(lightDeclarations, "--theme-color-");
|
||||
const themeContrast = getGroup(lightDeclarations, "--theme-contrast-");
|
||||
const lightScheme = getGroup(lightDeclarations, "--scheme-");
|
||||
const darkScheme = getGroup(darkDeclarations, "--scheme-");
|
||||
const derived = getGroup(lightDeclarations, "--color-");
|
||||
const semantic = Object.fromEntries(
|
||||
colorCategories.map((category) => [
|
||||
category,
|
||||
getGroup(lightDeclarations, `--${category}-`),
|
||||
])
|
||||
) as ColorSource["semantic"];
|
||||
|
||||
const themeDeclarations = {
|
||||
...prefixDeclarations("--theme-color-", themeColor),
|
||||
...prefixDeclarations("--theme-contrast-", themeContrast),
|
||||
};
|
||||
const schemeDeclarations = prefixDeclarations("--scheme-", lightScheme);
|
||||
const darkSchemeDeclarations = prefixDeclarations("--scheme-", darkScheme);
|
||||
const derivedDeclarations = prefixDeclarations("--color-", derived);
|
||||
const semanticDeclarations = Object.assign(
|
||||
{},
|
||||
...Object.entries(semantic).map(([category, values]) =>
|
||||
prefixDeclarations(`--${category}-`, values)
|
||||
)
|
||||
);
|
||||
const allDeclarations = {
|
||||
...themeDeclarations,
|
||||
...schemeDeclarations,
|
||||
...derivedDeclarations,
|
||||
...semanticDeclarations,
|
||||
};
|
||||
|
||||
expectValues("Theme color parameters", themeColor);
|
||||
expectValues("Theme contrast parameters", themeContrast);
|
||||
expectValues("Light scheme bounds", lightScheme);
|
||||
expectValues("Dark scheme bounds", darkScheme);
|
||||
expectValues("Derived colors", derived);
|
||||
for (const [category, colors] of Object.entries(semantic)) {
|
||||
expectValues(`${category} semantic colors`, colors);
|
||||
}
|
||||
expectSameNames("Light and dark scheme bounds", lightScheme, darkScheme);
|
||||
|
||||
const names = new Set(Object.keys(allDeclarations));
|
||||
const uncategorized = Object.keys(lightDeclarations).filter(
|
||||
(name) => names.has(name) === false
|
||||
);
|
||||
if (uncategorized.length > 0) {
|
||||
throw new Error(
|
||||
`Uncategorized color variables: ${uncategorized.join(", ")}`
|
||||
);
|
||||
}
|
||||
const darkNonScheme = Object.keys(darkDeclarations).filter(
|
||||
(name) => name.startsWith("--scheme-") === false
|
||||
);
|
||||
if (darkNonScheme.length > 0) {
|
||||
throw new Error(
|
||||
`Dark mode may override only scheme bounds: ${darkNonScheme.join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
for (const declarations of [schemeDeclarations, darkSchemeDeclarations]) {
|
||||
validateReferences({
|
||||
declarations,
|
||||
names,
|
||||
allowedPrefixes: ["--theme-color-", "--theme-contrast-", "--scheme-"],
|
||||
});
|
||||
}
|
||||
|
||||
validateReferences({
|
||||
declarations: derivedDeclarations,
|
||||
names,
|
||||
allowedPrefixes: [
|
||||
"--theme-color-",
|
||||
"--theme-contrast-",
|
||||
"--scheme-",
|
||||
"--color-",
|
||||
],
|
||||
requireReference: true,
|
||||
const topLevelRules = new Set<csstree.Rule>();
|
||||
stylesheet.children.forEach((node) => {
|
||||
if (node.type === "Rule") {
|
||||
topLevelRules.add(node);
|
||||
}
|
||||
});
|
||||
|
||||
for (const name of Object.keys(semanticDeclarations)) {
|
||||
validateSemanticName(name.slice(2));
|
||||
const roots = new Map<string, Declarations>();
|
||||
csstree.walk(stylesheet, {
|
||||
visit: "Rule",
|
||||
enter(rule) {
|
||||
if (rule.type !== "Rule") {
|
||||
return;
|
||||
}
|
||||
const selector = csstree.generate(rule.prelude);
|
||||
const isTopLevel = topLevelRules.has(rule);
|
||||
const isOwned = ownedSelectors.has(selector);
|
||||
if (isTopLevel && isOwned && roots.has(selector)) {
|
||||
throw new Error(`Duplicate color selector: ${selector}`);
|
||||
}
|
||||
const declarations: Declarations = new Map();
|
||||
rule.block.children.forEach((node) => {
|
||||
if (node.type !== "Declaration" || !node.property.startsWith("--")) {
|
||||
return;
|
||||
}
|
||||
if (!isTopLevel) {
|
||||
throw new Error(
|
||||
"Color variables may be declared only in top-level root selectors"
|
||||
);
|
||||
}
|
||||
if (!isOwned) {
|
||||
throw new Error(`Color variables may not be declared in ${selector}`);
|
||||
}
|
||||
if (declarations.has(node.property)) {
|
||||
throw new Error(`Duplicate color declaration: ${node.property}`);
|
||||
}
|
||||
const value = csstree.generate(node.value).trim();
|
||||
declarations.set(node.property, {
|
||||
value,
|
||||
references: getCssVariableReferences(value),
|
||||
});
|
||||
});
|
||||
if (isTopLevel && isOwned) {
|
||||
roots.set(selector, declarations);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const light = roots.get(rootSelector);
|
||||
const dark = roots.get(darkRootSelector);
|
||||
if (light === undefined) {
|
||||
throw new Error(`Missing color selector: ${rootSelector}`);
|
||||
}
|
||||
validateReferences({
|
||||
declarations: semanticDeclarations,
|
||||
names,
|
||||
allowedPrefixes: [
|
||||
"--color-",
|
||||
"--background-",
|
||||
"--foreground-",
|
||||
"--border-",
|
||||
"--overlay-",
|
||||
],
|
||||
requireReference: true,
|
||||
});
|
||||
validateCycles(allDeclarations);
|
||||
validateCycles({ ...allDeclarations, ...darkSchemeDeclarations });
|
||||
validateConsumed({
|
||||
label: "theme parameters",
|
||||
declarations: themeDeclarations,
|
||||
consumers: derivedDeclarations,
|
||||
});
|
||||
validateConsumed({
|
||||
label: "light scheme bounds",
|
||||
declarations: schemeDeclarations,
|
||||
consumers: derivedDeclarations,
|
||||
});
|
||||
validateConsumed({
|
||||
label: "derived colors",
|
||||
declarations: derivedDeclarations,
|
||||
consumers: { ...derivedDeclarations, ...semanticDeclarations },
|
||||
});
|
||||
if (dark === undefined) {
|
||||
throw new Error(`Missing color selector: ${darkRootSelector}`);
|
||||
}
|
||||
validateGraph(light);
|
||||
validateGraph(new Map([...light, ...dark]));
|
||||
|
||||
return {
|
||||
theme: { color: themeColor, contrast: themeContrast },
|
||||
scheme: { light: lightScheme, dark: darkScheme },
|
||||
derived,
|
||||
semantic,
|
||||
theme: {
|
||||
color: getGroup(light, "--theme-color-"),
|
||||
contrast: getGroup(light, "--theme-contrast-"),
|
||||
},
|
||||
scheme: {
|
||||
light: getGroup(light, "--scheme-"),
|
||||
dark: getGroup(dark, "--scheme-"),
|
||||
},
|
||||
derived: getGroup(light, "--color-"),
|
||||
semantic: {
|
||||
background: getGroup(light, "--background-"),
|
||||
foreground: getGroup(light, "--foreground-"),
|
||||
border: getGroup(light, "--border-"),
|
||||
overlay: getGroup(light, "--overlay-"),
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -34,8 +34,11 @@
|
||||
--scheme-foreground-soft-lightness: 0.203788;
|
||||
--scheme-foreground-strong-lightness: 0.1;
|
||||
--scheme-foreground-chroma-scale: 1;
|
||||
--scheme-chromatic-luminance-max: 0.18;
|
||||
--scheme-chromatic-foreground-mix: 100%;
|
||||
--scheme-intent-lightness: 0.48;
|
||||
--scheme-floating-weight: 99%;
|
||||
--scheme-raised-weight: 98%;
|
||||
--scheme-nested-weight: 97%;
|
||||
--scheme-informative-weight: 12.24%;
|
||||
|
||||
/* Colors derived from the bounded theme parameters. */
|
||||
--color-background: oklch(
|
||||
@@ -55,162 +58,78 @@
|
||||
var(--color-foreground-soft) calc(100% - var(--theme-contrast-content)),
|
||||
var(--color-foreground-strong)
|
||||
);
|
||||
--color-accent-source: color(
|
||||
from oklch(from var(--theme-color-accent) clamp(0.2, l, 0.8) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-positive-source: color(
|
||||
from
|
||||
oklch(from var(--theme-color-positive) clamp(0.2, l, 0.8) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-negative-source: color(
|
||||
from
|
||||
oklch(from var(--theme-color-negative) clamp(0.2, l, 0.8) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-warning-source: color(
|
||||
from
|
||||
oklch(from var(--theme-color-warning) clamp(0.2, l, 0.95) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-informative-source: color(
|
||||
from
|
||||
oklch(
|
||||
from var(--theme-color-informative) clamp(0.2, l, 0.8) min(c, 0.3) h
|
||||
)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
/* Cap relative luminance by scaling XYZ toward black without changing hue. */
|
||||
--color-accent: color(
|
||||
from var(--color-accent-source) xyz-d65
|
||||
calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
min(y, var(--scheme-chromatic-luminance-max))
|
||||
calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
from oklch(from var(--theme-color-accent) clamp(0.2, l, 0.48) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-accent-secondary-source: color(
|
||||
--color-accent-secondary: color(
|
||||
from oklch(from var(--color-accent) l c calc(h + 55)) srgb clamp(0, r, 1)
|
||||
clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-accent-secondary: color(
|
||||
from var(--color-accent-secondary-source) xyz-d65
|
||||
calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
min(y, var(--scheme-chromatic-luminance-max))
|
||||
calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
);
|
||||
--color-positive: color(
|
||||
from var(--color-positive-source) xyz-d65
|
||||
calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
min(y, var(--scheme-chromatic-luminance-max))
|
||||
calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
from
|
||||
oklch(from var(--theme-color-positive) clamp(0.2, l, 0.48) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-negative: color(
|
||||
from var(--color-negative-source) xyz-d65
|
||||
calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
min(y, var(--scheme-chromatic-luminance-max))
|
||||
calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
from
|
||||
oklch(from var(--theme-color-negative) clamp(0.2, l, 0.48) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-warning: color(
|
||||
from var(--color-warning-source) xyz-d65
|
||||
calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
min(y, var(--scheme-chromatic-luminance-max))
|
||||
calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
from
|
||||
oklch(from var(--theme-color-warning) clamp(0.2, l, 0.48) min(c, 0.3) h)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-informative: color(
|
||||
from var(--color-informative-source) xyz-d65
|
||||
calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
min(y, var(--scheme-chromatic-luminance-max))
|
||||
calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))
|
||||
from
|
||||
oklch(
|
||||
from var(--theme-color-informative) clamp(0.2, l, 0.48) min(c, 0.3) h
|
||||
)
|
||||
srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1)
|
||||
);
|
||||
--color-shadow: oklch(
|
||||
from var(--theme-color-neutral) 0.203788 min(c, 0.02) h
|
||||
);
|
||||
--color-surface-soft: color-mix(
|
||||
in oklab,
|
||||
var(--color-background) 92%,
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-surface-strong: color-mix(
|
||||
in oklab,
|
||||
var(--color-background) 88%,
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-surface-secondary: color-mix(
|
||||
in oklab,
|
||||
var(--color-surface-soft) calc(100% - var(--theme-contrast-surface)),
|
||||
var(--color-surface-strong)
|
||||
);
|
||||
--color-border-soft: color-mix(
|
||||
in oklab,
|
||||
var(--color-background) 90.58%,
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-border-strong: color-mix(
|
||||
in oklab,
|
||||
var(--color-background) 40%,
|
||||
var(--color-background) calc(92% - var(--theme-contrast-surface) * 0.04),
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-border: color-mix(
|
||||
in oklab,
|
||||
var(--color-border-soft) calc(100% - var(--theme-contrast-border)),
|
||||
var(--color-border-strong)
|
||||
var(--color-background) calc(90.58% - var(--theme-contrast-border) * 0.5058),
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-focus: light-dark(
|
||||
color-mix(
|
||||
in oklab,
|
||||
var(--color-accent) calc(92% + var(--theme-contrast-surface) * 0.08),
|
||||
var(--color-background)
|
||||
),
|
||||
color-mix(
|
||||
in oklab,
|
||||
oklch(from var(--color-accent) max(l, 0.6) c h)
|
||||
calc(92% + var(--theme-contrast-surface) * 0.08),
|
||||
var(--color-background)
|
||||
)
|
||||
--color-focus: color-mix(
|
||||
in oklab,
|
||||
oklch(from var(--theme-color-accent) max(l, 0.6) min(c, 0.3) h)
|
||||
calc(92% + var(--theme-contrast-surface) * 0.08),
|
||||
var(--color-background)
|
||||
);
|
||||
--color-on-chromatic: light-dark(
|
||||
var(--color-background),
|
||||
var(--color-foreground-strong)
|
||||
);
|
||||
--color-accent-foreground: color-mix(
|
||||
in oklab,
|
||||
var(--color-accent) var(--scheme-chromatic-foreground-mix),
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-accent-secondary-foreground: light-dark(
|
||||
var(--color-accent-secondary),
|
||||
oklch(from var(--color-accent-secondary) max(l, 0.72) c h)
|
||||
);
|
||||
--color-positive-foreground: color-mix(
|
||||
in oklab,
|
||||
color-mix(in oklab, var(--color-positive) 90%, var(--color-foreground))
|
||||
var(--scheme-chromatic-foreground-mix),
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-negative-foreground: light-dark(
|
||||
oklch(from var(--color-negative) calc(l - 0.04) calc(c * 0.9) h),
|
||||
oklch(from var(--color-negative) max(l, 0.7) c h)
|
||||
);
|
||||
--color-warning-foreground: color-mix(
|
||||
in oklab,
|
||||
oklch(
|
||||
from
|
||||
color-mix(in oklab, var(--color-warning) 88%, var(--color-foreground))
|
||||
calc(l - 0.03) calc(c * 1.12) h
|
||||
)
|
||||
var(--scheme-chromatic-foreground-mix),
|
||||
var(--color-foreground)
|
||||
);
|
||||
--color-informative-foreground: color-mix(
|
||||
in oklab,
|
||||
color-mix(in oklab, var(--color-informative) 90%, var(--color-foreground))
|
||||
var(--scheme-chromatic-foreground-mix),
|
||||
var(--color-foreground)
|
||||
);
|
||||
|
||||
/* Background */
|
||||
--background-primary: var(--color-background);
|
||||
--background-secondary: var(--color-surface-secondary);
|
||||
--background-floating: color-mix(
|
||||
in oklab,
|
||||
var(--background-primary) var(--scheme-floating-weight),
|
||||
var(--foreground-primary)
|
||||
);
|
||||
--background-floating-raised: color-mix(
|
||||
in oklab,
|
||||
var(--background-primary) var(--scheme-raised-weight),
|
||||
var(--foreground-primary)
|
||||
);
|
||||
--background-floating-nested: color-mix(
|
||||
in oklab,
|
||||
var(--background-primary) var(--scheme-nested-weight),
|
||||
var(--foreground-primary)
|
||||
);
|
||||
--background-disabled: color-mix(
|
||||
in oklab,
|
||||
var(--color-background) 97.38%,
|
||||
@@ -235,21 +154,15 @@
|
||||
var(--color-negative) 12%,
|
||||
var(--color-background)
|
||||
);
|
||||
--background-warning-subtle: light-dark(
|
||||
oklch(from var(--color-warning-source) 0.94 calc(c * 0.45) h),
|
||||
color-mix(
|
||||
in oklab,
|
||||
var(--color-warning-source) 13.02%,
|
||||
var(--color-background)
|
||||
)
|
||||
--background-warning-subtle: color-mix(
|
||||
in oklab,
|
||||
var(--color-warning) 16%,
|
||||
var(--color-background)
|
||||
);
|
||||
--background-informative-subtle: light-dark(
|
||||
color-mix(
|
||||
in oklab,
|
||||
var(--color-informative) 12.24%,
|
||||
var(--color-background)
|
||||
),
|
||||
color-mix(in oklab, var(--color-informative) 20%, var(--color-background))
|
||||
--background-informative-subtle: color-mix(
|
||||
in oklab,
|
||||
var(--color-informative) var(--scheme-informative-weight),
|
||||
var(--color-background)
|
||||
);
|
||||
|
||||
/* Foreground */
|
||||
@@ -261,7 +174,7 @@
|
||||
);
|
||||
--foreground-disabled: color-mix(
|
||||
in oklab,
|
||||
var(--color-foreground) 45%,
|
||||
var(--color-foreground) 47%,
|
||||
var(--color-background)
|
||||
);
|
||||
--foreground-on-inverse: var(--color-background);
|
||||
@@ -270,18 +183,30 @@
|
||||
--foreground-on-positive: var(--color-on-chromatic);
|
||||
--foreground-on-negative: var(--color-on-chromatic);
|
||||
--foreground-on-text-selection: var(--color-background);
|
||||
--foreground-accent: var(--color-accent-foreground);
|
||||
--foreground-accent-secondary: var(--color-accent-secondary-foreground);
|
||||
--foreground-positive: var(--color-positive-foreground);
|
||||
--foreground-negative: var(--color-negative-foreground);
|
||||
--foreground-warning: var(--color-warning-foreground);
|
||||
--foreground-informative: var(--color-informative-foreground);
|
||||
--foreground-accent: oklch(
|
||||
from var(--color-accent) var(--scheme-intent-lightness) c h
|
||||
);
|
||||
--foreground-accent-secondary: oklch(
|
||||
from var(--color-accent-secondary) var(--scheme-intent-lightness) c h
|
||||
);
|
||||
--foreground-positive: oklch(
|
||||
from var(--color-positive) var(--scheme-intent-lightness) c h
|
||||
);
|
||||
--foreground-negative: oklch(
|
||||
from var(--color-negative) var(--scheme-intent-lightness) c h
|
||||
);
|
||||
--foreground-warning: oklch(
|
||||
from var(--color-warning) var(--scheme-intent-lightness) c h
|
||||
);
|
||||
--foreground-informative: oklch(
|
||||
from var(--color-informative) var(--scheme-intent-lightness) c h
|
||||
);
|
||||
|
||||
/* Border */
|
||||
--border-default: var(--color-border);
|
||||
--border-focus: var(--color-focus);
|
||||
--border-negative: var(--foreground-negative);
|
||||
--border-warning: var(--color-warning-source);
|
||||
--border-warning: var(--color-warning);
|
||||
--border-informative: color-mix(
|
||||
in oklab,
|
||||
var(--color-informative) 29.97%,
|
||||
@@ -316,8 +241,11 @@
|
||||
--scheme-foreground-soft-lightness: 0.93;
|
||||
--scheme-foreground-strong-lightness: 1;
|
||||
--scheme-foreground-chroma-scale: 0.2;
|
||||
--scheme-chromatic-luminance-max: 0.18;
|
||||
--scheme-chromatic-foreground-mix: 35%;
|
||||
--scheme-intent-lightness: 0.75;
|
||||
--scheme-floating-weight: 96%;
|
||||
--scheme-raised-weight: 93%;
|
||||
--scheme-nested-weight: 90%;
|
||||
--scheme-informative-weight: 30%;
|
||||
}
|
||||
|
||||
:root[data-color-scheme="light"] {
|
||||
|
||||
@@ -11,6 +11,10 @@ import { SmallToggleButton } from "./small-toggle-button";
|
||||
import { ToggleButton } from "./toggle-button";
|
||||
import { ToggleGroup, ToggleGroupButton } from "./toggle-group";
|
||||
import { Tooltip, TooltipProvider } from "./tooltip";
|
||||
import { Text } from "./text";
|
||||
import { Label } from "./label";
|
||||
import { MenuItemButton } from "./menu";
|
||||
import { getSelectedItemBackground } from "./component-state-color";
|
||||
|
||||
let root: Root | undefined;
|
||||
|
||||
@@ -152,6 +156,101 @@ const contrast = (first: number[], second: number[]) => {
|
||||
);
|
||||
};
|
||||
|
||||
test("secondary text stays readable in selected floating rows", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
for (const mode of ["light", "dark"] as const) {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
act(() =>
|
||||
root?.render(
|
||||
createElement(
|
||||
"div",
|
||||
{
|
||||
style: {
|
||||
background: getSelectedItemBackground(
|
||||
"var(--background-floating-raised)"
|
||||
),
|
||||
},
|
||||
},
|
||||
createElement(Text, { color: "moreSubtle" }, "Category")
|
||||
)
|
||||
)
|
||||
);
|
||||
const row = container.firstElementChild!;
|
||||
const text = row.firstElementChild!;
|
||||
expect(
|
||||
contrast(
|
||||
readColor(getComputedStyle(text).color),
|
||||
readColor(getComputedStyle(row).backgroundColor)
|
||||
),
|
||||
mode
|
||||
).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
});
|
||||
|
||||
test("style source labels keep small text readable", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
for (const mode of ["light", "dark"] as const) {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
act(() =>
|
||||
root?.render(
|
||||
createElement(
|
||||
"div",
|
||||
null,
|
||||
...(["local", "overwritten", "remote"] as const).map((color) =>
|
||||
createElement(Label, { key: color, color, children: color })
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
for (const label of container.querySelectorAll("button")) {
|
||||
const style = getComputedStyle(label);
|
||||
expect(
|
||||
contrast(readColor(style.color), readColor(style.backgroundColor)),
|
||||
`${mode} ${label.textContent}`
|
||||
).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("neutral destructive buttons keep small text readable", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
for (const mode of ["light", "dark"] as const) {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
act(() =>
|
||||
root?.render(
|
||||
createElement(Button, { color: "neutral-destructive" }, "Delete")
|
||||
)
|
||||
);
|
||||
const style = getComputedStyle(container.querySelector("button")!);
|
||||
expect(
|
||||
contrast(readColor(style.color), readColor(style.backgroundColor)),
|
||||
mode
|
||||
).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
});
|
||||
|
||||
test("disabled menu items do not highlight on hover", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
act(() =>
|
||||
root?.render(createElement(MenuItemButton, { disabled: true }, "Disabled"))
|
||||
);
|
||||
const button = container.querySelector("button")!;
|
||||
const before = getComputedStyle(button).backgroundColor;
|
||||
await page.elementLocator(button).hover({ force: true });
|
||||
expect(getComputedStyle(button).backgroundColor).toBe(before);
|
||||
});
|
||||
|
||||
test("strong button interaction states preserve text contrast", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
|
||||
@@ -54,3 +54,42 @@ export const ColorPicker = () => {
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const Transparent = () => {
|
||||
const [value, setValue] = useState<StyleValue>({
|
||||
...initialColor,
|
||||
alpha: 0.25,
|
||||
});
|
||||
return (
|
||||
<ColorPickerComponent
|
||||
open
|
||||
value={value}
|
||||
onChange={(next) => next && setValue(next)}
|
||||
onChangeComplete={setValue}
|
||||
/>
|
||||
);
|
||||
};
|
||||
export const Disabled = () => (
|
||||
<ColorPickerComponent
|
||||
disabled
|
||||
value={initialColor}
|
||||
onChange={() => {}}
|
||||
onChangeComplete={() => {}}
|
||||
/>
|
||||
);
|
||||
export const Oklch = () => {
|
||||
const [value, setValue] = useState<StyleValue>({
|
||||
type: "color",
|
||||
colorSpace: "oklch",
|
||||
components: [0.65, 0.2, 260],
|
||||
alpha: 0.5,
|
||||
});
|
||||
return (
|
||||
<ColorPickerComponent
|
||||
open
|
||||
value={value}
|
||||
onChange={(next) => next && setValue(next)}
|
||||
onChangeComplete={setValue}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -59,7 +59,7 @@ const contrast = (first: number[], second: number[]) => {
|
||||
);
|
||||
};
|
||||
|
||||
test("command panels use the panel surface and readable group headings", () => {
|
||||
test("command panels and selected items follow surface elevation", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
@@ -74,7 +74,9 @@ test("command panels use the panel surface and readable group headings", () => {
|
||||
createElement(
|
||||
Command,
|
||||
null,
|
||||
createElement(CommandInput),
|
||||
createElement(CommandInput, {
|
||||
action: { name: "select", label: "Select" },
|
||||
}),
|
||||
createElement(
|
||||
CommandList,
|
||||
null,
|
||||
@@ -102,21 +104,43 @@ test("command panels use the panel surface and readable group headings", () => {
|
||||
"[data-input-field-input]"
|
||||
)?.parentElement;
|
||||
const heading = container.querySelector("[cmdk-group-heading]");
|
||||
const selectedItem = container.querySelector(
|
||||
"[cmdk-item][aria-selected=true]"
|
||||
);
|
||||
const panelReference = container.firstElementChild;
|
||||
if (
|
||||
panel === null ||
|
||||
inputContainer === null ||
|
||||
inputContainer === undefined ||
|
||||
heading === null ||
|
||||
selectedItem === null ||
|
||||
panelReference === null
|
||||
) {
|
||||
throw new Error("Expected a rendered command group");
|
||||
}
|
||||
|
||||
const panelBackground = readColor(getComputedStyle(panel).backgroundColor);
|
||||
expect(panelBackground, `${mode} panel surface`).toEqual(
|
||||
readColor(getComputedStyle(panelReference).backgroundColor)
|
||||
const referenceBackground = readColor(
|
||||
getComputedStyle(panelReference).backgroundColor
|
||||
);
|
||||
const selectedBackground = readColor(
|
||||
getComputedStyle(selectedItem).backgroundColor
|
||||
);
|
||||
if (mode === "light") {
|
||||
expect(luminance(panelBackground)).toBeLessThan(
|
||||
luminance(referenceBackground)
|
||||
);
|
||||
expect(luminance(selectedBackground)).toBeLessThan(
|
||||
luminance(panelBackground)
|
||||
);
|
||||
} else {
|
||||
expect(luminance(panelBackground)).toBeGreaterThan(
|
||||
luminance(referenceBackground)
|
||||
);
|
||||
expect(luminance(selectedBackground)).toBeGreaterThan(
|
||||
luminance(panelBackground)
|
||||
);
|
||||
}
|
||||
expect(
|
||||
readColor(getComputedStyle(inputContainer).backgroundColor),
|
||||
`${mode} command input surface`
|
||||
@@ -125,5 +149,11 @@ test("command panels use the panel surface and readable group headings", () => {
|
||||
contrast(readColor(getComputedStyle(heading).color), panelBackground),
|
||||
`${mode} heading contrast`
|
||||
).toBeGreaterThanOrEqual(4.5);
|
||||
const actionHint = container.querySelector("kbd");
|
||||
expect(actionHint).not.toBeNull();
|
||||
expect(
|
||||
contrast(readColor(getComputedStyle(actionHint!).color), panelBackground),
|
||||
`${mode} command shortcut contrast`
|
||||
).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
});
|
||||
@@ -35,7 +35,7 @@ import { Flex } from "./flex";
|
||||
import { InputField } from "./input-field";
|
||||
import { SmallIconButton } from "./small-icon-button";
|
||||
import { cssVar, declareCssVar } from "../css-var";
|
||||
import { selectedItemBackground } from "./component-state-color";
|
||||
import { getSelectedItemBackground } from "./component-state-color";
|
||||
|
||||
const panelWidth = "500px";
|
||||
const itemHeight = "32px";
|
||||
@@ -47,7 +47,7 @@ const StyledCommand = styled(CommandPrimitive, {
|
||||
boxSizing: "border-box",
|
||||
width: panelWidth,
|
||||
boxShadow: theme.shadows.menuDropShadow,
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
backgroundColor: cssVar("--background-floating-raised"),
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
borderRadius: theme.borderRadius[7],
|
||||
// clip selected item background
|
||||
@@ -186,7 +186,7 @@ export const CommandBackIcon = styled(ChevronLeftIcon, {
|
||||
const CommandInputField = styled(InputField, {
|
||||
"--sizes-controlHeight": theme.spacing[15],
|
||||
border: "none",
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
backgroundColor: cssVar("--background-floating-raised"),
|
||||
paddingInline: theme.spacing[4],
|
||||
});
|
||||
|
||||
@@ -216,10 +216,10 @@ export const CommandInput = (
|
||||
suffix={
|
||||
action && (
|
||||
<Text
|
||||
color="moreSubtle"
|
||||
color="subtle"
|
||||
css={{ alignSelf: "center", paddingInline: theme.spacing[5] }}
|
||||
>
|
||||
{action.label} <Kbd value={["enter"]} color="moreSubtle" />
|
||||
{action.label} <Kbd value={["enter"]} color="subtle" />
|
||||
</Text>
|
||||
)
|
||||
}
|
||||
@@ -489,7 +489,7 @@ export const CommandGroupHeading = styled("div", {
|
||||
...textVariants.labels,
|
||||
color: cssVar("--foreground-secondary"),
|
||||
display: "flex",
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
backgroundColor: cssVar("--background-floating-raised"),
|
||||
gap: theme.spacing[5],
|
||||
alignItems: "center",
|
||||
paddingInline: theme.spacing[5],
|
||||
@@ -530,7 +530,9 @@ const CommandItemStyled = styled(CommandPrimitive.Item, {
|
||||
backgroundColor: cssVar("--overlay-interaction-hover"),
|
||||
},
|
||||
"&[aria-selected=true]": {
|
||||
backgroundColor: selectedItemBackground,
|
||||
backgroundColor: getSelectedItemBackground(
|
||||
cssVar("--background-floating-raised")
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -4,15 +4,15 @@ export const neutralControlBackground = `color-mix(in oklab, ${cssVar(
|
||||
"--background-primary"
|
||||
)} 86%, ${cssVar("--foreground-primary")})`;
|
||||
|
||||
export const selectedItemBackground = `light-dark(
|
||||
color-mix(in oklab, ${cssVar("--background-accent")} 12%, ${cssVar(
|
||||
"--background-primary"
|
||||
)}),
|
||||
color-mix(in oklab, ${cssVar("--background-accent")} 20%, ${cssVar(
|
||||
"--background-primary"
|
||||
)})
|
||||
export const getSelectedItemBackground = (background: string) => `light-dark(
|
||||
color-mix(in oklab, ${cssVar("--background-accent")} 12%, ${background}),
|
||||
color-mix(in oklab, ${cssVar("--background-accent")} 20%, ${background})
|
||||
)`;
|
||||
|
||||
export const selectedItemBackground = getSelectedItemBackground(
|
||||
cssVar("--background-primary")
|
||||
);
|
||||
|
||||
// Selected controls need more separation in dark mode, while remaining neutral.
|
||||
// This is a component-state composition, not a theme parameter.
|
||||
export const selectedControlBackground = `light-dark(
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioGroup,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuSubContent,
|
||||
} from "./context-menu";
|
||||
import { MenuCheckedIcon } from "./menu";
|
||||
import { Text } from "./text";
|
||||
export default { title: "Context menu", component: ContextMenu };
|
||||
export const Open = () => {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [checked, setChecked] = useState(true);
|
||||
const [value, setValue] = useState("first");
|
||||
useEffect(() => {
|
||||
ref.current?.dispatchEvent(
|
||||
new MouseEvent("contextmenu", {
|
||||
bubbles: true,
|
||||
clientX: 100,
|
||||
clientY: 70,
|
||||
})
|
||||
);
|
||||
}, []);
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
<div ref={ref} style={{ width: 240, height: 120 }}>
|
||||
<Text>Context menu</Text>
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuLabel>Actions</ContextMenuLabel>
|
||||
<ContextMenuItem>Copy</ContextMenuItem>
|
||||
<ContextMenuItem disabled>Paste</ContextMenuItem>
|
||||
<ContextMenuSub>
|
||||
<ContextMenuSubTrigger>More</ContextMenuSubTrigger>
|
||||
<ContextMenuSubContent>
|
||||
<ContextMenuItem>Duplicate</ContextMenuItem>
|
||||
<ContextMenuItem disabled>Delete</ContextMenuItem>
|
||||
</ContextMenuSubContent>
|
||||
</ContextMenuSub>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuCheckboxItem
|
||||
checked={checked}
|
||||
onCheckedChange={(v) => setChecked(v === true)}
|
||||
>
|
||||
Show guides
|
||||
</ContextMenuCheckboxItem>
|
||||
<ContextMenuRadioGroup value={value} onValueChange={setValue}>
|
||||
<ContextMenuRadioItem value="first" icon={<MenuCheckedIcon />}>
|
||||
First
|
||||
</ContextMenuRadioItem>
|
||||
<ContextMenuRadioItem value="second" icon={<MenuCheckedIcon />}>
|
||||
Second
|
||||
</ContextMenuRadioItem>
|
||||
</ContextMenuRadioGroup>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
);
|
||||
};
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
} from "./dropdown-menu";
|
||||
import { MenuCheckedAndSetIcon } from "./menu";
|
||||
import { Text } from "./text";
|
||||
|
||||
let root: Root | undefined;
|
||||
|
||||
@@ -23,8 +25,113 @@ afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = undefined;
|
||||
document.body.innerHTML = "";
|
||||
document.documentElement.removeAttribute("data-color-scheme");
|
||||
});
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"dropdowns rise above dialogs in %s mode",
|
||||
async (mode) => {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
await act(async () =>
|
||||
root?.render(
|
||||
<Dialog open>
|
||||
<DialogContent aria-describedby={undefined}>
|
||||
<DialogTitle>Dialog</DialogTitle>
|
||||
<Text color="destructive" data-dialog-error>
|
||||
Error
|
||||
</Text>
|
||||
<DropdownMenu defaultOpen>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button>Actions</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>Action</DropdownMenuItem>
|
||||
<DropdownMenuItem icon={<MenuCheckedAndSetIcon />}>
|
||||
Set
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem destructive>Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(document.querySelector('[role="menu"]')).not.toBeNull()
|
||||
);
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
const context = canvas.getContext("2d")!;
|
||||
const brightness = (element: Element) => {
|
||||
context.fillStyle = getComputedStyle(element).backgroundColor;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
return Array.from(context.getImageData(0, 0, 1, 1).data)
|
||||
.slice(0, 3)
|
||||
.reduce((sum, channel) => sum + channel, 0);
|
||||
};
|
||||
const dialog = brightness(document.querySelector('[role="dialog"]')!);
|
||||
const menu = brightness(document.querySelector('[role="menu"]')!);
|
||||
expect(mode === "light" ? menu < dialog : menu > dialog).toBe(true);
|
||||
const panel = document.createElement("div");
|
||||
panel.style.backgroundColor = "var(--background-primary)";
|
||||
document.body.append(panel);
|
||||
expect(
|
||||
mode === "light" ? dialog < brightness(panel) : dialog > brightness(panel)
|
||||
).toBe(true);
|
||||
panel.remove();
|
||||
|
||||
const color = (element: Element, property: "color" | "backgroundColor") => {
|
||||
context.fillStyle = getComputedStyle(element)[property];
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
return Array.from(context.getImageData(0, 0, 1, 1).data).slice(0, 3);
|
||||
};
|
||||
const luminance = (channels: number[]) =>
|
||||
channels
|
||||
.map((channel) => {
|
||||
const value = channel / 255;
|
||||
return value <= 0.04045
|
||||
? value / 12.92
|
||||
: ((value + 0.055) / 1.055) ** 2.4;
|
||||
})
|
||||
.reduce(
|
||||
(sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index],
|
||||
0
|
||||
);
|
||||
const contrast = (element: Element, surface: Element) => {
|
||||
const foreground = luminance(color(element, "color"));
|
||||
const background = luminance(color(surface, "backgroundColor"));
|
||||
return (
|
||||
(Math.max(foreground, background) + 0.05) /
|
||||
(Math.min(foreground, background) + 0.05)
|
||||
);
|
||||
};
|
||||
expect(
|
||||
contrast(
|
||||
document.querySelector('[role="menuitem"]:last-child')!,
|
||||
document.querySelector('[role="menu"]')!
|
||||
),
|
||||
`${mode} destructive menu text contrast`
|
||||
).toBeGreaterThanOrEqual(4.5);
|
||||
expect(
|
||||
contrast(
|
||||
document.querySelector('[role="menuitem"] svg')!,
|
||||
document.querySelector('[role="menu"]')!
|
||||
),
|
||||
`${mode} set icon contrast`
|
||||
).toBeGreaterThanOrEqual(3);
|
||||
expect(
|
||||
contrast(
|
||||
document.querySelector("[data-dialog-error]")!,
|
||||
document.querySelector('[role="dialog"]')!
|
||||
),
|
||||
`${mode} dialog error text contrast`
|
||||
).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
);
|
||||
|
||||
test("shows the maximize button hover background", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
|
||||
@@ -2,6 +2,12 @@ import { Button } from "./button";
|
||||
import { css, theme } from "../stitches.config";
|
||||
import { textVariants } from "./text";
|
||||
import { StorySection } from "./storybook";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "./dropdown-menu";
|
||||
import {
|
||||
Dialog,
|
||||
DialogActions,
|
||||
@@ -64,6 +70,26 @@ const DialogDemo = () => (
|
||||
);
|
||||
export { DialogDemo as Dialog };
|
||||
|
||||
export const DropdownInDialog = () => (
|
||||
<StorySection title="Dropdown in dialog">
|
||||
<Dialog defaultOpen>
|
||||
<DialogContent>
|
||||
<div className={bodyStyle()}>
|
||||
<DropdownMenu defaultOpen>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button>Actions</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>Example action</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<DialogTitle>Dialog with dropdown</DialogTitle>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export const ResizableDialog = () => (
|
||||
<StorySection title="Resizable dialog">
|
||||
<Dialog defaultOpen resize="both">
|
||||
|
||||
@@ -46,7 +46,7 @@ if (placeholderImage) {
|
||||
const panelStyle = css({
|
||||
boxSizing: "border-box",
|
||||
boxShadow: theme.shadows.panelSectionDropShadow,
|
||||
background: cssVar("--background-primary"),
|
||||
background: cssVar("--background-floating"),
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
borderRadius: theme.borderRadius[7],
|
||||
display: "flex",
|
||||
|
||||
@@ -311,6 +311,7 @@ export const FloatingPanel = ({
|
||||
</DialogTrigger>
|
||||
)}
|
||||
<DialogContent
|
||||
data-floating-panel
|
||||
css={{ width: theme.sizes.sidebarWidth, overflow: "auto" }}
|
||||
width={width}
|
||||
height={height}
|
||||
|
||||
@@ -90,3 +90,25 @@ export const GradientPicker = () => {
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const MidpointHint = () => (
|
||||
<GradientVariant
|
||||
label="Midpoint"
|
||||
initial="linear-gradient(90deg, black 0% 30%, white 100%)"
|
||||
/>
|
||||
);
|
||||
export const Disabled = () => {
|
||||
const gradient = parseLinearGradientOrThrow(
|
||||
"linear-gradient(90deg, black 0%, white 100%)"
|
||||
);
|
||||
return (
|
||||
<GradientPickerComponent
|
||||
disabled
|
||||
gradient={gradient}
|
||||
backgroundImage={formatLinearGradient(gradient)}
|
||||
onChange={() => {}}
|
||||
onChangeComplete={() => {}}
|
||||
onThumbSelect={() => {}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -4,6 +4,7 @@ import { afterEach, expect, test, vi } from "vitest";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { InsetList, InsetListItem } from "./inset-list";
|
||||
import { List, ListItem } from "./primitives/list";
|
||||
import "../colors/colors.css";
|
||||
|
||||
let root: Root | undefined;
|
||||
|
||||
@@ -15,6 +16,7 @@ afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = undefined;
|
||||
document.body.innerHTML = "";
|
||||
document.documentElement.removeAttribute("data-color-scheme");
|
||||
});
|
||||
|
||||
const pressArrow = (element: HTMLElement, key: string) => {
|
||||
@@ -23,6 +25,56 @@ const pressArrow = (element: HTMLElement, key: string) => {
|
||||
});
|
||||
};
|
||||
|
||||
test.each([
|
||||
["light", "--background-primary"],
|
||||
["light", "--background-floating"],
|
||||
["dark", "--background-primary"],
|
||||
["dark", "--background-floating"],
|
||||
] as const)(
|
||||
"selected inset list rows follow the %s %s surface",
|
||||
(mode, background) => {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
const container = document.createElement("div");
|
||||
container.style.background = `var(${background})`;
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
act(() =>
|
||||
root?.render(
|
||||
<InsetList>
|
||||
<InsetListItem data-state="selected">Selected</InsetListItem>
|
||||
</InsetList>
|
||||
)
|
||||
);
|
||||
|
||||
const selected = container.querySelector("button")!;
|
||||
const canvas = document.createElement("canvas");
|
||||
const context = canvas.getContext("2d")!;
|
||||
const brightness = (surfaceColor: string, rowColor?: string) => {
|
||||
context.clearRect(0, 0, 1, 1);
|
||||
context.fillStyle = surfaceColor;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
if (rowColor) {
|
||||
context.fillStyle = rowColor;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
}
|
||||
return Array.from(context.getImageData(0, 0, 1, 1).data)
|
||||
.slice(0, 3)
|
||||
.reduce((sum, channel) => sum + channel, 0);
|
||||
};
|
||||
const surfaceColor = getComputedStyle(container).backgroundColor;
|
||||
const rowColor = getComputedStyle(selected).backgroundColor;
|
||||
const surface = brightness(surfaceColor);
|
||||
const selection = brightness(surfaceColor, rowColor);
|
||||
context.clearRect(0, 0, 1, 1);
|
||||
context.fillStyle = rowColor;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
expect(context.getImageData(0, 0, 1, 1).data[3]).toBeLessThan(255);
|
||||
expect(mode === "light" ? selection < surface : selection > surface).toBe(
|
||||
true
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
test("keeps navigation labels left aligned beside their icons", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { forwardRef, type ComponentProps, type Ref } from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { buttonStyle } from "./button";
|
||||
import { selectedItemBackground } from "./component-state-color";
|
||||
import { cssVar } from "../css-var";
|
||||
import { css, styled, theme, type CSS } from "../stitches.config";
|
||||
|
||||
export const InsetList = styled("div", {
|
||||
@@ -25,7 +25,10 @@ const insetListItemStyle = css(buttonStyle, {
|
||||
gap: theme.spacing[5],
|
||||
cursor: "pointer",
|
||||
"&[aria-current=true], &[aria-current=page], &[data-state=selected]": {
|
||||
background: selectedItemBackground,
|
||||
background: `light-dark(
|
||||
color-mix(in oklab, ${cssVar("--background-accent")} 12%, transparent),
|
||||
color-mix(in oklab, ${cssVar("--background-accent")} 20%, transparent)
|
||||
)`,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { cssVar } from "../css-var";
|
||||
import { Kbd as KbdComponent } from "./kbd";
|
||||
import { Flex } from "./flex";
|
||||
import { Text } from "./text";
|
||||
@@ -21,7 +22,9 @@ export const Kbd = () => (
|
||||
</Flex>
|
||||
<Flex direction="column" gap="1">
|
||||
<Text variant="labels">contrast</Text>
|
||||
<KbdComponent value={["meta", "z"]} color="contrast" />
|
||||
<div style={{ background: cssVar("--background-inverse") }}>
|
||||
<KbdComponent value={["meta", "z"]} color="contrast" />
|
||||
</div>
|
||||
</Flex>
|
||||
</StoryGrid>
|
||||
</StorySection>
|
||||
|
||||
@@ -114,7 +114,7 @@ export const MenuItemButton = styled("button", menuItemCss, {
|
||||
boxSizing: "border-box",
|
||||
width: `calc(100% - ${itemMargin} * 2)`,
|
||||
"&:focus:not(:focus-visible)": { backgroundColor: "unset" },
|
||||
"&:hover:not([diabled])": {
|
||||
"&:hover:not([disabled])": {
|
||||
backgroundColor: cssVar("--overlay-interaction-hover"),
|
||||
},
|
||||
});
|
||||
@@ -133,10 +133,10 @@ const menuBorderWidth = "1px";
|
||||
export const menuCss = css({
|
||||
boxSizing: "border-box",
|
||||
borderRadius: theme.borderRadius[6],
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
backgroundColor: cssVar("--background-floating-raised"),
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
boxShadow: `${theme.shadows.menuDropShadow}, inset 0 0 0 1px ${cssVar(
|
||||
"--background-primary"
|
||||
"--background-floating-raised"
|
||||
)}`,
|
||||
padding: `${menuPadding} 0`,
|
||||
variants: {
|
||||
@@ -149,6 +149,10 @@ export const menuCss = css({
|
||||
export const MenuList = styled("div", menuCss);
|
||||
|
||||
export const subMenuCss = css(menuCss, {
|
||||
backgroundColor: cssVar("--background-floating-nested"),
|
||||
boxShadow: `${theme.shadows.menuDropShadow}, inset 0 0 0 1px ${cssVar(
|
||||
"--background-floating-nested"
|
||||
)}`,
|
||||
// the goal is to align the top menu item in a sub menu
|
||||
// with the menu item in the parent menu that opened it
|
||||
marginTop: `calc((${menuPadding} + ${menuBorderWidth}) * -1)`,
|
||||
@@ -163,10 +167,10 @@ export const subContentProps: Partial<ComponentProps<typeof SubContent>> = {
|
||||
// Arrow is hard to implement with just CSS,
|
||||
// so we implement it as a component
|
||||
const ArrowBackground = styled("path", {
|
||||
fill: cssVar("--background-primary"),
|
||||
fill: cssVar("--background-floating-raised"),
|
||||
});
|
||||
const ArrowInnerBorder = styled("path", {
|
||||
fill: cssVar("--background-primary"),
|
||||
fill: cssVar("--background-floating-raised"),
|
||||
});
|
||||
const ArrowOuterBorder = styled("path", { fill: cssVar("--border-default") });
|
||||
const ArrowSvg = styled("svg", { transform: "translateY(-3px)" });
|
||||
|
||||
@@ -22,9 +22,9 @@ export const PopoverAnchor = Primitive.Anchor;
|
||||
const contentStyle = css({
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
boxShadow: `${theme.shadows.menuDropShadow}, inset 0 0 0 1px ${cssVar(
|
||||
"--background-primary"
|
||||
"--background-floating-raised"
|
||||
)}`,
|
||||
background: cssVar("--background-primary"),
|
||||
background: cssVar("--background-floating-raised"),
|
||||
borderRadius: theme.borderRadius[6],
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
|
||||
@@ -65,3 +65,11 @@ export const PositionGrid = () => {
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const Disabled = () => (
|
||||
<PositionGridComponent
|
||||
disabled
|
||||
selectedPosition={{ x: 50, y: 50 }}
|
||||
onSelect={() => {}}
|
||||
/>
|
||||
);
|
||||
@@ -0,0 +1,57 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import "../colors/colors.css";
|
||||
import { Select } from "./select";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
test.each(["light", "dark"] as const)(
|
||||
"select menu clears the trigger and separates from it in %s mode",
|
||||
async (mode) => {
|
||||
document.documentElement.dataset.colorScheme = mode;
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(<Select options={["Block", "Flex"]} defaultValue="Block" />)
|
||||
);
|
||||
const trigger = container.querySelector<HTMLButtonElement>("button")!;
|
||||
const bottom = trigger.getBoundingClientRect().bottom;
|
||||
await act(async () => userEvent.click(trigger));
|
||||
await vi.waitFor(() =>
|
||||
expect(document.querySelector('[role="listbox"]')).not.toBeNull()
|
||||
);
|
||||
const list = document.querySelector<HTMLElement>('[role="listbox"]')!;
|
||||
expect(list.getBoundingClientRect().top - bottom).toBeGreaterThanOrEqual(
|
||||
4
|
||||
);
|
||||
const canvas = document.createElement("canvas");
|
||||
const context = canvas.getContext("2d")!;
|
||||
const brightness = (element: Element) => {
|
||||
context.fillStyle = getComputedStyle(element).backgroundColor;
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
return Array.from(context.getImageData(0, 0, 1, 1).data)
|
||||
.slice(0, 3)
|
||||
.reduce((sum, channel) => sum + channel, 0);
|
||||
};
|
||||
const panel = document.createElement("div");
|
||||
panel.style.backgroundColor = "var(--background-primary)";
|
||||
document.body.append(panel);
|
||||
expect(
|
||||
mode === "light"
|
||||
? brightness(list) < brightness(panel)
|
||||
: brightness(list) > brightness(panel)
|
||||
).toBe(true);
|
||||
panel.remove();
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
document.documentElement.removeAttribute("data-color-scheme");
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
useEffect,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { styled, theme } from "../stitches.config";
|
||||
import { rawTheme, styled, theme } from "../stitches.config";
|
||||
import {
|
||||
menuCss,
|
||||
menuItemCss,
|
||||
@@ -269,7 +269,10 @@ const SelectBase = <Option,>(
|
||||
</SelectButton>
|
||||
</Primitive.Trigger>
|
||||
<Primitive.Portal>
|
||||
<SelectContent position="popper">
|
||||
<SelectContent
|
||||
position="popper"
|
||||
sideOffset={Number.parseFloat(rawTheme.spacing[3])}
|
||||
>
|
||||
<Box
|
||||
css={{
|
||||
display: "flex",
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { SplitView } from "./split-view";
|
||||
import { Text } from "./text";
|
||||
import { cssVar } from "../css-var";
|
||||
export default { title: "Split view", component: SplitView };
|
||||
const Example = ({
|
||||
width = 640,
|
||||
single = false,
|
||||
}: {
|
||||
width?: number;
|
||||
single?: boolean;
|
||||
}) => (
|
||||
<div
|
||||
style={{ width, height: 240, background: cssVar("--background-floating") }}
|
||||
>
|
||||
<SplitView
|
||||
separatorLabel="Resize panels"
|
||||
start={<Text>Start</Text>}
|
||||
end={single ? undefined : <Text>End</Text>}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
export const Default = () => <Example />;
|
||||
export const Narrow = () => <Example width={280} />;
|
||||
export const SinglePane = () => <Example single />;
|
||||
@@ -15,7 +15,9 @@ const createStyleSourceColor = (solid: string, foreground: string) => ({
|
||||
border: `color-mix(in oklab, ${solid} 44%, ${cssVar(
|
||||
"--background-primary"
|
||||
)})`,
|
||||
foreground,
|
||||
foreground: `light-dark(color-mix(in oklab, ${foreground} 86%, ${cssVar(
|
||||
"--foreground-primary"
|
||||
)}), ${foreground})`,
|
||||
});
|
||||
|
||||
const accentBackground = cssVar("--background-accent");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { cssVar } from "../css-var";
|
||||
import { textVariants, Text as TextComponent } from "./text";
|
||||
import { StorySection, StoryGrid } from "./storybook";
|
||||
import { Flex } from "./flex";
|
||||
@@ -33,7 +34,15 @@ export const Text = () => (
|
||||
<StorySection title="Colors">
|
||||
<StoryGrid>
|
||||
{colors.map((color) => (
|
||||
<TextComponent key={color} color={color}>
|
||||
<TextComponent
|
||||
key={color}
|
||||
color={color}
|
||||
css={
|
||||
color === "contrast"
|
||||
? { background: cssVar("--background-inverse") }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{color}
|
||||
</TextComponent>
|
||||
))}
|
||||
|
||||
@@ -12,7 +12,7 @@ type VariantStyle = typeof normalize & (typeof typography)[Variant];
|
||||
|
||||
export const moreSubtleForeground = `color-mix(in oklab, ${cssVar(
|
||||
"--foreground-secondary"
|
||||
)} 56%, ${cssVar("--background-primary")})`;
|
||||
)} 92%, ${cssVar("--foreground-primary")})`;
|
||||
|
||||
export const textVariants = {} as { [Key in Variant]: VariantStyle };
|
||||
|
||||
|
||||
Reference in new issue
Block a user