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