From 89ca46cd7fbf4f2ba37477dd9afe3776b196e400 Mon Sep 17 00:00:00 2001 From: Oleg Isonen Date: Tue, 10 Nov 2026 22:10:16 +0000 Subject: [PATCH] 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. --- .github/workflows/visual-regression.yml | 2 +- .storybook/preview.tsx | 5 + .storybook/request-fixtures.ts | 27 ++ apps/builder/app/auth/login.stories.tsx | 13 + .../features/assets/assets.stories.tsx | 168 +++++++ .../breakpoints-editor.stories.tsx | 67 +++ .../canvas-settings-popover.stories.tsx | 25 ++ .../marketplace/marketplace.stories.tsx | 91 ++++ .../navigator/navigator-panel.stories.tsx | 219 ++++++++++ .../features/pages/page-states.stories.tsx | 182 ++++++++ .../features/pages/search-preview.stories.tsx | 2 +- .../publish-validation-results.stories.tsx | 61 +++ .../builder/features/safe-mode.stories.tsx | 29 ++ .../asset-query-form.stories.tsx | 103 +++++ .../variable-popover.stories.tsx | 333 ++++++++++++++ .../backdrop-filter.stories.tsx | 134 +++--- .../background-content.stories.tsx | 245 +++++------ .../sections/borders/borders.stories.tsx | 165 ++++--- .../box-shadows/box-shadows.stories.tsx | 148 +++---- .../sections/filter/filter.stories.tsx | 130 +++--- .../shared/grid-generator.browser.test.tsx | 104 +++++ .../layout/shared/grid-generator.stories.tsx | 93 ++++ .../sections/layout/shared/grid-generator.tsx | 16 +- .../shared/grid-settings.browser.test.tsx | 49 +++ .../layout/shared/grid-settings.stories.tsx | 101 +++++ .../sections/outline/outline.stories.tsx | 155 ++++--- .../sections/shared/input-popover.test.tsx | 42 ++ .../sections/shared/input-popover.tsx | 1 - .../shared/css-fragment.stories.tsx | 17 + ...plate-name-confirmation-dialog.stories.tsx | 32 ++ .../text-file-editor.stories.tsx | 226 ++++++++++ .../canvas-tools/canvas-tools.stories.tsx | 246 +++++++++++ .../collaborative-cursors.stories.tsx | 63 +++ .../floating-surfaces.stories.tsx | 104 +++++ .../canvas-tools/grid-guides.stories.tsx | 91 ++++ .../workspace/canvas-tools/media-badge.tsx | 2 +- .../block-instance-outline.stories.tsx | 225 ++++++++++ .../canvas-tools/resize-handles.stories.tsx | 63 +++ .../workspace/canvas-tools/text-toolbar.tsx | 4 +- apps/builder/app/builder/panels.stories.tsx | 211 +++++++++ .../asset-folder-dialogs.stories.tsx | 196 +++++++++ ...llection-entry-settings-dialog.stories.tsx | 171 ++++++++ .../delete-unused-assets.stories.tsx | 99 +++++ .../shared/binding-popover.stories.tsx | 88 ++++ .../builder/shared/collapsible-section.tsx | 10 +- .../shared/style-source-actions.stories.tsx | 112 +++++ .../features/build-mode/block.stories.tsx | 168 +++++++ .../dashboard/workspace/dialogs.stories.tsx | 56 +++ .../shared/code-editor-base.browser.test.tsx | 46 ++ apps/builder/app/shared/code-editor-base.tsx | 3 + .../shared/error/error-boundary.stories.tsx | 41 ++ .../app/shared/import-dialogs.stories.tsx | 55 +++ apps/builder/app/shared/logout.stories.tsx | 16 + .../project-settings-states.stories.tsx | 149 +++++++ .../app/shared/storybook/request-fixture.tsx | 25 ++ packages/design-system/src/colors/README.md | 64 ++- .../__generated__/css-variable-names.d.ts | 3 + .../src/colors/color-contrast.browser.test.ts | 332 +++++++------- .../src/colors/color-contrast.ts | 122 ++---- .../src/colors/color-source-utils.test.ts | 46 +- .../src/colors/color-source-utils.ts | 410 ++++-------------- packages/design-system/src/colors/colors.css | 228 ++++------ .../button-contrast.browser.test.ts | 99 +++++ .../src/components/color-picker.stories.tsx | 39 ++ .../src/components/command.browser.test.ts | 38 +- .../design-system/src/components/command.tsx | 16 +- .../src/components/component-state-color.ts | 14 +- .../components/context-menu-open.stories.tsx | 68 +++ .../src/components/dialog.browser.test.tsx | 107 +++++ .../src/components/dialog.stories.tsx | 26 ++ .../design-system/src/components/dialog.tsx | 2 +- .../src/components/floating-panel.tsx | 1 + .../components/gradient-picker.stories.tsx | 22 + .../components/inset-list.browser.test.tsx | 52 +++ .../src/components/inset-list.tsx | 7 +- .../src/components/kbd.stories.tsx | 5 +- .../design-system/src/components/menu.tsx | 14 +- .../design-system/src/components/popover.tsx | 4 +- .../src/components/position-grid.stories.tsx | 8 + .../src/components/select.browser.test.tsx | 57 +++ .../design-system/src/components/select.tsx | 7 +- .../src/components/split-view.stories.tsx | 24 + .../src/components/style-source-color.ts | 4 +- .../src/components/text.stories.tsx | 11 +- packages/design-system/src/components/text.ts | 2 +- 85 files changed, 5744 insertions(+), 1317 deletions(-) create mode 100644 .storybook/request-fixtures.ts create mode 100644 apps/builder/app/builder/features/assets/assets.stories.tsx create mode 100644 apps/builder/app/builder/features/breakpoints/breakpoints-editor.stories.tsx create mode 100644 apps/builder/app/builder/features/breakpoints/canvas-settings-popover.stories.tsx create mode 100644 apps/builder/app/builder/features/marketplace/marketplace.stories.tsx create mode 100644 apps/builder/app/builder/features/navigator/navigator-panel.stories.tsx create mode 100644 apps/builder/app/builder/features/pages/page-states.stories.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-validation-results.stories.tsx create mode 100644 apps/builder/app/builder/features/safe-mode.stories.tsx create mode 100644 apps/builder/app/builder/features/settings-panel/asset-query-form.stories.tsx create mode 100644 apps/builder/app/builder/features/settings-panel/variable-popover.stories.tsx create mode 100644 apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.browser.test.tsx create mode 100644 apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.stories.tsx create mode 100644 apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.browser.test.tsx create mode 100644 apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.stories.tsx create mode 100644 apps/builder/app/builder/features/template-name-confirmation-dialog.stories.tsx create mode 100644 apps/builder/app/builder/features/text-file-editor/text-file-editor.stories.tsx create mode 100644 apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.stories.tsx create mode 100644 apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.stories.tsx create mode 100644 apps/builder/app/builder/features/workspace/canvas-tools/floating-surfaces.stories.tsx create mode 100644 apps/builder/app/builder/features/workspace/canvas-tools/grid-guides.stories.tsx create mode 100644 apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.stories.tsx create mode 100644 apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.stories.tsx create mode 100644 apps/builder/app/builder/panels.stories.tsx create mode 100644 apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.stories.tsx create mode 100644 apps/builder/app/builder/shared/asset-manager/collection-entry-settings-dialog.stories.tsx create mode 100644 apps/builder/app/builder/shared/asset-manager/delete-unused-assets.stories.tsx create mode 100644 apps/builder/app/builder/shared/binding-popover.stories.tsx create mode 100644 apps/builder/app/builder/shared/style-source-actions.stories.tsx create mode 100644 apps/builder/app/canvas/features/build-mode/block.stories.tsx create mode 100644 apps/builder/app/shared/error/error-boundary.stories.tsx create mode 100644 apps/builder/app/shared/import-dialogs.stories.tsx create mode 100644 apps/builder/app/shared/logout.stories.tsx create mode 100644 apps/builder/app/shared/project-settings/project-settings-states.stories.tsx create mode 100644 apps/builder/app/shared/storybook/request-fixture.tsx create mode 100644 packages/design-system/src/components/context-menu-open.stories.tsx create mode 100644 packages/design-system/src/components/select.browser.test.tsx create mode 100644 packages/design-system/src/components/split-view.stories.tsx diff --git a/.github/workflows/visual-regression.yml b/.github/workflows/visual-regression.yml index c307c73ca9..17ce068c4b 100644 --- a/.github/workflows/visual-regression.yml +++ b/.github/workflows/visual-regression.yml @@ -56,7 +56,7 @@ jobs: ) ) timeout-minutes: 7 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 environment: name: development steps: diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx index 667bd2ef82..48cf868a8f 100644 --- a/.storybook/preview.tsx +++ b/.storybook/preview.tsx @@ -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"; diff --git a/.storybook/request-fixtures.ts b/.storybook/request-fixtures.ts new file mode 100644 index 0000000000..bbfef693d8 --- /dev/null +++ b/.storybook/request-fixtures.ts @@ -0,0 +1,27 @@ +/** Story-only HTTP boundary. Install before stories import clients that capture fetch. */ +export type RequestFixture = ( + request: Request +) => Response | Promise | 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; + }; +}; diff --git a/apps/builder/app/auth/login.stories.tsx b/apps/builder/app/auth/login.stories.tsx index 609b600415..a11463c838 100644 --- a/apps/builder/app/auth/login.stories.tsx +++ b/apps/builder/app/auth/login.stories.tsx @@ -31,3 +31,16 @@ export const Auth: StoryFn = () => { export const Dark = Auth.bind({}); Dark.globals = { colorScheme: "dark" }; + +export const Error = () => { + const router = createRouter( + + ); + return ; +}; diff --git a/apps/builder/app/builder/features/assets/assets.stories.tsx b/apps/builder/app/builder/features/assets/assets.stories.tsx new file mode 100644 index 0000000000..3a085ceb72 --- /dev/null +++ b/apps/builder/app/builder/features/assets/assets.stories.tsx @@ -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 | 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(() => {}); + } + 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 ? ( +
+ {}} onClose={() => {}} /> +
+ ) : null; +}; +export const Ready = () => ; +export const Loading = () => ; +export const InvalidConfiguration = () => ; +export const MissingTemplate = () => ( + +); +export const Unavailable = () => ; +export const EntryWarning = () => ; +export const ReadOnly = () => ; diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-editor.stories.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.stories.tsx new file mode 100644 index 0000000000..eb8e82e54b --- /dev/null +++ b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.stories.tsx @@ -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(); + 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 ( + + setToDelete(breakpoint)} + > + + + {toDelete && ( + setToDelete(undefined)} + onConfirm={() => setToDelete(undefined)} + /> + )} + + ); +}; + +export const Populated = () => ; +export const Empty = () => ; +export const DeleteConfirmation = () => ( + {}} + onConfirm={() => {}} + /> +); diff --git a/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.stories.tsx b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.stories.tsx new file mode 100644 index 0000000000..d9519d93d7 --- /dev/null +++ b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.stories.tsx @@ -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 ; +}; diff --git a/apps/builder/app/builder/features/marketplace/marketplace.stories.tsx b/apps/builder/app/builder/features/marketplace/marketplace.stories.tsx new file mode 100644 index 0000000000..720d945450 --- /dev/null +++ b/apps/builder/app/builder/features/marketplace/marketplace.stories.tsx @@ -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( + loading ? "section" : undefined + ); + const [about, setAbout] = useState( + selected ? "section" : undefined + ); + return ( +
+ setActive(item.projectId)} + /> +
+ ); +}; +export const Default = () => ; +export const Loading = () => ; +export const Selected = () => ; +export const 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 }) => ( +
+ {}} + /> +
+); +export const TemplatesAvailable = () => ; +export const TemplatesWithoutShareLink = () => ; diff --git a/apps/builder/app/builder/features/navigator/navigator-panel.stories.tsx b/apps/builder/app/builder/features/navigator/navigator-panel.stories.tsx new file mode 100644 index 0000000000..4672f68816 --- /dev/null +++ b/apps/builder/app/builder/features/navigator/navigator-panel.stories.tsx @@ -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("[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 ( + + + {ready && {}} />} + + + ); +}; + +export const Design = () => ; +export const NoEditableContent = () => ; +export const EditableContent = () => ; +export const MdxContent = () => ; +export const MultiSelection = () => ; +export const ContextMenu = () => ; +export const Rename = () => ; diff --git a/apps/builder/app/builder/features/pages/page-states.stories.tsx b/apps/builder/app/builder/features/pages/page-states.stories.tsx new file mode 100644 index 0000000000..5460b757ba --- /dev/null +++ b/apps/builder/app/builder/features/pages/page-states.stories.tsx @@ -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 ( +
+ {}} /> +
+ ); + } + const content = + state === "folder" ? ( + {}} + onRequestDelete={() => {}} + onDuplicate={() => {}} + /> + ) : state === "newFolder" ? ( + {}} onSuccess={() => {}} /> + ) : state === "template" ? ( + {}} + onDuplicate={() => {}} + onDelete={() => {}} + /> + ) : state === "newTemplate" ? ( + {}} /> + ) : state === "fromTemplate" ? ( + {}} + /> + ) : state === "newPage" ? ( + {}} /> + ) : ( + {}} + onDelete={() => {}} + onDuplicate={() => {}} + /> + ); + return ( + + {content} + + ); +}; +export const Tree = () => ; +export const ContentTree = () => ; +export const Folder = () => ; +export const NewFolder = () => ; +export const Template = () => ; +export const TemplateReadOnly = () => ( + +); +export const NewTemplate = () => ; +export const FromTemplate = () => ; +export const FromTemplateContentMode = () => ( + +); +export const NewPage = () => ; +export const Home = () => ; +export const Draft = () => ; +export const TextDocument = () => ; +export const RedirectConflict = () => ; +export const Marketplace = () => ; +export const BoundContent = () => ; diff --git a/apps/builder/app/builder/features/pages/search-preview.stories.tsx b/apps/builder/app/builder/features/pages/search-preview.stories.tsx index 5d38dcf1e8..5906e793b2 100644 --- a/apps/builder/app/builder/features/pages/search-preview.stories.tsx +++ b/apps/builder/app/builder/features/pages/search-preview.stories.tsx @@ -16,7 +16,7 @@ const faviconDataUrl = `data:image/svg+xml,${encodeURIComponent( export const SearchPreview = () => ( - + { + 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 ( + + + + ); +}; + +export const ErrorsAndWarnings = () => ( + +); +export const WarningOnly = () => ( + +); diff --git a/apps/builder/app/builder/features/safe-mode.stories.tsx b/apps/builder/app/builder/features/safe-mode.stories.tsx new file mode 100644 index 0000000000..1035fff428 --- /dev/null +++ b/apps/builder/app/builder/features/safe-mode.stories.tsx @@ -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( + '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 ; +}; diff --git a/apps/builder/app/builder/features/settings-panel/asset-query-form.stories.tsx b/apps/builder/app/builder/features/settings-panel/asset-query-form.stories.tsx new file mode 100644 index 0000000000..451b7d8468 --- /dev/null +++ b/apps/builder/app/builder/features/settings-panel/asset-query-form.stories.tsx @@ -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(); +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(null); + return ( +
+
+ +
+
+
+ ); +}; +export const Loaded = () => ; +export const Pending = () => ; +export const Error = () => ; +export const InvalidSavedQuery = () => ; diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.stories.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.stories.tsx new file mode 100644 index 0000000000..09fc8daca3 --- /dev/null +++ b/apps/builder/app/builder/features/settings-panel/variable-popover.stories.tsx @@ -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 ( + + + {ready && ( + { + if (open && invalidName) { + requestAnimationFrame(() => { + document + .querySelector( + '[data-variable-editor-dialog] input[name="name"]' + ) + ?.checkValidity(); + }); + } + }} + > + + + )} + + + ); +}; + +const valueStory = (value: DataSource & { type: "variable" }) => () => ( + +); + +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 () => ; +}; + +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(() => {}) + : undefined; +const assetsError = (request: Request) => + request.url.includes(assetsOpenApiUrl) + ? new Response(undefined, { status: 500 }) + : undefined; +const AssetsVariable = resourceStory(assetsResource); +export const Assets = () => ( + + + +); +export const AssetsDescriptionPending = () => ( + + + +); +export const AssetsDescriptionError = () => ( + + + +); + +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 = () => ; +export const ShadowWarning = () => ( + +); +export const InvalidName = () => ( + +); diff --git a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsx index 4915d2b49e..5397638437 100644 --- a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsx @@ -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 ( - -
- - ); -}; - -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 ( - -
- + + +
+ + ); }; -export const BackdropFilters = () => ( - - - - Default - -
- - - - With blur filter - - - - With multiple filters - - - - -); - export default { - title: "Style panel/Backdrop Filters", + title: "Style panel/Backdrop filters", component: Section, }; + +export const Empty = () => ; +export const Blur = () => ; +export const Multiple = () => ( + +); diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx index 4c5bc9dba1..d831a649f7 100644 --- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx @@ -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["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 ( - - - + + + + + ); }; -export const BackgroundContent = () => ( - - - - Image (none) - - - - Linear gradient - - - - Conic gradient - - - - Radial gradient - - - - Solid - - - - Repeating linear gradient - - - - Multi-stop gradient - - - - -); - export default { title: "Style panel/Backgrounds", component: BackgroundContentPanel, }; + +export const None = () => ( + +); +export const LinearGradient = () => ( + +); +export const ConicGradient = () => ( + +); +export const RadialGradient = () => ( + +); +export const Solid = () => ( + +); +export const RepeatingLinearGradient = () => ( + +); +export const MultiStopGradient = () => ( + +); diff --git a/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsx index edad48a48d..fa2cd60aa6 100644 --- a/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsx @@ -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 ( - -
- - ); -}; - -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 ( - -
- - ); -}; - -export const Borders = () => ( - - - - Default + + {ready && (
- - - With solid border - - - - With mixed borders - - - - -); - -export default { - title: "Style panel/Borders", - component: Section, + )} + + ); }; +export default { title: "Style panel/Borders", component: Section }; +export const Default = () => ; +export const Solid = () => ( + +); +export const Mixed = () => ( + +); diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsx index 4368bd3a7e..3f07cbe0e3 100644 --- a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsx @@ -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 ( - -
- + + +
+ + ); }; -const WithInsetShadowVariant = () => { - useEffect(() => { - $styles.set(new Map([[getStyleDeclKey(insetShadow), insetShadow]])); - }, []); - return ( - -
- - ); -}; - -const WithMultipleShadowsVariant = () => { - useEffect(() => { - $styles.set(new Map([[getStyleDeclKey(multipleShadows), multipleShadows]])); - }, []); - return ( - -
- - ); -}; - -export const BoxShadows = () => ( - - - - Default - -
- - - - With outer shadow - - - - With inset shadow - - - - With multiple shadows - - - - -); - export default { title: "Style panel/Box Shadows", component: Section, }; + +export const Empty = () => ; +export const Outer = () => ; +export const Inset = () => ; +export const Multiple = () => ; diff --git a/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsx index f133030a0c..4ebb90e89e 100644 --- a/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsx @@ -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 ( - -
- - ); -}; - -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 ( - -
- + + +
+ + ); }; -export const Filters = () => ( - - - - Default - -
- - - - With blur filter - - - - With multiple filters - - - - -); +export const Empty = () => ; +export const Single = () => ; +export const Multiple = () => ; export default { title: "Style panel/Filters", diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.browser.test.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.browser.test.tsx new file mode 100644 index 0000000000..c7745680d7 --- /dev/null +++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.browser.test.tsx @@ -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( + + + + ) + ); + + const dialog = document.querySelector('[role="dialog"]'); + const cells = dialog?.querySelectorAll("button"); + const preset = Array.from(cells ?? []).find((button) => + button.textContent?.includes("Fluid sidebar") + ); + const preview = preset?.querySelector("div"); + const previewCell = preview?.querySelector("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("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"); + } + } +); diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.stories.tsx new file mode 100644 index 0000000000..7c766c2dab --- /dev/null +++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.stories.tsx @@ -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 ( + + + + + + ); +}; diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx index 5a894feea6..435d7b5daf 100644 --- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx @@ -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, }} /> diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.browser.test.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.browser.test.tsx new file mode 100644 index 0000000000..5f364427aa --- /dev/null +++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.browser.test.tsx @@ -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()); + + const dialog = document.querySelector('[role="dialog"]'); + const section = dialog?.querySelector( + '[data-floating-panel-container] > [data-state="open"]' + ); + const stickyHeader = section?.querySelector( + "[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"); + } + } +); diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.stories.tsx new file mode 100644 index 0000000000..1b23dc4022 --- /dev/null +++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.stories.tsx @@ -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 ( + + + + + + + + ); +}; + +export const Tracks = () => ; +export const Areas = () => ; diff --git a/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsx index cbdb73cc6d..1dbd1c438a 100644 --- a/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsx @@ -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 ( - -
- - ); -}; - -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 ( - -
- - ); -}; - -export const Outline = () => ( - - - - Default + + {ready && (
- - - With solid outline - - - - With dashed outline - - - - -); - -export default { - title: "Style panel/Outline", - component: Section, + )} + + ); }; +export default { title: "Style panel/Outline", component: Section }; +export const Default = () => ; +export const Solid = () => ( + +); +export const Dashed = () => ( + +); diff --git a/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.test.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.test.tsx index 6df2724a4b..85e2fba5f3 100644 --- a/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.test.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.test.tsx @@ -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( + + ["paddingTop"]} + onClose={() => {}} + /> + + ) + ); + 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"); + } + } +); diff --git a/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsx index 2c8bc269ba..ed3e2a422d 100644 --- a/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsx +++ b/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsx @@ -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", diff --git a/apps/builder/app/builder/features/style-panel/shared/css-fragment.stories.tsx b/apps/builder/app/builder/features/style-panel/shared/css-fragment.stories.tsx index 44aa178381..963490db77 100644 --- a/apps/builder/app/builder/features/style-panel/shared/css-fragment.stories.tsx +++ b/apps/builder/app/builder/features/style-panel/shared/css-fragment.stories.tsx @@ -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 = () => (
); + +export const CSSValueDialog = () => ( + {}} + onChangeComplete={() => {}} + /> + } + /> +); diff --git a/apps/builder/app/builder/features/template-name-confirmation-dialog.stories.tsx b/apps/builder/app/builder/features/template-name-confirmation-dialog.stories.tsx new file mode 100644 index 0000000000..3a11752c81 --- /dev/null +++ b/apps/builder/app/builder/features/template-name-confirmation-dialog.stories.tsx @@ -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 ; +}; + +export const Rename = () => ; +export const Delete = () => ; diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.stories.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.stories.tsx new file mode 100644 index 0000000000..62049ec6b1 --- /dev/null +++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.stories.tsx @@ -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 ( + + {ready && ( + {}} + /> + )} + + ); +}; + +export const Loaded = () => ; +export const ReadOnly = () => ; +export const LoadError = () => ; +export const Markdown = () => ; +export const 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 | 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 ( + + {ready && ( + {}} + /> + )} + + ); +}; + +export const Mdx = () => ; +export const MdxReadOnly = () => ; +export const MdxSaveError = () => ; +export const MdxConflict = () => ; + +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 ( + {}} + onCreated={() => {}} + /> + ); +}; + +export const Create = () => ; +export const CreateInvalidExtension = () => ; +export const CreateDisabled = () => ; diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.stories.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.stories.tsx new file mode 100644 index 0000000000..439a12ce8b --- /dev/null +++ b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.stories.tsx @@ -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 ( + + + {ready && } + + + ); +}; + +export const SelectedBright = () => ( + +); +export const SelectedDark = () => ( + +); +export const SelectedSlot = () => ; +export const HoveredBright = () => ( + +); +export const HoveredDark = () => ; +export const CollaboratorBright = () => ( + +); +export const CollaboratorDark = () => ( + +); +export const Dragging = () => ; +export const InstanceContextMenu = () => ( + +); diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.stories.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.stories.tsx new file mode 100644 index 0000000000..c4ad5d334d --- /dev/null +++ b/apps/builder/app/builder/features/workspace/canvas-tools/collaborative-cursors.stories.tsx @@ -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 ( + <> + + {ready && } + + ); +}; + +export const BrightPalette = () => ; +export const DarkPalette = () => ; diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/floating-surfaces.stories.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/floating-surfaces.stories.tsx new file mode 100644 index 0000000000..537be4c1fa --- /dev/null +++ b/apps/builder/app/builder/features/workspace/canvas-tools/floating-surfaces.stories.tsx @@ -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 = () => ( + +
+ + + +
+
+); + +export const TextToolbarFormatted = () => ( + +
+ + + +
+
+); + +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 ( + +
+
+ +
+
+
+ ); +}; diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/grid-guides.stories.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/grid-guides.stories.tsx new file mode 100644 index 0000000000..de510f895f --- /dev/null +++ b/apps/builder/app/builder/features/workspace/canvas-tools/grid-guides.stories.tsx @@ -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 ( + + + + + + ); +}; + +export const BrightCells = () => ; +export const DarkCells = () => ; +export const BrightAreas = () => ; +export const DarkAreas = () => ; +export const TrackHighlight = () => ; +export const AreaHighlight = () => ; diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx index 923ed59e0f..8e1300d132 100644 --- a/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx +++ b/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx @@ -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], diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.stories.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.stories.tsx new file mode 100644 index 0000000000..9c82b829d8 --- /dev/null +++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.stories.tsx @@ -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 ( + + + {ready && + (state === "slash" || state === "slashEmpty" ? ( + + ) : state === "menu" ? ( + {}} + 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} + > + + + ) : ( + + ))} + + + ); +}; + +export const Insert = () => ; +export const Delete = () => ; +export const TemplatesMenuOpen = () => ; +export const SlashMenu = () => ; +export const SlashMenuNoResults = () => ; diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.stories.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.stories.tsx new file mode 100644 index 0000000000..20f0c21563 --- /dev/null +++ b/apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.stories.tsx @@ -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 ( + + + + + + ); +}; + +export const BrightIdle = () => ( + +); +export const DarkIdle = () => ; +export const BrightResizing = () => ; +export const DarkResizing = () => ; diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx index 6dc5eb98ab..b413c72814 100644 --- a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx +++ b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx @@ -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(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")}`, diff --git a/apps/builder/app/builder/panels.stories.tsx b/apps/builder/app/builder/panels.stories.tsx new file mode 100644 index 0000000000..e4a517b32c --- /dev/null +++ b/apps/builder/app/builder/panels.stories.tsx @@ -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 = (store: WritableAtom) => { + 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