Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Open text assets in code editor (#5918)

Oleg Isonencfba520e6d8d
diff --git a/apps/builder/app/builder/features/assets/assets.tsx b/apps/builder/app/builder/features/assets/assets.tsx
index b85fcd8573..4c6cec0011 100644
--- a/apps/builder/app/builder/features/assets/assets.tsx
+++ b/apps/builder/app/builder/features/assets/assets.tsx
@@ -7,13 +7,17 @@ import {
import { BrushCleaningIcon, NewFolderIcon } from "@webstudio-is/icons";
import { useRef, useState } from "react";
import { useStore } from "@nanostores/react";
+import { isTextFileAsset } from "@webstudio-is/sdk";
import { AssetManager } from "~/builder/shared/asset-manager";
import { AssetUpload, type AssetUploadHandle } from "~/builder/shared/assets";
import { openDeleteUnusedAssetsDialog } from "~/builder/shared/asset-manager/delete-unused-assets";
import { CreateAssetFolderDialog } from "~/builder/shared/asset-manager/asset-folder-dialogs";
import { $authPermit } from "~/shared/nano-states";
+import { $assets } from "~/shared/sync/data-stores";
import type { Publish } from "~/shared/pubsub";
import { useImageAssetCanvasDrag } from "./use-image-asset-canvas-drag";
+import { TextFileEditor } from "~/builder/features/text-file-editor/text-file-editor";
+import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
export const AssetsPanel = ({
publish,
@@ -23,8 +27,24 @@ export const AssetsPanel = ({
}) => {
const [folderId, setFolderId] = useState<string>();
const [createFolderOpen, setCreateFolderOpen] = useState(false);
+ const [openedTextAssetId, setOpenedTextAssetId] = useState<string>();
const uploadRef = useRef<AssetUploadHandle>(null);
const authPermit = useStore($authPermit);
+ const openAsset = (assetId: string) => {
+ const asset = $assets.get().get(assetId);
+ if (asset === undefined) {
+ return;
+ }
+ if (isTextFileAsset(asset)) {
+ setOpenedTextAssetId(assetId);
+ return;
+ }
+ window.open(
+ getAssetUrl(asset, window.location.origin),
+ "_blank",
+ "noopener,noreferrer"
+ );
+ };
useImageAssetCanvasDrag(publish);
return (
<>
@@ -55,6 +75,7 @@ export const AssetsPanel = ({
<AssetManager
folderId={folderId}
onFolderChange={setFolderId}
+ onOpen={openAsset}
canManageFolders={authPermit !== "view"}
panelActions={{
...(authPermit === "view"
@@ -71,6 +92,17 @@ export const AssetsPanel = ({
onOpenChange={setCreateFolderOpen}
currentFolderId={folderId}
/>
+ {openedTextAssetId !== undefined && (
+ <TextFileEditor
+ key={openedTextAssetId}
+ assetId={openedTextAssetId}
+ onOpenChange={(open) => {
+ if (open === false) {
+ setOpenedTextAssetId(undefined);
+ }
+ }}
+ />
+ )}
</>
);
};
diff --git a/apps/builder/app/builder/features/help/remote-dialog.tsx b/apps/builder/app/builder/features/help/remote-dialog.tsx
index 2455f4685b..6f75c4513c 100644
--- a/apps/builder/app/builder/features/help/remote-dialog.tsx
+++ b/apps/builder/app/builder/features/help/remote-dialog.tsx
@@ -39,6 +39,7 @@ export const RemoteDialog = () => {
* to make the close button last in the tab order
*/}
<DialogTitle
+ maximizable
suffix={
<DialogTitleActions>
<IconButton
diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
index 46d688bf0d..60cde42765 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -183,6 +183,7 @@ export const CodeControl = ({
lang={lang}
title={
<DialogTitle
+ maximizable
suffix={
<DialogTitleActions>
<DialogMaximize />
diff --git a/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx b/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx
index 1c75c2782d..a9106259d8 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/select-asset.tsx
@@ -2,11 +2,10 @@ import { useMemo } from "react";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import { Button, Flex, Text, FloatingPanel } from "@webstudio-is/design-system";
-import type { Prop } from "@webstudio-is/sdk";
import { acceptToMimeCategories } from "@webstudio-is/sdk";
import { $assets } from "~/shared/sync/data-stores";
import { AssetManager } from "~/builder/shared/asset-manager";
-import { type ControlProps } from "../shared";
+import { type PropValue } from "../shared";
import { formatAssetName } from "@webstudio-is/project-build/runtime";
import { AssetUpload } from "~/builder/shared/assets";
@@ -19,12 +18,10 @@ const isImageAccept = (accept?: string) => {
);
};
-type AssetControlProps = ControlProps<unknown>;
-
type Props = {
accept?: string;
- prop?: Extract<Prop, { type: "asset" }>;
- onChange: AssetControlProps["onChange"];
+ prop?: Extract<PropValue, { type: "asset" }>;
+ onChange: (value: Extract<PropValue, { type: "asset" }>) => void;
};
export const SelectAsset = ({ prop, onChange, accept }: Props) => {
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
index 151af05bbf..d162514ab8 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
@@ -127,6 +127,7 @@ export const TextContent = ({
<CodeEditor
title={
<DialogTitle
+ maximizable
suffix={
<DialogTitleActions>
<DialogMaximize />
diff --git a/apps/builder/app/builder/features/settings-panel/controls/url.tsx b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
index 3c2bcd6d9f..02c33c7fac 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/url.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
@@ -44,6 +44,7 @@ import {
$selectedInstanceScope,
useBindingState,
humanizeAttribute,
+ type PropValue,
} from "../shared";
import { SelectAsset } from "./select-asset";
import { createRootFolder } from "@webstudio-is/project-build";
@@ -51,13 +52,23 @@ import { PropertyLabel } from "../property-label";
type UrlControlProps = ControlProps<"url">;
+export type UrlInputValue = Extract<
+ PropValue,
+ { type: "string" | "page" | "asset" }
+>;
+
+type UrlInputProp =
+ | UrlInputValue
+ | { type: "expression"; value: string }
+ | undefined;
+
type BaseControlProps = {
id: string;
instanceId: string;
readOnly: boolean;
- prop: UrlControlProps["prop"];
+ prop: UrlInputProp;
value: string;
- onChange: UrlControlProps["onChange"];
+ onChange: (value: UrlInputValue) => void;
};
const Row = ({ children }: { children: ReactNode }) => (
@@ -442,10 +453,7 @@ const modes = {
type Mode = keyof typeof modes;
-const propToMode = (
- prop: undefined | UrlControlProps["prop"],
- value: string
-): Mode => {
+const propToMode = (prop: UrlInputProp, value: string): Mode => {
if (prop === undefined) {
return "url";
}
@@ -469,34 +477,40 @@ const propToMode = (
return "url";
};
-export const UrlControl = ({
+export const UrlInput = ({
instanceId,
- meta,
prop,
- propName,
- computedValue,
+ value,
+ readOnly = false,
onChange,
-}: UrlControlProps) => {
- const value = String(computedValue ?? "");
+ suffix,
+}: {
+ instanceId: string;
+ prop: UrlInputProp;
+ value: string;
+ readOnly?: boolean;
+ onChange: (value: UrlInputValue) => void;
+ suffix?: ReactNode;
+}) => {
const { value: mode, set: setMode } = useDraftValue<Mode>(
propToMode(prop, value),
() => {}
);
-
const id = useId();
-
const BaseControl = modes[mode].control;
-
- const label = humanizeAttribute(meta.label || propName);
- const { scope, aliases } = useStore($selectedInstanceScope);
- const expression =
- prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
- const { overwritable, variant } = useBindingState(
- prop?.type === "expression" ? prop.value : undefined
+ const control = (
+ <BaseControl
+ id={id}
+ instanceId={instanceId}
+ readOnly={readOnly}
+ prop={prop}
+ value={value}
+ onChange={onChange}
+ />
);
return (
- <VerticalLayout label={<PropertyLabel name={propName} />}>
+ <>
<Flex
css={{
py: theme.spacing[2],
@@ -508,7 +522,7 @@ export const UrlControl = ({
>
<ToggleGroup
type="single"
- disabled={overwritable === false}
+ disabled={readOnly}
value={mode}
onValueChange={(value) => {
// too tricky to prove to TS that value is a Mode
@@ -523,30 +537,66 @@ export const UrlControl = ({
))}
</ToggleGroup>
</Flex>
+ {suffix === undefined ? (
+ control
+ ) : (
+ <BindingControl>
+ {control}
+ {suffix}
+ </BindingControl>
+ )}
+ </>
+ );
+};
- <BindingControl>
- <BaseControl
- id={id}
- instanceId={instanceId}
- readOnly={overwritable === false}
- prop={prop}
- value={value}
- onChange={onChange}
- />
- <BindingPopover
- scope={scope}
- aliases={aliases}
- validate={(value) => validatePrimitiveValue(value, label)}
- variant={variant}
- value={expression}
- onChange={(newExpression) =>
- onChange({ type: "expression", value: newExpression })
- }
- onRemove={(evaluatedValue) =>
- onChange({ type: "string", value: String(evaluatedValue) })
- }
- />
- </BindingControl>
+export const UrlControl = ({
+ instanceId,
+ meta,
+ prop,
+ propName,
+ computedValue,
+ onChange,
+}: UrlControlProps) => {
+ const value = String(computedValue ?? "");
+ const label = humanizeAttribute(meta.label || propName);
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
+ const { overwritable, variant } = useBindingState(
+ prop?.type === "expression" ? prop.value : undefined
+ );
+
+ return (
+ <VerticalLayout label={<PropertyLabel name={propName} />}>
+ <UrlInput
+ instanceId={instanceId}
+ prop={
+ prop?.type === "string" ||
+ prop?.type === "page" ||
+ prop?.type === "asset" ||
+ prop?.type === "expression"
+ ? prop
+ : undefined
+ }
+ value={value}
+ readOnly={overwritable === false}
+ onChange={onChange}
+ suffix={
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ validate={(value) => validatePrimitiveValue(value, label)}
+ variant={variant}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "string", value: String(evaluatedValue) })
+ }
+ />
+ }
+ />
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index 74ee890e78..691e83ce87 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -952,6 +952,7 @@ const VariablePopoverContent = ({
</Grid>
<DialogTitle
+ maximizable
suffix={
<DialogTitleActions>
{(variableType === "resource" ||
@@ -1026,6 +1027,7 @@ export const VariablePopoverTrigger = ({
return (
<FloatingPanel
+ maximizable
placement="center"
width={740}
height={480}
diff --git a/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx b/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx
new file mode 100644
index 0000000000..f0291cf2cf
--- /dev/null
+++ b/apps/builder/app/builder/features/text-file-editor/markdown-preview.test.tsx
@@ -0,0 +1,51 @@
+import { expect, test } from "vitest";
+import type { Asset } from "@webstudio-is/sdk";
+import { __testing__ } from "./markdown-preview";
+import { renderMarkdown } from "./text-file-utils";
+
+const { resolveAssetReferences } = __testing__;
+
+const image: Asset = {
+ id: "image-id",
+ projectId: "project-id",
+ type: "image",
+ name: "image.png",
+ format: "png",
+ size: 1,
+ meta: { width: 1, height: 1 },
+ createdAt: "2026-01-01T00:00:00.000Z",
+};
+
+test("resolves asset IDs in Markdown images and links", () => {
+ const html = resolveAssetReferences({
+ html: renderMarkdown(
+ "![Local image](image-id)\n\n[Download image](image-id)\n\n![Remote image](https://example.com/image.png)"
+ ),
+ assetContainers: [{ status: "uploaded", asset: image }],
+ origin: "https://builder.example",
+ });
+
+ expect(html).toContain(
+ 'src="https://builder.example/cgi/image/image.png?format=raw"'
+ );
+ expect(html).toContain(
+ 'href="https://builder.example/cgi/image/image.png?format=raw"'
+ );
+ expect(html).toContain('src="https://example.com/image.png"');
+});
+
+test("uses an object URL while an inserted image is uploading", () => {
+ const html = resolveAssetReferences({
+ html: renderMarkdown("![Uploading](image-id)"),
+ assetContainers: [
+ {
+ status: "uploading",
+ asset: image,
+ objectURL: "blob:https://builder.example/upload",
+ },
+ ],
+ origin: "https://builder.example",
+ });
+
+ expect(html).toContain('src="blob:https://builder.example/upload"');
+});
diff --git a/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx b/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx
new file mode 100644
index 0000000000..3dece892ed
--- /dev/null
+++ b/apps/builder/app/builder/features/text-file-editor/markdown-preview.tsx
@@ -0,0 +1,241 @@
+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import {
+ Box,
+ css,
+ numericScrubControl,
+ theme,
+} from "@webstudio-is/design-system";
+import type { AssetContainer } from "~/builder/shared/assets";
+import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
+import { renderMarkdown } from "./text-file-utils";
+
+const minimumPaneWidth = 160;
+
+const previewStyle = css({
+ minWidth: 0,
+ height: "100%",
+ overflow: "auto",
+ boxSizing: "border-box",
+ padding: theme.spacing[9],
+ color: theme.colors.foregroundMain,
+ background: theme.colors.backgroundPanel,
+ fontFamily: theme.fonts.sans,
+ fontSize: 14,
+ lineHeight: 1.5,
+ userSelect: "text",
+ "& > :first-child": { marginTop: 0 },
+ "& > :last-child": { marginBottom: 0 },
+ "& h1, & h2, & h3, & h4, & h5, & h6": {
+ marginBlock: "1em 0.5em",
+ fontWeight: 600,
+ lineHeight: 1.25,
+ },
+ "& h1": { fontSize: "2em" },
+ "& h2": { fontSize: "1.5em" },
+ "& h3": { fontSize: "1.25em" },
+ "& p, & ul, & ol, & blockquote, & pre, & table": {
+ marginBlock: "1em",
+ },
+ "& ul, & ol": { paddingLeft: theme.spacing[9] },
+ "& ul": { listStyleType: "disc" },
+ "& ol": { listStyleType: "decimal" },
+ "& blockquote": {
+ marginInline: 0,
+ paddingLeft: theme.spacing[5],
+ color: theme.colors.foregroundSubtle,
+ borderLeft: `3px solid ${theme.colors.borderMain}`,
+ },
+ "& code": {
+ padding: "0.125em 0.25em",
+ borderRadius: theme.borderRadius[3],
+ background: theme.colors.backgroundControls,
+ fontFamily: theme.fonts.mono,
+ },
+ "& pre": {
+ overflowX: "auto",
+ padding: theme.spacing[5],
+ borderRadius: theme.borderRadius[4],
+ background: theme.colors.backgroundControls,
+ },
+ "& pre code": { padding: 0, background: "transparent" },
+ "& table": { width: "100%", borderCollapse: "collapse" },
+ "& th, & td": {
+ padding: theme.spacing[3],
+ border: `1px solid ${theme.colors.borderMain}`,
+ textAlign: "left",
+ },
+ "& img": { maxWidth: "100%" },
+ "& a": { color: theme.colors.foregroundPrimary },
+});
+
+const splitHandleStyle = css({
+ position: "relative",
+ width: 5,
+ height: "100%",
+ cursor: "col-resize",
+ touchAction: "none",
+ outline: "none",
+ "&::before": {
+ position: "absolute",
+ content: '""',
+ top: 0,
+ bottom: 0,
+ left: 2,
+ width: 1,
+ background: theme.colors.backgroundPrimaryLight,
+ },
+ "&:hover::before, &:focus-visible::before": {
+ left: 1,
+ width: 3,
+ },
+});
+
+const clampRatio = (ratio: number) => Math.min(0.8, Math.max(0.2, ratio));
+
+const resolveAssetReferences = ({
+ html,
+ assetContainers,
+ origin,
+}: {
+ html: string;
+ assetContainers: AssetContainer[];
+ origin: string;
+}) => {
+ if (typeof DOMParser === "undefined") {
+ return html;
+ }
+
+ const document = new DOMParser().parseFromString(html, "text/html");
+ const urls = new Map(
+ assetContainers.map((container) => [
+ container.asset.id,
+ container.status === "uploading"
+ ? container.objectURL
+ : getAssetUrl(container.asset, origin).href,
+ ])
+ );
+ for (const image of document.querySelectorAll("img[src]")) {
+ const url = urls.get(image.getAttribute("src") ?? "");
+ if (url !== undefined) {
+ image.setAttribute("src", url);
+ }
+ }
+ for (const link of document.querySelectorAll("a[href]")) {
+ const url = urls.get(link.getAttribute("href") ?? "");
+ if (url !== undefined) {
+ link.setAttribute("href", url);
+ }
+ }
+ return document.body.innerHTML;
+};
+
+export const __testing__ = { resolveAssetReferences };
+
+export const MarkdownSplitView = ({
+ open,
+ source,
+ assetContainers,
+ children,
+}: {
+ open: boolean;
+ source: string;
+ assetContainers: AssetContainer[];
+ children: ReactNode;
+}) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const handleRef = useRef<HTMLDivElement>(null);
+ const ratioRef = useRef(0.5);
+ const [ratio, setRatio] = useState(ratioRef.current);
+ const html = useMemo(() => {
+ if (open === false) {
+ return "";
+ }
+ return resolveAssetReferences({
+ html: renderMarkdown(source),
+ assetContainers,
+ origin: window.location.origin,
+ });
+ }, [assetContainers, open, source]);
+
+ const updateRatio = (nextRatio: number) => {
+ ratioRef.current = clampRatio(nextRatio);
+ setRatio(ratioRef.current);
+ };
+
+ useEffect(() => {
+ const handle = handleRef.current;
+ if (handle === null) {
+ return;
+ }
+
+ return numericScrubControl(handle, {
+ getInitialValue: () => {
+ const width = containerRef.current?.getBoundingClientRect().width ?? 0;
+ return width * ratioRef.current;
+ },
+ getValue: (state, movement) => {
+ const width = containerRef.current?.getBoundingClientRect().width ?? 0;
+ const paneWidth = Math.min(minimumPaneWidth, width / 2);
+ return Math.min(
+ width - paneWidth,
+ Math.max(paneWidth, state.value + movement)
+ );
+ },
+ onValueInput: (event) => {
+ const width = containerRef.current?.getBoundingClientRect().width ?? 0;
+ if (width > 0) {
+ updateRatio(event.value / width);
+ }
+ },
+ });
+ }, []);
+
+ return (
+ <Box
+ ref={containerRef}
+ css={{
+ display: "grid",
+ height: "100%",
+ minHeight: 0,
+ }}
+ style={{
+ gridTemplateColumns: open
+ ? `minmax(0, ${ratio}fr) 5px minmax(0, ${1 - ratio}fr)`
+ : "minmax(0, 1fr)",
+ }}
+ >
+ <Box css={{ minWidth: 0, minHeight: 0, overflow: "hidden" }}>
+ {children}
+ </Box>
+ <div
+ ref={handleRef}
+ className={splitHandleStyle()}
+ hidden={open === false}
+ role="separator"
+ aria-label="Resize Markdown preview"
+ aria-orientation="vertical"
+ aria-valuemin={20}
+ aria-valuemax={80}
+ aria-valuenow={Math.round(ratio * 100)}
+ tabIndex={0}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowLeft") {
+ event.preventDefault();
+ updateRatio(ratioRef.current - 0.05);
+ }
+ if (event.key === "ArrowRight") {
+ event.preventDefault();
+ updateRatio(ratioRef.current + 0.05);
+ }
+ }}
+ />
+ <div
+ className={previewStyle()}
+ hidden={open === false}
+ role="region"
+ aria-label="Markdown preview"
+ dangerouslySetInnerHTML={{ __html: html }}
+ />
+ </Box>
+ );
+};
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
new file mode 100644
index 0000000000..f5ecbcbd5b
--- /dev/null
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx
@@ -0,0 +1,593 @@
+import {
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+ type RefObject,
+} from "react";
+import { useStore } from "@nanostores/react";
+import {
+ Box,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Flex,
+ FloatingPanel,
+ IconButton,
+ rawTheme,
+ Text,
+ theme,
+ toast,
+ Tooltip,
+} from "@webstudio-is/design-system";
+import {
+ BlockquoteIcon,
+ BoldIcon,
+ ChevronDownIcon,
+ CheckboxCheckedIcon,
+ HeadingIcon,
+ ImageIcon,
+ LinkIcon,
+ ListIcon,
+ MarkdownEmbedIcon,
+ MinusIcon,
+ RepeatGridIcon,
+ SpinnerIcon,
+ TextItalicIcon,
+ TextStrikethroughIcon,
+} from "@webstudio-is/icons";
+import { formatAssetName } from "@webstudio-is/project-build/runtime";
+import { getPagePath, type Asset } from "@webstudio-is/sdk";
+import { CodeEditor } from "~/shared/code-editor";
+import { EditorDialog, type EditorApi } from "~/shared/code-editor-base";
+import { $assets, $pages, $props } from "~/shared/sync/data-stores";
+import { $authPermit } from "~/shared/nano-states";
+import { AssetManager } from "~/builder/shared/asset-manager";
+import { getAssetUrl } from "~/builder/shared/assets/asset-utils";
+import {
+ AssetUpload,
+ updateAssetContent,
+ useAssets,
+} from "~/builder/shared/assets";
+import {
+ UrlInput,
+ type UrlInputValue,
+} from "~/builder/features/settings-panel/controls/url";
+import {
+ getTextFileEditorExtensions,
+ isMarkdownAsset,
+} from "./text-file-utils";
+import { MarkdownSplitView } from "./markdown-preview";
+
+type TextFileState =
+ | { status: "loading" }
+ | { status: "loaded"; content: string }
+ | { status: "error" };
+
+const markdownActions = [
+ {
+ label: "Bold",
+ icon: <BoldIcon />,
+ template: { prefix: "**", suffix: "**", placeholder: "bold text" },
+ },
+ {
+ label: "Italic",
+ icon: <TextItalicIcon />,
+ template: { prefix: "_", suffix: "_", placeholder: "italic text" },
+ },
+ {
+ label: "Strikethrough",
+ icon: <TextStrikethroughIcon />,
+ template: {
+ prefix: "~~",
+ suffix: "~~",
+ placeholder: "strikethrough text",
+ },
+ },
+ {
+ label: "Blockquote",
+ icon: <BlockquoteIcon />,
+ template: { prefix: "> ", placeholder: "Quote" },
+ },
+ {
+ label: "Inline code",
+ icon: (
+ <Text as="span" variant="mono">
+ &lt;/&gt;
+ </Text>
+ ),
+ template: { prefix: "`", suffix: "`", placeholder: "code" },
+ },
+ {
+ label: "Code block",
+ icon: (
+ <Text as="span" variant="mono">
+ ```
+ </Text>
+ ),
+ template: {
+ prefix: "\n\n```\n",
+ suffix: "\n```\n\n",
+ placeholder: "code",
+ },
+ },
+ {
+ label: "Bulleted list",
+ icon: <ListIcon fill="currentColor" />,
+ template: { prefix: "- ", placeholder: "List item" },
+ },
+ {
+ label: "Numbered list",
+ icon: (
+ <Text as="span" variant="mono">
+ 1.
+ </Text>
+ ),
+ template: { prefix: "1. ", placeholder: "List item" },
+ },
+ {
+ label: "Task list",
+ icon: <CheckboxCheckedIcon />,
+ template: { prefix: "- [ ] ", placeholder: "Task" },
+ },
+ {
+ label: "Horizontal rule",
+ icon: <MinusIcon />,
+ template: { prefix: "\n\n---\n\n", placeholder: "" },
+ },
+ {
+ label: "Table",
+ icon: <RepeatGridIcon />,
+ template: {
+ prefix: "\n\n| Column 1 | Column 2 |\n| --- | --- |\n| ",
+ suffix: " | Value |\n\n",
+ placeholder: "Value",
+ },
+ },
+];
+
+const headingLevels = [1, 2, 3, 4, 5, 6] as const;
+
+const MarkdownHeadingMenu = ({
+ editorApiRef,
+ disabled,
+}: {
+ editorApiRef: RefObject<EditorApi | undefined>;
+ disabled: boolean;
+}) => (
+ <DropdownMenu>
+ <Tooltip content="Heading">
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ type="button"
+ aria-label="Heading"
+ disabled={disabled}
+ css={{ gap: theme.spacing[1], paddingInline: theme.spacing[2] }}
+ >
+ <HeadingIcon />
+ <ChevronDownIcon size={12} />
+ </IconButton>
+ </DropdownMenuTrigger>
+ </Tooltip>
+ <DropdownMenuContent
+ align="start"
+ sideOffset={4}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ editorApiRef.current?.focus();
+ }}
+ >
+ {headingLevels.map((level) => (
+ <DropdownMenuItem
+ key={level}
+ withIndicator={false}
+ onSelect={() =>
+ editorApiRef.current?.insertTemplate({
+ prefix: `${"#".repeat(level)} `,
+ placeholder: `Heading ${level}`,
+ })
+ }
+ >
+ Heading {level}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+);
+
+const MarkdownImagePicker = ({
+ editorApiRef,
+ disabled,
+}: {
+ editorApiRef: RefObject<EditorApi | undefined>;
+ disabled: boolean;
+}) => {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <FloatingPanel
+ title="Images"
+ titleSuffix={<AssetUpload type="image" accept="image/*" />}
+ placement="bottom-within"
+ open={open}
+ onOpenChange={setOpen}
+ content={
+ <AssetManager
+ accept="image/*"
+ onChange={(assetId) => {
+ editorApiRef.current?.insertTemplate({
+ prefix: "![",
+ suffix: `](${assetId})`,
+ placeholder: "alt text",
+ });
+ setOpen(false);
+ }}
+ />
+ }
+ >
+ <IconButton
+ type="button"
+ aria-label="Image"
+ title="Image"
+ disabled={disabled}
+ onMouseDown={(event) => event.preventDefault()}
+ >
+ <ImageIcon />
+ </IconButton>
+ </FloatingPanel>
+ );
+};
+
+const getMarkdownHref = (value: UrlInputValue) => {
+ if (value.type === "string" || value.type === "asset") {
+ return value.value;
+ }
+
+ const pages = $pages.get();
+ if (pages === undefined) {
+ return "";
+ }
+
+ const pageId =
+ typeof value.value === "string" ? value.value : value.value.pageId;
+ if (pages.pages.has(pageId) === false) {
+ return "";
+ }
+
+ const url = new URL(getPagePath(pageId, pages), "https://any-valid.url");
+ if (typeof value.value === "string") {
+ return url.pathname;
+ }
+
+ const section = value.value;
+ const idProp = Array.from($props.get().values()).find(
+ (prop) => prop.instanceId === section.instanceId && prop.name === "id"
+ );
+ if (idProp?.type === "string") {
+ url.hash = encodeURIComponent(idProp.value);
+ }
+ return `${url.pathname}${url.hash}`;
+};
+
+const initialLinkValue: UrlInputValue = { type: "string", value: "" };
+
+const MarkdownLinkPicker = ({
+ editorApiRef,
+ disabled,
+}: {
+ editorApiRef: RefObject<EditorApi | undefined>;
+ disabled: boolean;
+}) => {
+ const [open, setOpen] = useState(false);
+ const [value, setValue] = useState<UrlInputValue>(initialLinkValue);
+ const valueRef = useRef<UrlInputValue>(initialLinkValue);
+
+ return (
+ <FloatingPanel
+ title="Link"
+ placement="bottom-within"
+ open={open}
+ onOpenChange={(open) => {
+ if (open) {
+ valueRef.current = initialLinkValue;
+ setValue(initialLinkValue);
+ }
+ setOpen(open);
+ }}
+ content={
+ open && (
+ <Flex
+ direction="column"
+ gap={5}
+ css={{ padding: theme.panel.padding }}
+ >
+ <UrlInput
+ instanceId="markdown-link"
+ prop={value}
+ value={value.type === "string" ? value.value : ""}
+ onChange={(value) => {
+ valueRef.current = value;
+ setValue(value);
+ }}
+ />
+ <Flex justify="end">
+ <Button
+ type="button"
+ onClick={() => {
+ const href = getMarkdownHref(valueRef.current);
+ if (href === "") {
+ return;
+ }
+ editorApiRef.current?.insertTemplate({
+ prefix: "[",
+ suffix: `](${href})`,
+ placeholder: "link text",
+ });
+ setOpen(false);
+ }}
+ >
+ Insert link
+ </Button>
+ </Flex>
+ </Flex>
+ )
+ }
+ >
+ <IconButton
+ type="button"
+ aria-label="Link"
+ title="Link"
+ disabled={disabled}
+ onMouseDown={(event) => event.preventDefault()}
+ >
+ <LinkIcon />
+ </IconButton>
+ </FloatingPanel>
+ );
+};
+
+const MarkdownToolbar = ({
+ editorApiRef,
+ disabled,
+ previewOpen,
+ onPreviewOpenChange,
+}: {
+ editorApiRef: RefObject<EditorApi | undefined>;
+ disabled: boolean;
+ previewOpen: boolean;
+ onPreviewOpenChange: (open: boolean) => void;
+}) => (
+ <Flex
+ role="toolbar"
+ aria-label="Markdown formatting"
+ align="center"
+ gap={2}
+ css={{
+ padding: theme.spacing[3],
+ borderBottom: `1px solid ${theme.colors.borderMain}`,
+ overflow: "hidden",
+ flexShrink: 0,
+ background: theme.colors.backgroundPanel,
+ }}
+ >
+ <Flex
+ align="center"
+ gap={2}
+ css={{
+ minWidth: 0,
+ flex: 1,
+ overflowX: "auto",
+ scrollbarWidth: "none",
+ "&::-webkit-scrollbar": { display: "none" },
+ }}
+ >
+ <MarkdownHeadingMenu editorApiRef={editorApiRef} disabled={disabled} />
+ {markdownActions.map(({ label, icon, template }) => (
+ <Tooltip key={label} content={label}>
+ <IconButton
+ type="button"
+ aria-label={label}
+ disabled={disabled}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => editorApiRef.current?.insertTemplate(template)}
+ >
+ {icon}
+ </IconButton>
+ </Tooltip>
+ ))}
+ <MarkdownLinkPicker editorApiRef={editorApiRef} disabled={disabled} />
+ <MarkdownImagePicker editorApiRef={editorApiRef} disabled={disabled} />
+ </Flex>
+ <Tooltip content={previewOpen ? "Hide preview" : "Show preview"}>
+ <IconButton
+ type="button"
+ aria-label={previewOpen ? "Hide preview" : "Show preview"}
+ aria-pressed={previewOpen}
+ variant={previewOpen ? "local" : "default"}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => onPreviewOpenChange(previewOpen === false)}
+ >
+ <MarkdownEmbedIcon />
+ </IconButton>
+ </Tooltip>
+ </Flex>
+);
+
+export const TextFileEditor = ({
+ assetId,
+ onOpenChange,
+}: {
+ assetId: string;
+ onOpenChange: (open: boolean) => void;
+}) => {
+ const assets = useStore($assets);
+ const asset = assets.get(assetId);
+ const { assetContainers } = useAssets();
+ const canEdit = useStore($authPermit) !== "view";
+ const [state, setState] = useState<TextFileState>({ status: "loading" });
+ const [previewOpen, setPreviewOpen] = useState(false);
+ const currentAssetRef = useRef<Asset>();
+ const persistedContentRef = useRef<string>();
+ const requestedContentRef = useRef<string>();
+ const saveQueueRef = useRef(Promise.resolve());
+ const editorApiRef = useRef<EditorApi>();
+
+ useEffect(() => {
+ const assetToLoad = $assets.get().get(assetId);
+ if (assetToLoad === undefined) {
+ setState({ status: "error" });
+ return;
+ }
+ currentAssetRef.current = assetToLoad;
+
+ const controller = new AbortController();
+ setState({ status: "loading" });
+
+ const load = async () => {
+ try {
+ const response = await fetch(
+ getAssetUrl(assetToLoad, window.location.origin),
+ { signal: controller.signal }
+ );
+ if (response.ok === false) {
+ throw new Error(`Unable to load asset: ${response.status}`);
+ }
+ const content = await response.text();
+ persistedContentRef.current = content;
+ setState({ status: "loaded", content });
+ } catch (error) {
+ if (controller.signal.aborted) {
+ return;
+ }
+ setState({ status: "error" });
+ toast.error(
+ error instanceof Error ? error.message : "Unable to load asset"
+ );
+ }
+ };
+
+ void load();
+ return () => controller.abort();
+ }, [assetId]);
+
+ const save = (content: string) => {
+ if (canEdit === false) {
+ return;
+ }
+ requestedContentRef.current = content;
+ saveQueueRef.current = saveQueueRef.current.then(async () => {
+ const requestedContent = requestedContentRef.current;
+ if (
+ requestedContent === undefined ||
+ requestedContent === persistedContentRef.current
+ ) {
+ return;
+ }
+
+ const currentAsset = currentAssetRef.current;
+ if (currentAsset === undefined) {
+ toast.error("Unable to save: asset not found");
+ return;
+ }
+
+ try {
+ const updatedAsset = await updateAssetContent({
+ asset: currentAsset,
+ content: requestedContent,
+ });
+ currentAssetRef.current = updatedAsset;
+ persistedContentRef.current = requestedContent;
+ toast.success("File saved successfully");
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Unable to save");
+ }
+ });
+ };
+
+ const title = asset === undefined ? "Text file" : formatAssetName(asset);
+ const isMarkdown = asset !== undefined && isMarkdownAsset(asset);
+ let editor: ReactNode;
+ if (state.status === "loaded" && asset !== undefined) {
+ editor = (
+ <CodeEditor
+ editorApiRef={editorApiRef}
+ value={state.content}
+ languageExtensions={getTextFileEditorExtensions(asset)}
+ size="full"
+ expandable={false}
+ showBorder={false}
+ readOnly={canEdit === false}
+ onChange={(content) => {
+ setState({ status: "loaded", content });
+ }}
+ onChangeComplete={save}
+ />
+ );
+ }
+
+ return (
+ <EditorDialog
+ title={title}
+ contentPadding={false}
+ open
+ onOpenChange={(open) => {
+ if (open === false && state.status === "loaded") {
+ save(state.content);
+ }
+ onOpenChange(open);
+ }}
+ content={
+ <Box
+ data-floating-panel-container
+ css={{ height: "100%", minHeight: 0 }}
+ >
+ {state.status === "loading" && (
+ <Flex align="center" justify="center" css={{ height: "100%" }}>
+ <SpinnerIcon size={rawTheme.spacing[15]} />
+ </Flex>
+ )}
+ {state.status === "error" && (
+ <Flex align="center" justify="center" css={{ height: "100%" }}>
+ <Text color="subtle">Unable to load this file.</Text>
+ </Flex>
+ )}
+ {state.status === "loaded" && asset !== undefined && (
+ <Box
+ css={{
+ display: "grid",
+ gridTemplateRows: isMarkdown
+ ? "auto minmax(0, 1fr)"
+ : "minmax(0, 1fr)",
+ height: "100%",
+ }}
+ >
+ {isMarkdown && (
+ <MarkdownToolbar
+ editorApiRef={editorApiRef}
+ disabled={canEdit === false}
+ previewOpen={previewOpen}
+ onPreviewOpenChange={setPreviewOpen}
+ />
+ )}
+ {isMarkdown ? (
+ <MarkdownSplitView
+ open={previewOpen}
+ source={state.content}
+ assetContainers={assetContainers}
+ >
+ {editor}
+ </MarkdownSplitView>
+ ) : (
+ editor
+ )}
+ </Box>
+ )}
+ </Box>
+ }
+ >
+ <button type="button" hidden tabIndex={-1} />
+ </EditorDialog>
+ );
+};
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
new file mode 100644
index 0000000000..43f4ba828e
--- /dev/null
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, test } from "vitest";
+import {
+ ALLOWED_FILE_TYPES,
+ getAssetTextEditorLanguage,
+ isTextFileAsset,
+} from "@webstudio-is/sdk";
+import {
+ getTextFileEditorExtensions,
+ isMarkdownAsset,
+ renderMarkdown,
+} from "./text-file-utils";
+
+describe("text file assets", () => {
+ test("detects formats case-insensitively", () => {
+ expect(isTextFileAsset({ format: "JSON" })).toBe(true);
+ expect(getTextFileEditorExtensions({ format: "JSON" })).toHaveLength(1);
+ });
+
+ test("does not open unsupported files", () => {
+ expect(isTextFileAsset({ format: "pdf" })).toBe(false);
+ });
+
+ test.each(["md", "js", "css", "json", "html", "xml", "svg"])(
+ "uses the available CodeMirror language for %s",
+ (format) => {
+ expect(getTextFileEditorExtensions({ format })).toHaveLength(1);
+ }
+ );
+
+ test.each(["txt", "csv"])("uses plain text editing for %s", (format) => {
+ expect(getTextFileEditorExtensions({ format })).toEqual([]);
+ });
+
+ test.each(Object.keys(ALLOWED_FILE_TYPES))(
+ "defines editor behavior for %s files",
+ (format) => {
+ const language = getAssetTextEditorLanguage({ format });
+ expect(isTextFileAsset({ format })).toBe(language !== undefined);
+ expect(getTextFileEditorExtensions({ format })).toHaveLength(
+ language === undefined || language === "plain" ? 0 : 1
+ );
+ }
+ );
+
+ test("identifies Markdown files case-insensitively", () => {
+ expect(isMarkdownAsset({ format: "MD" })).toBe(true);
+ expect(isMarkdownAsset({ format: "txt" })).toBe(false);
+ });
+
+ test("renders a safe GFM preview", () => {
+ const html = renderMarkdown(
+ "~~done~~\n\n| A | B |\n| - | - |\n| 1 | 2 |\n\n<script>alert(1)</script>\n\n[unsafe](javascript:alert(1))"
+ );
+ expect(html).toContain("<del>done</del>");
+ expect(html).toContain("<table>");
+ expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
+ expect(html).not.toContain('href="javascript:');
+ });
+});
diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
new file mode 100644
index 0000000000..b12b1710a7
--- /dev/null
+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts
@@ -0,0 +1,41 @@
+import type { Extension } from "@codemirror/state";
+import { css } from "@codemirror/lang-css";
+import { html } from "@codemirror/lang-html";
+import { javascript } from "@codemirror/lang-javascript";
+import { markdown } from "@codemirror/lang-markdown";
+import { micromark } from "micromark";
+import { gfm, gfmHtml } from "micromark-extension-gfm";
+import {
+ getAssetTextEditorLanguage,
+ type Asset,
+ type AssetTextEditorLanguage,
+} from "@webstudio-is/sdk";
+
+const languageExtensions = {
+ plain: [],
+ css: [css()],
+ html: [html()],
+ javascript: [javascript()],
+ json: [javascript()],
+ markdown: [markdown()],
+ xml: [html()],
+} satisfies Record<AssetTextEditorLanguage, Extension[]>;
+
+export const getTextFileEditorExtensions = (
+ asset: Pick<Asset, "format">
+): Extension[] => {
+ const language = getAssetTextEditorLanguage(asset);
+ if (language === undefined) {
+ return [];
+ }
+ return languageExtensions[language];
+};
+
+export const isMarkdownAsset = (asset: Pick<Asset, "format">) =>
+ getAssetTextEditorLanguage(asset) === "markdown";
+
+export const renderMarkdown = (source: string) =>
+ micromark(source, {
+ extensions: [gfm()],
+ htmlExtensions: [gfmHtml()],
+ });
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
index 0ec0cd6ef5..7f816bcbd8 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx
@@ -103,6 +103,7 @@ type FolderNavigationProps =
type AssetManagerProps = FolderNavigationProps & {
onChange?: (assetId: Asset["id"]) => void;
+ onOpen?: (assetId: Asset["id"]) => void;
/** acceptable file types in the `<input accept>` attribute format */
accept?: string;
canManageFolders?: boolean;
@@ -140,6 +141,7 @@ const getItemCountLabel = (count: number, qualifier?: string) =>
export const AssetManager = ({
accept = "*",
onChange,
+ onOpen,
folderId,
onFolderChange,
canManageFolders = false,
@@ -914,6 +916,7 @@ export const AssetManager = ({
}}
onKeyDown={handleShortcut}
autoScrollOnElementDrag={canManageFolders}
+ allowFolderDrop={canManageFolders}
contextMenu={
hasPanelContextMenuActions ? (
<AssetManagerItemContextMenuContent
@@ -997,6 +1000,11 @@ export const AssetManager = ({
onChange={(assetContainer) => {
onChange?.(assetContainer.asset.id);
}}
+ onOpen={
+ assetContainer.status === "uploaded" && onOpen !== undefined
+ ? () => onOpen(assetContainer.asset.id)
+ : undefined
+ }
selected={isItemSelected({
type: "asset",
id: assetContainer.asset.id,
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
index 653544d77a..6518358621 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx
@@ -1,3 +1,4 @@
+import { act } from "react-dom/test-utils";
import { afterEach, expect, test, vi } from "vitest";
import { TooltipProvider } from "@webstudio-is/design-system";
import type { Asset } from "@webstudio-is/sdk";
@@ -11,7 +12,8 @@ const assetBase = {
id: "asset",
projectId: "project",
size: 100,
- createdAt: "2026-01-01T00:00:00.000Z",
+ createdAt: "2026-01-15T12:00:00.000Z",
+ updatedAt: "2026-02-15T12:00:00.000Z",
} as const;
const createImageAsset = (values: Partial<ImageAsset> = {}): ImageAsset => ({
...assetBase,
@@ -86,6 +88,36 @@ test("uses an auto-growing textarea for the asset description", () => {
);
expect(settingsIndicator).toBeInstanceOf(HTMLElement);
expect(settingsIndicator?.className).toBe(thumbnailIndicator?.className);
+ expect(document.body.textContent).toContain("Created");
+ expect(document.body.textContent).toContain("Last modified");
+ expect(document.body.textContent).toContain("Jan 15, 2026");
+ expect(document.body.textContent).toContain("Feb 15, 2026");
+});
+
+test("closes asset settings before replacing an asset", () => {
+ const onOpenChange = vi.fn();
+ const onReplace = vi.fn();
+ renderer.render(
+ <TooltipProvider>
+ <AssetSettings
+ open
+ onOpenChange={onOpenChange}
+ onReplace={onReplace}
+ asset={createImageAsset()}
+ >
+ <button>Anchor</button>
+ </AssetSettings>
+ </TooltipProvider>
+ );
+
+ act(() => {
+ document
+ .querySelector<HTMLButtonElement>('[aria-label="Replace asset"]')
+ ?.click();
+ });
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onReplace).toHaveBeenCalledOnce();
});
test("keeps asset metadata read-only in View mode", () => {
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
index 42558a7ab7..460dfc9ba1 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx
@@ -101,6 +101,19 @@ const buttonLinkClass = css({
...textVariants.link,
}).toString();
+const dateTimeFormatter = new Intl.DateTimeFormat("en-US", {
+ dateStyle: "medium",
+ timeStyle: "short",
+});
+
+const formatDateTime = (date: string) => {
+ try {
+ return dateTimeFormatter.format(new Date(date));
+ } catch {
+ return date;
+ }
+};
+
const AssetUsagesList = ({ usages }: { usages: AssetUsage[] }) => {
const props = useStore($props);
const styles = useStore($styles);
@@ -413,6 +426,29 @@ const AssetSettingsContent = ({
</Grid>
</Box>
+ <Grid
+ columns={2}
+ css={{
+ padding: theme.panel.padding,
+ gridTemplateColumns: "auto 1fr",
+ columnGap: theme.spacing[5],
+ rowGap: theme.spacing[3],
+ }}
+ >
+ <Text variant="labels">Created</Text>
+ <Text variant="labels" align="right">
+ {formatDateTime(asset.createdAt)}
+ </Text>
+ {asset.updatedAt && (
+ <>
+ <Text variant="labels">Last modified</Text>
+ <Text variant="labels" align="right">
+ {formatDateTime(asset.updatedAt)}
+ </Text>
+ </>
+ )}
+ </Grid>
+
<Grid css={{ padding: theme.panel.padding, gap: 4 }}>
<Label htmlFor="asset-manager-filename">Name</Label>
<InputErrorsTooltip
@@ -606,6 +642,13 @@ export const AssetSettings = ({
onOpenChange(false);
onDelete();
};
+ const replaceAsset =
+ onReplace === undefined
+ ? undefined
+ : () => {
+ onOpenChange(false);
+ onReplace();
+ };
return (
<Popover modal open={open} onOpenChange={onOpenChange}>
{usages.length === 0 && (
@@ -622,7 +665,7 @@ export const AssetSettings = ({
asset={asset}
usages={usages}
onDelete={deleteAsset}
- onReplace={onReplace}
+ onReplace={replaceAsset}
focusName={focusName}
/>
</PopoverContent>
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx
index 4d9437058f..8aec11e38d 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx
@@ -238,6 +238,58 @@ describe("AssetThumbnail", () => {
expect(onOpen).toHaveBeenCalledTimes(2);
});
+ test("opens an asset from double click, keyboard, context, and dropdown actions", () => {
+ const onOpen = vi.fn();
+ const interactions = createInteractions();
+ const container = renderer.render(
+ <TooltipProvider>
+ {createUploadedAssetThumbnail({ interactions, onOpen })}
+ </TooltipProvider>
+ );
+ const card = container.querySelector<HTMLButtonElement>(
+ "[data-asset-manager-thumbnail-button]"
+ );
+
+ card?.click();
+ expect(onOpen).not.toHaveBeenCalled();
+
+ card?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+ expect(onOpen).toHaveBeenCalledOnce();
+
+ card?.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
+ );
+ expect(onOpen).toHaveBeenCalledTimes(2);
+
+ card?.dispatchEvent(
+ new MouseEvent("contextmenu", {
+ bubbles: true,
+ button: 2,
+ cancelable: true,
+ })
+ );
+ expect(interactions.onContextMenuActions).toHaveBeenCalledWith(
+ expect.objectContaining({ open: onOpen })
+ );
+
+ act(() => {
+ container
+ .querySelector<HTMLButtonElement>(
+ '[aria-label="Actions for document.pdf"]'
+ )
+ ?.dispatchEvent(
+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })
+ );
+ });
+ const open = Array.from(
+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')
+ ).find((item) => item.textContent === "Open");
+ expect(open).toBeDefined();
+
+ act(() => open?.click());
+ expect(onOpen).toHaveBeenCalledTimes(3);
+ });
+
describe.each([
{
variant: "folder",
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
index 35889f0955..5b9946caf2 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx
@@ -18,6 +18,7 @@ import {
FILE_EXTENSIONS_BY_CATEGORY,
IMAGE_MIME_TYPES,
detectAssetType,
+ isResizableImageFileName,
} from "@webstudio-is/sdk";
import type { MimeCategory } from "@webstudio-is/sdk";
import { draggable } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
@@ -118,6 +119,7 @@ type AssetThumbnailProps = {
assetContainer: AssetContainer;
interactions: AssetManagerThumbnailInteractions;
onChange?: (assetContainer: AssetContainer) => void;
+ onOpen?: () => void;
selected?: boolean;
forcedSelection?: boolean;
folderPath?: string;
@@ -131,6 +133,7 @@ export const AssetThumbnail = ({
assetContainer,
interactions,
onChange,
+ onOpen,
selected,
forcedSelection,
folderPath,
@@ -172,6 +175,7 @@ export const AssetThumbnail = ({
assetContainer.status === "uploading"
? {}
: {
+ open: onOpen,
settings: () => setSettingsOpen(true),
...(authPermit === "view"
? {}
@@ -241,7 +245,7 @@ export const AssetThumbnail = ({
}}
title={alt}
preview={
- assetType === "image" ? (
+ assetType === "image" && isResizableImageFileName(asset.name) ? (
<StyledWebstudioImage
assetId={asset.id}
name={asset.name}
@@ -269,9 +273,14 @@ export const AssetThumbnail = ({
labelSuffix={`.${ext}`}
path={folderPath}
onPreviewClick={() => onChange?.(assetContainer)}
+ onDoubleClick={onOpen}
onKeyDown={(event: KeyboardEvent) => {
- if (event.code === "Enter") {
- onChange?.(assetContainer);
+ if (event.key === "Enter") {
+ if (onOpen !== undefined) {
+ onOpen();
+ } else {
+ onChange?.(assetContainer);
+ }
}
}}
header={
diff --git a/apps/builder/app/builder/shared/assets/assets-shell.test.tsx b/apps/builder/app/builder/shared/assets/assets-shell.test.tsx
index 899a2a31f5..7f168724af 100644
--- a/apps/builder/app/builder/shared/assets/assets-shell.test.tsx
+++ b/apps/builder/app/builder/shared/assets/assets-shell.test.tsx
@@ -49,6 +49,16 @@ describe("AssetsShell", () => {
).toBe(true);
});
+ test("advertises folder drops only when folder management is enabled", () => {
+ const container = renderer.render(
+ <AssetsShell searchProps={{}} isEmpty type="file" allowFolderDrop>
+ <div />
+ </AssetsShell>
+ );
+
+ expect(container.textContent).toContain("Drop files or folders here");
+ });
+
test("opens its context menu from panel chrome outside the asset list", () => {
const container = renderer.render(
<AssetsShell
diff --git a/apps/builder/app/builder/shared/assets/assets-shell.tsx b/apps/builder/app/builder/shared/assets/assets-shell.tsx
index 0324e1fed4..087abb94a8 100644
--- a/apps/builder/app/builder/shared/assets/assets-shell.tsx
+++ b/apps/builder/app/builder/shared/assets/assets-shell.tsx
@@ -14,6 +14,7 @@ import {
ScrollAreaNative,
SearchField,
theme,
+ toast,
} from "@webstudio-is/design-system";
import { autoScrollForElements } from "@atlaskit/pragmatic-drag-and-drop-auto-scroll/element";
import {
@@ -24,14 +25,19 @@ import {
import { AssetPanelState } from "./asset-panel-state";
import { Separator } from "./separator";
import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";
-import {
- containsFiles,
- getFiles,
-} from "@atlaskit/pragmatic-drag-and-drop/external/file";
+import { containsFiles } from "@atlaskit/pragmatic-drag-and-drop/external/file";
import { dropTargetForExternal } from "@atlaskit/pragmatic-drag-and-drop/external/adapter";
import invariant from "tiny-invariant";
import type { ContainsSource } from "@atlaskit/pragmatic-drag-and-drop/dist/types/public-utils/external/native-types";
import { uploadAssets } from "./upload-assets";
+import {
+ createDroppedAssetFolderStructure,
+ readDroppedAssetItems,
+} from "./directory-drop";
+import { $assetFolders } from "~/shared/sync/data-stores";
+import { createAssetFolderHierarchy } from "@webstudio-is/sdk";
+import { executeRuntimeMutation } from "~/shared/instance-utils/data";
+import { onNextTransactionComplete } from "~/shared/sync/project-queue";
import {
IDLE,
isBlockedByBackdrop,
@@ -61,6 +67,7 @@ type AssetsShellProps = {
onKeyDown?: ComponentProps<typeof Flex>["onKeyDown"];
onElementChange?: (element: HTMLDivElement | null) => void;
autoScrollOnElementDrag?: boolean;
+ allowFolderDrop?: boolean;
};
const containsFilesOrUri = (parameter: ContainsSource) => {
@@ -72,11 +79,38 @@ const containsFilesOrUri = (parameter: ContainsSource) => {
const OVER = 2;
type DropTargetState = typeof IDLE | typeof OVER;
+const uploadDroppedFiles = ({
+ files,
+ type,
+ accept,
+ folderId,
+}: {
+ files: File[];
+ type: AssetType;
+ accept?: string;
+ folderId?: string;
+}) => {
+ const validFiles = validateFiles(files).filter((file) => {
+ if (acceptUploadType(type, accept, file)) {
+ return true;
+ }
+
+ console.warn(
+ `Unsupported file dropped for type=${type}, accept=${accept} and file.type=${file.type}, file.name=${file.name}`
+ );
+ return false;
+ });
+
+ for (const [detectedType, filesOfType] of groupFilesByAssetType(validFiles)) {
+ uploadAssets(detectedType, filesOfType, { folderId });
+ }
+};
+
export const AssetsShell = ({
filters,
searchProps,
isEmpty,
- emptyMessage = "Drop files here",
+ emptyMessage,
emptyContent,
children,
interactionOverlay,
@@ -88,6 +122,7 @@ export const AssetsShell = ({
onKeyDown,
onElementChange,
autoScrollOnElementDrag = false,
+ allowFolderDrop = false,
type,
accept,
}: AssetsShellProps) => {
@@ -97,6 +132,13 @@ export const AssetsShell = ({
useState<ExternalMonitorDragState>(IDLE);
const [dropTargetState, setDropTargetState] = useState<DropTargetState>(IDLE);
+ const dropMessage = allowFolderDrop
+ ? "Drop files or folders here"
+ : "Drop files here";
+ const dropDescription = allowFolderDrop
+ ? "Drop files or folders from your computer into this panel."
+ : "Drop files from anywhere into this panel.";
+ const resolvedEmptyMessage = emptyMessage ?? dropMessage;
useEffect(() => {
const element = listViewportRef.current;
@@ -163,7 +205,8 @@ export const AssetsShell = ({
setMonitorState(IDLE);
setDropTargetState(IDLE);
- const droppedUrls = await Promise.all(
+ const droppedItemsPromise = readDroppedAssetItems(source.items);
+ const droppedUrlsPromise = Promise.all(
source.items
.filter((item) => item.type === "text/uri-list")
.map(
@@ -173,33 +216,76 @@ export const AssetsShell = ({
)
)
);
+ try {
+ const [droppedItems, droppedUrls] = await Promise.all([
+ droppedItemsPromise,
+ droppedUrlsPromise,
+ ]);
+ let didCreateFolder = false;
+ const fileGroups = allowFolderDrop
+ ? await createDroppedAssetFolderStructure({
+ directories: droppedItems.directories,
+ parentFolderId: folderId,
+ getOrCreateFolder: (name, parentId) => {
+ const hierarchy = createAssetFolderHierarchy(
+ $assetFolders.get()
+ );
+ const existing = hierarchy.findByName({ name, parentId });
+ if (existing !== undefined) {
+ return existing.id;
+ }
+ didCreateFolder = true;
+ const result = executeRuntimeMutation({
+ id: "assetFolders.create",
+ input: { name, parentId },
+ });
+ if (result === undefined) {
+ throw new Error(
+ `Unable to create asset folder "${name}"`
+ );
+ }
+ return result.result.folderId;
+ },
+ })
+ : [];
- const droppedFiles = validateFiles(getFiles({ source }));
+ if (
+ allowFolderDrop === false &&
+ droppedItems.directories.length > 0
+ ) {
+ toast.error("Folder upload is only available in Assets.");
+ }
- const files = droppedFiles
- .filter((file) => file != null)
- .filter((file) => {
- if (acceptUploadType(type, accept, file)) {
- return true;
+ const uploadFolderFiles = () => {
+ for (const { files, folderId } of fileGroups) {
+ uploadDroppedFiles({
+ files,
+ type,
+ accept,
+ folderId,
+ });
}
+ };
+ if (didCreateFolder && fileGroups.length > 0) {
+ onNextTransactionComplete(uploadFolderFiles);
+ } else {
+ uploadFolderFiles();
+ }
- console.warn(
- `Unsupported file dropped for type=${type}, accept=${accept} and file.type=${file.type}, file.name=${file.name}`
- );
- return false;
+ uploadDroppedFiles({
+ files: droppedItems.files,
+ type,
+ accept,
+ folderId,
});
-
- for (const [detectedType, filesOfType] of groupFilesByAssetType(
- files
- )) {
- uploadAssets(detectedType, filesOfType, { folderId });
+ uploadAssets(type, droppedUrls, { folderId });
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : String(error));
}
-
- uploadAssets(type, droppedUrls, { folderId });
},
})
);
- }, [accept, containsByType, folderId, type]);
+ }, [accept, allowFolderDrop, containsByType, folderId, type]);
const dragState = Math.max(monitorState, dropTargetState);
@@ -244,12 +330,10 @@ export const AssetsShell = ({
{emptyContent}
<AssetPanelState
overlay={emptyContent !== undefined}
- message={emptyMessage}
+ message={resolvedEmptyMessage}
active={dragState === OVER}
description={
- emptyMessage === "Drop files here"
- ? "Drop files from anywhere into this panel."
- : undefined
+ emptyMessage === undefined ? dropDescription : undefined
}
/>
</Flex>
@@ -283,8 +367,8 @@ export const AssetsShell = ({
}}
>
<AssetPanelState
- message="Drop files here"
- description="Drop files from anywhere into this panel."
+ message={dropMessage}
+ description={dropDescription}
active={dragState === OVER}
/>
</Flex>
diff --git a/apps/builder/app/builder/shared/assets/directory-drop.test.ts b/apps/builder/app/builder/shared/assets/directory-drop.test.ts
new file mode 100644
index 0000000000..4952e4b646
--- /dev/null
+++ b/apps/builder/app/builder/shared/assets/directory-drop.test.ts
@@ -0,0 +1,118 @@
+import { expect, test, vi } from "vitest";
+import {
+ createDroppedAssetFolderStructure,
+ readDroppedAssetItems,
+ type DroppedAssetDirectory,
+} from "./directory-drop";
+
+const fileEntry = (file: File) =>
+ ({
+ name: file.name,
+ isFile: true,
+ isDirectory: false,
+ file: (success: FileCallback) => success(file),
+ }) as FileSystemFileEntry;
+
+const directoryEntry = (name: string, batches: readonly FileSystemEntry[][]) =>
+ ({
+ name,
+ isFile: false,
+ isDirectory: true,
+ createReader: () => {
+ let index = 0;
+ return {
+ readEntries: (success: FileSystemEntriesCallback) => {
+ success(batches[index] ?? []);
+ index += 1;
+ },
+ };
+ },
+ }) as FileSystemDirectoryEntry;
+
+const droppedItem = (entry: FileSystemEntry, standard = false) =>
+ ({
+ kind: "file",
+ type: "",
+ getAsFile: () => null,
+ webkitGetAsEntry: standard ? undefined : () => entry,
+ ...(standard ? { getAsEntry: () => entry } : {}),
+ }) as unknown as DataTransferItem;
+
+test("reads dropped files and complete nested directory hierarchies", async () => {
+ const direct = new File(["direct"], "direct.txt");
+ const markdown = new File(["# Home"], "index.md");
+ const logo = new File(["logo"], "logo.svg");
+ const images = directoryEntry("images", [[fileEntry(logo)], []]);
+ const empty = directoryEntry("empty", [[]]);
+ const site = directoryEntry("site", [
+ [fileEntry(markdown), images],
+ [empty],
+ [],
+ ]);
+
+ await expect(
+ readDroppedAssetItems([
+ droppedItem(fileEntry(direct), true),
+ droppedItem(site),
+ ])
+ ).resolves.toEqual({
+ files: [direct],
+ directories: [
+ {
+ name: "site",
+ files: [markdown],
+ directories: [
+ { name: "images", files: [logo], directories: [] },
+ { name: "empty", files: [], directories: [] },
+ ],
+ },
+ ],
+ });
+});
+
+test("falls back to regular files when directory entries are unavailable", async () => {
+ const file = new File(["content"], "file.txt");
+ const item = {
+ getAsFile: () => file,
+ webkitGetAsEntry: () => null,
+ } as unknown as DataTransferItem;
+
+ await expect(readDroppedAssetItems([item])).resolves.toEqual({
+ files: [file],
+ directories: [],
+ });
+});
+
+test("creates every folder before returning files grouped by destination", async () => {
+ const readme = new File(["readme"], "readme.md");
+ const logo = new File(["logo"], "logo.svg");
+ const directories: DroppedAssetDirectory[] = [
+ {
+ name: "site",
+ files: [readme],
+ directories: [
+ { name: "images", files: [logo], directories: [] },
+ { name: "empty", files: [], directories: [] },
+ ],
+ },
+ ];
+ const getOrCreateFolder = vi.fn(
+ async (name: string, parentId: string | undefined) =>
+ parentId === undefined ? name : `${parentId}/${name}`
+ );
+
+ await expect(
+ createDroppedAssetFolderStructure({
+ directories,
+ getOrCreateFolder,
+ })
+ ).resolves.toEqual([
+ { folderId: "site", files: [readme] },
+ { folderId: "site/images", files: [logo] },
+ ]);
+ expect(getOrCreateFolder.mock.calls).toEqual([
+ ["site", undefined],
+ ["images", "site"],
+ ["empty", "site"],
+ ]);
+});
diff --git a/apps/builder/app/builder/shared/assets/directory-drop.ts b/apps/builder/app/builder/shared/assets/directory-drop.ts
new file mode 100644
index 0000000000..3c9dd611e3
--- /dev/null
+++ b/apps/builder/app/builder/shared/assets/directory-drop.ts
@@ -0,0 +1,118 @@
+export type DroppedAssetDirectory = {
+ name: string;
+ files: File[];
+ directories: DroppedAssetDirectory[];
+};
+
+export type DroppedAssetItems = {
+ files: File[];
+ directories: DroppedAssetDirectory[];
+};
+
+type DataTransferItemWithEntry = DataTransferItem & {
+ getAsEntry?: () => FileSystemEntry | null;
+};
+
+const getEntry = (item: DataTransferItem) => {
+ const itemWithEntry = item as DataTransferItemWithEntry;
+ return itemWithEntry.getAsEntry?.() ?? item.webkitGetAsEntry?.();
+};
+
+const readFileEntry = (entry: FileSystemFileEntry) =>
+ new Promise<File>((resolve, reject) => entry.file(resolve, reject));
+
+const readDirectoryEntries = async (entry: FileSystemDirectoryEntry) => {
+ const reader = entry.createReader();
+ const entries: FileSystemEntry[] = [];
+ while (true) {
+ const batch = await new Promise<FileSystemEntry[]>((resolve, reject) =>
+ reader.readEntries(resolve, reject)
+ );
+ if (batch.length === 0) {
+ return entries;
+ }
+ entries.push(...batch);
+ }
+};
+
+const readDirectoryEntry = async (
+ entry: FileSystemDirectoryEntry
+): Promise<DroppedAssetDirectory> => {
+ const children = await readDirectoryEntries(entry);
+ const files: File[] = [];
+ const directories: DroppedAssetDirectory[] = [];
+ for (const child of children) {
+ if (child.isFile) {
+ files.push(await readFileEntry(child as FileSystemFileEntry));
+ continue;
+ }
+ if (child.isDirectory) {
+ directories.push(
+ await readDirectoryEntry(child as FileSystemDirectoryEntry)
+ );
+ }
+ }
+ return { name: entry.name, files, directories };
+};
+
+export const readDroppedAssetItems = async (
+ items: readonly DataTransferItem[]
+): Promise<DroppedAssetItems> => {
+ const files: File[] = [];
+ const directories: DroppedAssetDirectory[] = [];
+
+ for (const item of items) {
+ const entry = getEntry(item);
+ if (entry?.isDirectory) {
+ directories.push(
+ await readDirectoryEntry(entry as FileSystemDirectoryEntry)
+ );
+ continue;
+ }
+ if (entry?.isFile) {
+ files.push(await readFileEntry(entry as FileSystemFileEntry));
+ continue;
+ }
+ const file = item.getAsFile();
+ if (file !== null) {
+ files.push(file);
+ }
+ }
+
+ return { files, directories };
+};
+
+export type DroppedAssetFileGroup = {
+ folderId: string;
+ files: File[];
+};
+
+export const createDroppedAssetFolderStructure = async ({
+ directories,
+ parentFolderId,
+ getOrCreateFolder,
+}: {
+ directories: readonly DroppedAssetDirectory[];
+ parentFolderId?: string;
+ getOrCreateFolder: (
+ name: string,
+ parentId: string | undefined
+ ) => string | Promise<string>;
+}): Promise<DroppedAssetFileGroup[]> => {
+ const groups: DroppedAssetFileGroup[] = [];
+ const createDirectories = async (
+ children: readonly DroppedAssetDirectory[],
+ parentId: string | undefined
+ ) => {
+ for (const directory of children) {
+ const folderId = await getOrCreateFolder(directory.name, parentId);
+ if (directory.files.length > 0) {
+ groups.push({ folderId, files: directory.files });
+ }
+ await createDirectories(directory.directories, folderId);
+ }
+ };
+
+ await createDirectories(directories, parentFolderId);
+ return groups;
+};
diff --git a/apps/builder/app/builder/shared/assets/index.ts b/apps/builder/app/builder/shared/assets/index.ts
index cad53f2caf..67dddfe1ce 100644
--- a/apps/builder/app/builder/shared/assets/index.ts
+++ b/apps/builder/app/builder/shared/assets/index.ts
@@ -2,6 +2,7 @@ export { useAssets } from "./use-assets";
export * from "./delete-assets";
export { replaceAsset } from "./replace-asset";
export { uploadAssets } from "./upload-assets";
+export { updateAssetContent } from "./update-asset-content";
export * from "./types";
export * from "./separator";
export * from "./assets-shell";
diff --git a/apps/builder/app/builder/shared/assets/replace-asset.test.ts b/apps/builder/app/builder/shared/assets/replace-asset.test.ts
new file mode 100644
index 0000000000..d6c006c083
--- /dev/null
+++ b/apps/builder/app/builder/shared/assets/replace-asset.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, expect, test } from "vitest";
+import type { Asset } from "@webstudio-is/sdk";
+import { $uploadingFilesDataStore } from "~/shared/nano-states";
+import { $assets } from "~/shared/sync/data-stores";
+import { __testing__ } from "./replace-asset";
+
+const { waitForAsset } = __testing__;
+
+const asset = {
+ id: "replacement",
+ type: "file",
+ name: "data_hash.json",
+ format: "json",
+ projectId: "project",
+ size: 2,
+ createdAt: "",
+ meta: {},
+} satisfies Asset;
+
+beforeEach(() => {
+ $assets.set(new Map());
+ $uploadingFilesDataStore.set([]);
+});
+
+test("resolves an existing replacement asset", async () => {
+ $assets.set(new Map([[asset.id, asset]]));
+
+ await expect(waitForAsset(asset.id)).resolves.toBe(asset);
+});
+
+test("waits for a replacement asset to finish uploading", async () => {
+ $uploadingFilesDataStore.set([{ assetId: asset.id } as never]);
+ const result = waitForAsset(asset.id);
+
+ $assets.set(new Map([[asset.id, asset]]));
+
+ await expect(result).resolves.toBe(asset);
+});
+
+test("rejects when a replacement upload fails", async () => {
+ $uploadingFilesDataStore.set([{ assetId: asset.id } as never]);
+ const result = waitForAsset(asset.id);
+
+ $uploadingFilesDataStore.set([]);
+
+ await expect(result).rejects.toThrow("Failed to upload replacement asset");
+});
diff --git a/apps/builder/app/builder/shared/assets/replace-asset.ts b/apps/builder/app/builder/shared/assets/replace-asset.ts
index 3b314b10c5..1c6be26e23 100644
--- a/apps/builder/app/builder/shared/assets/replace-asset.ts
+++ b/apps/builder/app/builder/shared/assets/replace-asset.ts
@@ -1,6 +1,7 @@
import type { Asset } from "@webstudio-is/sdk";
import { toast } from "@webstudio-is/design-system";
import { $assets } from "~/shared/sync/data-stores";
+import { $uploadingFilesDataStore } from "~/shared/nano-states";
import { onNextTransactionComplete } from "~/shared/sync/project-queue";
import { invalidateAssets } from "~/shared/resources";
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
@@ -12,7 +13,7 @@ import { uploadAssets } from "./upload-assets";
* 1. Uploads the new file via the existing upload pipeline
* 2. Waits for the upload to complete (new asset appears in $assets)
* 3. Re-points all references (props, styles, page meta) from old → new asset
- * 4. Copies filename & description from old asset to new asset
+ * 4. Copies the description from the old asset to the new asset
* 5. Deletes the old asset
*/
export const replaceAsset = async (
@@ -25,7 +26,9 @@ export const replaceAsset = async (
return;
}
- const fileToAssetId = await uploadAssets("image", [file]);
+ const fileToAssetId = await uploadAssets("image", [file], {
+ folderId: oldAsset.folderId,
+ });
const newAssetId = fileToAssetId.get(file);
if (!newAssetId) {
@@ -33,12 +36,30 @@ export const replaceAsset = async (
return;
}
- await waitForAsset(newAssetId);
+ try {
+ await waitForAsset(newAssetId);
+ } catch {
+ return;
+ }
- executeRuntimeMutation({
- id: "assets.replace",
- input: { fromAssetId: oldAssetId, toAssetId: newAssetId },
- });
+ try {
+ const result = executeRuntimeMutation({
+ id: "assets.replace",
+ input: { fromAssetId: oldAssetId, toAssetId: newAssetId },
+ });
+ if (result === undefined) {
+ throw new Error("Asset replacement is not permitted");
+ }
+ } catch (error) {
+ executeRuntimeMutation({
+ id: "assets.delete",
+ input: { assetIdsOrPrefixes: [newAssetId], force: true },
+ });
+ toast.error(
+ error instanceof Error ? error.message : "Failed to replace asset"
+ );
+ return;
+ }
onNextTransactionComplete(() => {
invalidateAssets();
@@ -54,14 +75,32 @@ const waitForAsset = (assetId: string): Promise<Asset> => {
return Promise.resolve(existingAsset);
}
- // Use .listen() instead of .subscribe(), so the `unsubscribe` variable is always assigned before the callback runs.
- return new Promise((resolve) => {
- const unsubscribe = $assets.listen((assets) => {
+ return new Promise((resolve, reject) => {
+ const cleanup = () => {
+ unsubscribeAssets();
+ unsubscribeUploads();
+ };
+ const check = () => {
+ const assets = $assets.get();
const asset = assets.get(assetId);
if (asset !== undefined) {
- unsubscribe();
+ cleanup();
resolve(asset);
+ return;
}
- });
+
+ const isUploading = $uploadingFilesDataStore
+ .get()
+ .some((fileData) => fileData.assetId === assetId);
+ if (isUploading === false) {
+ cleanup();
+ reject(new Error("Failed to upload replacement asset"));
+ }
+ };
+ const unsubscribeAssets = $assets.listen(check);
+ const unsubscribeUploads = $uploadingFilesDataStore.listen(check);
+ check();
});
};
+
+export const __testing__ = { waitForAsset };
diff --git a/apps/builder/app/builder/shared/assets/update-asset-content.test.ts b/apps/builder/app/builder/shared/assets/update-asset-content.test.ts
new file mode 100644
index 0000000000..8be626de7a
--- /dev/null
+++ b/apps/builder/app/builder/shared/assets/update-asset-content.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { updateProjectAssetContent } from "@webstudio-is/http-client";
+import { $authToken } from "~/shared/nano-states";
+import { $project } from "~/shared/sync/data-stores";
+import { createUpdateAssetContent } from "./update-asset-content";
+
+const requestContentUpdate = vi.fn<typeof updateProjectAssetContent>();
+const commitUpdatedAsset = vi.fn();
+const updateAssetContent = createUpdateAssetContent({
+ requestContentUpdate,
+ commitUpdatedAsset,
+});
+
+const asset = {
+ id: "asset",
+ projectId: "project",
+ name: "settings_old.json",
+ format: "json",
+ size: 2,
+ type: "file" as const,
+ meta: {},
+ createdAt: "2026-01-01T00:00:00.000Z",
+};
+
+beforeEach(() => {
+ requestContentUpdate.mockReset();
+ commitUpdatedAsset.mockReset();
+ $project.set({ id: "project" } as never);
+ $authToken.set("token");
+});
+
+afterEach(() => {
+ $project.set(undefined);
+ $authToken.set(undefined);
+});
+
+test("commits a content revision without changing the asset id", async () => {
+ const revision = {
+ ...asset,
+ name: "settings_new.json",
+ size: 7,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ };
+ requestContentUpdate.mockResolvedValue({ asset: revision });
+
+ await expect(
+ updateAssetContent({ asset, content: '{"a":1}' })
+ ).resolves.toEqual(revision);
+
+ expect(requestContentUpdate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ assetId: "asset",
+ projectId: "project",
+ expectedName: "settings_old.json",
+ authToken: "token",
+ requestOrigin: window.location.origin,
+ })
+ );
+ await expect(
+ requestContentUpdate.mock.calls[0]?.[0].readAssetData()
+ ).resolves.toBe('{"a":1}');
+ expect(commitUpdatedAsset).toHaveBeenCalledWith(revision);
+});
+
+test("does not commit a conflicting revision", async () => {
+ requestContentUpdate.mockRejectedValue(new Error("File changed"));
+
+ await expect(updateAssetContent({ asset, content: "stale" })).rejects.toThrow(
+ "File changed"
+ );
+ expect(commitUpdatedAsset).not.toHaveBeenCalled();
+});
diff --git a/apps/builder/app/builder/shared/assets/update-asset-content.ts b/apps/builder/app/builder/shared/assets/update-asset-content.ts
new file mode 100644
index 0000000000..a753e69b98
--- /dev/null
+++ b/apps/builder/app/builder/shared/assets/update-asset-content.ts
@@ -0,0 +1,66 @@
+import type { Asset } from "@webstudio-is/sdk";
+import { updateProjectAssetContent } from "@webstudio-is/http-client";
+import { fetch } from "~/shared/fetch.client";
+import { $authToken } from "~/shared/nano-states";
+import { $project } from "~/shared/sync/data-stores";
+import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";
+import { getWebstudioData } from "~/shared/instance-utils/data";
+import { invalidateAssets } from "~/shared/resources";
+import { onNextTransactionComplete } from "~/shared/sync/project-queue";
+
+type UpdateAssetContentDependencies = {
+ requestContentUpdate: typeof updateProjectAssetContent;
+ commitUpdatedAsset: (asset: Asset) => void;
+};
+
+export const createUpdateAssetContent =
+ (dependencies: UpdateAssetContentDependencies) =>
+ async ({
+ asset,
+ content,
+ }: {
+ asset: Asset;
+ content: string;
+ }): Promise<Asset> => {
+ const projectId = $project.get()?.id;
+ if (projectId === undefined) {
+ throw new Error("Project not found");
+ }
+
+ const origin = window.location.origin;
+ const { asset: updatedAsset } = await dependencies.requestContentUpdate({
+ assetId: asset.id,
+ projectId,
+ expectedName: asset.name,
+ origin,
+ authToken: $authToken.get(),
+ readAssetData: async () => content,
+ request: fetch,
+ requestOrigin: origin,
+ });
+
+ dependencies.commitUpdatedAsset(updatedAsset);
+ return updatedAsset;
+ };
+
+export const updateAssetContent = createUpdateAssetContent({
+ requestContentUpdate: updateProjectAssetContent,
+ commitUpdatedAsset: (updatedAsset) => {
+ createTransactionFromBuilderPatchPayload({
+ data: getWebstudioData(),
+ payload: [
+ {
+ namespace: "assets",
+ patches: [
+ {
+ op: "replace",
+ path: [updatedAsset.id],
+ value: updatedAsset,
+ },
+ ],
+ },
+ ],
+ });
+ onNextTransactionComplete(invalidateAssets);
+ },
+});
diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsx
index 88d90e92dc..d2f414c195 100644
--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx
+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx
@@ -355,8 +355,8 @@ const processUpload = async (
fileData.source === "file" ? fileData.file : new URL(fileData.url),
onCompleted: (data) => {
URL.revokeObjectURL(fileData.objectURL);
- deleteUploadingFileData(assetId);
handleAfterSubmit(assetId, data, projectId, fileData.folderId);
+ deleteUploadingFileData(assetId);
},
onError: (error) => {
URL.revokeObjectURL(fileData.objectURL);
diff --git a/apps/builder/app/builder/shared/assets/use-assets-hook.test.tsx b/apps/builder/app/builder/shared/assets/use-assets-hook.test.tsx
new file mode 100644
index 0000000000..facfc8a603
--- /dev/null
+++ b/apps/builder/app/builder/shared/assets/use-assets-hook.test.tsx
@@ -0,0 +1,53 @@
+import { createRoot } from "react-dom/client";
+import { act } from "react-dom/test-utils";
+import { afterEach, expect, test } from "vitest";
+import type { Asset } from "@webstudio-is/sdk";
+import { $uploadingFilesDataStore } from "~/shared/nano-states";
+import { $assets } from "~/shared/sync/data-stores";
+import type { AssetContainer } from "./types";
+import { useAssets } from "./use-assets";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let renderedAssets: AssetContainer[] = [];
+
+const AssetsProbe = () => {
+ renderedAssets = useAssets().assetContainers;
+ return null;
+};
+
+const renderProbe = () => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() => root.render(<AssetsProbe />));
+ return () => act(() => root.unmount());
+};
+
+afterEach(() => {
+ $assets.set(new Map());
+ $uploadingFilesDataStore.set([]);
+ renderedAssets = [];
+});
+
+test("reads current assets when mounted after an in-place store update", () => {
+ $assets.set(new Map());
+ renderProbe()();
+
+ const asset: Asset = {
+ id: "image-id",
+ projectId: "project-id",
+ type: "image",
+ name: "image.png",
+ format: "png",
+ size: 1,
+ meta: { width: 1, height: 1 },
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+ $assets.get().set(asset.id, asset);
+
+ const unmount = renderProbe();
+ expect(renderedAssets.map(({ asset }) => asset.id)).toEqual([asset.id]);
+ unmount();
+});
diff --git a/apps/builder/app/builder/shared/assets/use-assets.tsx b/apps/builder/app/builder/shared/assets/use-assets.tsx
index 1971b25308..37054914b2 100644
--- a/apps/builder/app/builder/shared/assets/use-assets.tsx
+++ b/apps/builder/app/builder/shared/assets/use-assets.tsx
@@ -1,9 +1,11 @@
import { useMemo } from "react";
-import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import type { Asset } from "@webstudio-is/sdk";
+import type { Asset, Assets } from "@webstudio-is/sdk";
import { $assets } from "~/shared/sync/data-stores";
-import { $uploadingFilesDataStore } from "~/shared/nano-states";
+import {
+ $uploadingFilesDataStore,
+ type UploadingFileData,
+} from "~/shared/nano-states";
import type {
AssetContainer,
UploadedAssetContainer,
@@ -11,39 +13,39 @@ import type {
} from "./types";
import { uploadingFileDataToAsset } from "./asset-utils";
-const $assetContainers = computed(
- [$assets, $uploadingFilesDataStore],
- (assets, uploadingFilesData) => {
- const uploadingContainers: UploadingAssetContainer[] = [];
+const getAssetContainers = (
+ assets: Assets,
+ uploadingFilesData: UploadingFileData[]
+) => {
+ const uploadingContainers: UploadingAssetContainer[] = [];
- for (const uploadingFile of uploadingFilesData) {
- uploadingContainers.push({
- status: "uploading",
- objectURL: uploadingFile.objectURL,
- asset: uploadingFileDataToAsset(uploadingFile),
- });
- }
+ for (const uploadingFile of uploadingFilesData) {
+ uploadingContainers.push({
+ status: "uploading",
+ objectURL: uploadingFile.objectURL,
+ asset: uploadingFileDataToAsset(uploadingFile),
+ });
+ }
- const uploadedContainers: UploadedAssetContainer[] = [];
+ const uploadedContainers: UploadedAssetContainer[] = [];
- for (const asset of assets.values()) {
- uploadedContainers.push({
- status: "uploaded",
- asset,
- });
- }
+ for (const asset of assets.values()) {
+ uploadedContainers.push({
+ status: "uploaded",
+ asset,
+ });
+ }
- // sort newest uploaded assets first
- uploadedContainers.sort(
- (leftContainer, rightContainer) =>
- new Date(rightContainer.asset.createdAt).getTime() -
- new Date(leftContainer.asset.createdAt).getTime()
- );
+ // sort newest uploaded assets first
+ uploadedContainers.sort(
+ (leftContainer, rightContainer) =>
+ new Date(rightContainer.asset.createdAt).getTime() -
+ new Date(leftContainer.asset.createdAt).getTime()
+ );
- // put uploading assets first
- return [...uploadingContainers, ...uploadedContainers];
- }
-);
+ // put uploading assets first
+ return [...uploadingContainers, ...uploadedContainers];
+};
const filterByType = (
assetContainers: AssetContainer[],
@@ -58,7 +60,12 @@ const filterByType = (
};
export const useAssets = (type?: Asset["type"]) => {
- const assetContainers = useStore($assetContainers);
+ const assets = useStore($assets);
+ const uploadingFilesData = useStore($uploadingFilesDataStore);
+ const assetContainers = useMemo(
+ () => getAssetContainers(assets, uploadingFilesData),
+ [assets, uploadingFilesData]
+ );
const assetsByType = useMemo(() => {
return filterByType(assetContainers, type);
diff --git a/apps/builder/app/routes/rest.assets.$assetId.content.tsx b/apps/builder/app/routes/rest.assets.$assetId.content.tsx
new file mode 100644
index 0000000000..1967c5244e
--- /dev/null
+++ b/apps/builder/app/routes/rest.assets.$assetId.content.tsx
@@ -0,0 +1,66 @@
+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
+import {
+ AssetRevisionConflictError,
+ updateAssetContent,
+} from "@webstudio-is/asset-uploader/index.server";
+import type { Asset } from "@webstudio-is/sdk";
+import { createAssetClient } from "~/shared/asset-client";
+import { createContext } from "~/shared/context.server";
+import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
+import { checkCsrf } from "~/services/csrf-session.server";
+import { parseError } from "~/shared/error/error-parse";
+import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
+
+export type AssetContentActionResponse = { asset: Asset } | { errors: string };
+
+export const action = async ({ request, params }: ActionFunctionArgs) => {
+ preventCrossOriginCookie(request);
+ if (request.headers.has("x-auth-token") === false) {
+ await checkCsrf(request);
+ }
+
+ try {
+ if (request.method !== "PUT" || request.body === null) {
+ return json(
+ { errors: "Method not allowed" } satisfies AssetContentActionResponse,
+ { status: 405, headers: privateNoStoreResponseHeaders }
+ );
+ }
+ if (params.assetId === undefined) {
+ throw new Error("Asset id is required");
+ }
+
+ const url = new URL(request.url);
+ const projectId = url.searchParams.get("projectId");
+ const expectedName = url.searchParams.get("expectedName");
+ if (projectId === null || expectedName === null) {
+ throw new Error("Project id and expected asset name are required");
+ }
+
+ const context = await createContext(request);
+ const asset = await updateAssetContent(
+ {
+ assetId: params.assetId,
+ projectId,
+ expectedName,
+ data: request.body,
+ },
+ createAssetClient(),
+ context
+ );
+ return json({ asset } satisfies AssetContentActionResponse, {
+ headers: privateNoStoreResponseHeaders,
+ });
+ } catch (error) {
+ console.error(error);
+ return json(
+ {
+ errors: parseError(error).message,
+ } satisfies AssetContentActionResponse,
+ {
+ status: error instanceof AssetRevisionConflictError ? 409 : 400,
+ headers: privateNoStoreResponseHeaders,
+ }
+ );
+ }
+};
diff --git a/apps/builder/app/routes/rest.assets_.$name.tsx b/apps/builder/app/routes/rest.assets_.$name.tsx
index 7c8d0ddf7b..198637e63d 100644
--- a/apps/builder/app/routes/rest.assets_.$name.tsx
+++ b/apps/builder/app/routes/rest.assets_.$name.tsx
@@ -79,6 +79,8 @@ export const action = async (props: ActionFunctionArgs) => {
const url = new URL(request.url);
const projectId = url.searchParams.get("projectId");
const folderId = url.searchParams.get("folderId") ?? undefined;
+ const description =
+ request.headers.get("x-webstudio-asset-description") ?? undefined;
const rawAssetType = url.searchParams.get("type");
const isApiUpload = projectId !== null || rawAssetType !== null;
@@ -121,6 +123,7 @@ export const action = async (props: ActionFunctionArgs) => {
projectId,
type: assetType,
filename: params.name,
+ description,
folderId,
},
context
diff --git a/apps/builder/app/shared/code-editor-base.test.ts b/apps/builder/app/shared/code-editor-base.test.ts
index 321b81b6dd..4a2570beb9 100644
--- a/apps/builder/app/shared/code-editor-base.test.ts
+++ b/apps/builder/app/shared/code-editor-base.test.ts
@@ -1,6 +1,10 @@
import { EditorSelection } from "@codemirror/state";
import { expect, test } from "vitest";
-import { clampEditorSelection, normalizeEditorValue } from "./code-editor-base";
+import {
+ clampEditorSelection,
+ getTemplateInsertion,
+ normalizeEditorValue,
+} from "./code-editor-base";
test("clampEditorSelection preserves selection within document length", () => {
const selection = EditorSelection.create([
@@ -40,3 +44,33 @@ test("normalizeEditorValue defaults undefined to empty string", () => {
expect(normalizeEditorValue(undefined)).toBe("");
expect(normalizeEditorValue("value")).toBe("value");
});
+
+test("getTemplateInsertion wraps and selects existing text", () => {
+ const insertion = getTemplateInsertion({
+ from: 4,
+ selectedText: "selected",
+ prefix: "**",
+ suffix: "**",
+ placeholder: "bold text",
+ });
+
+ expect(insertion.text).toBe("**selected**");
+ expect([insertion.selection.anchor, insertion.selection.head]).toEqual([
+ 6, 14,
+ ]);
+});
+
+test("getTemplateInsertion inserts and selects a placeholder", () => {
+ const insertion = getTemplateInsertion({
+ from: 3,
+ selectedText: "",
+ prefix: "[",
+ suffix: "](https://)",
+ placeholder: "link text",
+ });
+
+ expect(insertion.text).toBe("[link text](https://)");
+ expect([insertion.selection.anchor, insertion.selection.head]).toEqual([
+ 4, 13,
+ ]);
+});
diff --git a/apps/builder/app/shared/code-editor-base.tsx b/apps/builder/app/shared/code-editor-base.tsx
index 561a568a4f..bde7f64efb 100644
--- a/apps/builder/app/shared/code-editor-base.tsx
+++ b/apps/builder/app/shared/code-editor-base.tsx
@@ -113,6 +113,10 @@ const editorContentStyle = css({
"&:focus-within": {
borderColor: theme.colors.borderFocus,
},
+ '&[data-border="hidden"]:not([data-invalid="true"]):is(:hover, :focus-within)':
+ {
+ borderColor: "transparent",
+ },
'&[data-invalid="true"]': {
borderColor: theme.colors.borderDestructiveMain,
outlineColor: theme.colors.borderDestructiveMain,
@@ -231,9 +235,38 @@ export const foldGutterExtension = foldGutter({
export type EditorApi = {
replaceSelection: (string: string) => void;
+ insertTemplate: (template: {
+ prefix: string;
+ suffix?: string;
+ placeholder: string;
+ }) => void;
focus: () => void;
};
+export const getTemplateInsertion = ({
+ from,
+ selectedText,
+ prefix,
+ suffix = "",
+ placeholder,
+}: {
+ from: number;
+ selectedText: string;
+ prefix: string;
+ suffix?: string;
+ placeholder: string;
+}) => {
+ const content = selectedText || placeholder;
+ const selectionFrom = from + prefix.length;
+ return {
+ text: `${prefix}${content}${suffix}`,
+ selection: EditorSelection.range(
+ selectionFrom,
+ selectionFrom + content.length
+ ),
+ };
+};
+
type EditorContentProps = {
editorApiRef?: RefObject<undefined | EditorApi>;
extensions?: Extension[];
@@ -241,6 +274,7 @@ type EditorContentProps = {
autoFocus?: boolean;
invalid?: boolean;
showShortcuts?: boolean;
+ showBorder?: boolean;
value?: string;
onChange: (value: string) => void;
onChangeComplete: (value: string) => void;
@@ -253,6 +287,7 @@ export const EditorContent = ({
autoFocus = false,
invalid = false,
showShortcuts = false,
+ showBorder = true,
value,
onChange,
onChangeComplete,
@@ -411,6 +446,25 @@ export const EditorContent = ({
view.dispatch(view.state.replaceSelection(string));
view.focus();
},
+ insertTemplate({ prefix, suffix, placeholder }) {
+ const view = viewRef.current;
+ if (view === undefined) {
+ return;
+ }
+ const { from, to } = view.state.selection.main;
+ const insertion = getTemplateInsertion({
+ from,
+ selectedText: view.state.doc.sliceString(from, to),
+ prefix,
+ suffix,
+ placeholder,
+ });
+ view.dispatch({
+ changes: { from, to, insert: insertion.text },
+ selection: insertion.selection,
+ });
+ view.focus();
+ },
focus() {
viewRef.current?.focus();
},
@@ -420,6 +474,7 @@ export const EditorContent = ({
<div
className={editorContentStyle()}
data-invalid={invalid}
+ data-border={showBorder ? undefined : "hidden"}
ref={editorRef}
>
{showShortcuts && (
@@ -470,6 +525,7 @@ export const EditorDialog = ({
placement = "center",
width = 640,
height = 480,
+ contentPadding = true,
...panelProps
}: {
title: ReactNode;
@@ -477,6 +533,7 @@ export const EditorDialog = ({
children: ReactNode;
width?: number;
height?: number;
+ contentPadding?: boolean;
placement?: ComponentProps<typeof FloatingPanel>["placement"];
resize?: ComponentProps<typeof FloatingPanel>["resize"];
open?: boolean;
@@ -494,7 +551,7 @@ export const EditorDialog = ({
<Grid
align="stretch"
css={{
- padding: theme.panel.padding,
+ padding: contentPadding ? theme.panel.padding : 0,
height: "100%",
overflow: "hidden",
boxSizing: "content-box",
diff --git a/apps/builder/app/shared/code-editor.tsx b/apps/builder/app/shared/code-editor.tsx
index aa46a6a64d..38055848af 100644
--- a/apps/builder/app/shared/code-editor.tsx
+++ b/apps/builder/app/shared/code-editor.tsx
@@ -5,6 +5,7 @@ import {
useEffect,
type ReactNode,
} from "react";
+import type { Extension } from "@codemirror/state";
import { styleTags, tags } from "@lezer/highlight";
import {
keymap,
@@ -59,6 +60,8 @@ const wrapperStyle = css({
},
});
+const noLanguageExtensions: Extension[] = [];
+
const getHtmlExtensions = () => [
highlightActiveLine(),
highlightSpecialChars(),
@@ -137,11 +140,21 @@ export const CodeEditor = forwardRef<
HTMLDivElement,
Omit<ComponentProps<typeof EditorContent>, "extensions"> & {
lang?: "html" | "json" | "markdown" | "css-properties";
+ languageExtensions?: Extension[];
title?: ReactNode;
size?: "default" | "small" | "full";
+ expandable?: boolean;
}
->(({ lang, title, size, ...editorContentProps }, ref) => {
- const extensions = useMemo(() => {
+>((props, ref) => {
+ const {
+ lang,
+ languageExtensions = noLanguageExtensions,
+ title,
+ size,
+ expandable = true,
+ ...editorContentProps
+ } = props;
+ const builtInExtensions = useMemo(() => {
if (lang === "html") {
return getHtmlExtensions();
}
@@ -167,6 +180,11 @@ export const CodeEditor = forwardRef<
return [];
}, [lang]);
+ const extensions = useMemo(
+ () => [...builtInExtensions, ...languageExtensions],
+ [builtInExtensions, languageExtensions]
+ );
+
const dialogExtensions = useMemo(
() => [...extensions, foldGutterExtension],
[extensions]
@@ -191,20 +209,24 @@ export const CodeEditor = forwardRef<
}, []);
return (
<div className={wrapperStyle({ size })} ref={ref}>
- <EditorDialogControl>
+ {expandable === false ? (
<EditorContent {...editorContentProps} extensions={extensions} />
- <EditorDialog
- title={title}
- content={
- <EditorContent
- {...editorContentProps}
- extensions={dialogExtensions}
- />
- }
- >
- <EditorDialogButton />
- </EditorDialog>
- </EditorDialogControl>
+ ) : (
+ <EditorDialogControl>
+ <EditorContent {...editorContentProps} extensions={extensions} />
+ <EditorDialog
+ title={title}
+ content={
+ <EditorContent
+ {...editorContentProps}
+ extensions={dialogExtensions}
+ />
+ }
+ >
+ <EditorDialogButton />
+ </EditorDialog>
+ </EditorDialogControl>
+ )}
</div>
);
});
diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.json
index 6887d5dc34..3e8cfd588f 100644
--- a/fixtures/react-router-cloudflare/.webstudio/data.json
+++ b/fixtures/react-router-cloudflare/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -475,6 +475,7 @@
"size": 999,
"name": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"createdAt": "2024-07-26T13:39:48.678+00:00",
+ "updatedAt": "2024-07-26T13:39:51.097+00:00",
"format": "svg",
"meta": {
"width": 14,
@@ -488,6 +489,7 @@
"size": 64701,
"name": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"createdAt": "2024-12-06T14:36:07.046+00:00",
+ "updatedAt": "2024-12-06T14:36:07.046+00:00",
"format": "jpg",
"meta": {
"width": 820,
diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.json
index 6887d5dc34..3e8cfd588f 100644
--- a/fixtures/react-router-docker/.webstudio/data.json
+++ b/fixtures/react-router-docker/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -475,6 +475,7 @@
"size": 999,
"name": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"createdAt": "2024-07-26T13:39:48.678+00:00",
+ "updatedAt": "2024-07-26T13:39:51.097+00:00",
"format": "svg",
"meta": {
"width": 14,
@@ -488,6 +489,7 @@
"size": 64701,
"name": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"createdAt": "2024-12-06T14:36:07.046+00:00",
+ "updatedAt": "2024-12-06T14:36:07.046+00:00",
"format": "jpg",
"meta": {
"width": 820,
diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.json
index 6887d5dc34..3e8cfd588f 100644
--- a/fixtures/react-router-netlify/.webstudio/data.json
+++ b/fixtures/react-router-netlify/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -475,6 +475,7 @@
"size": 999,
"name": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"createdAt": "2024-07-26T13:39:48.678+00:00",
+ "updatedAt": "2024-07-26T13:39:51.097+00:00",
"format": "svg",
"meta": {
"width": 14,
@@ -488,6 +489,7 @@
"size": 64701,
"name": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"createdAt": "2024-12-06T14:36:07.046+00:00",
+ "updatedAt": "2024-12-06T14:36:07.046+00:00",
"format": "jpg",
"meta": {
"width": 820,
diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.json
index 6887d5dc34..3e8cfd588f 100644
--- a/fixtures/react-router-vercel/.webstudio/data.json
+++ b/fixtures/react-router-vercel/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -475,6 +475,7 @@
"size": 999,
"name": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"createdAt": "2024-07-26T13:39:48.678+00:00",
+ "updatedAt": "2024-07-26T13:39:51.097+00:00",
"format": "svg",
"meta": {
"width": 14,
@@ -488,6 +489,7 @@
"size": 64701,
"name": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"createdAt": "2024-12-06T14:36:07.046+00:00",
+ "updatedAt": "2024-12-06T14:36:07.046+00:00",
"format": "jpg",
"meta": {
"width": 820,
diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
index 5cfc72569f..3bcf267907 100644
--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json
+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -473,6 +473,7 @@
"size": 999,
"name": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"createdAt": "2024-07-26T13:39:48.678+00:00",
+ "updatedAt": "2024-07-26T13:39:51.097+00:00",
"format": "svg",
"meta": {
"width": 14,
@@ -486,6 +487,7 @@
"size": 64701,
"name": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"createdAt": "2024-12-06T14:36:07.046+00:00",
+ "updatedAt": "2024-12-06T14:36:07.046+00:00",
"format": "jpg",
"meta": {
"width": 820,
diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
index 0e572d0bb8..8c72f92e80 100644
--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c",
"projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",
diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
index 5cfc72569f..3bcf267907 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
@@ -473,6 +473,7 @@
"size": 999,
"name": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"createdAt": "2024-07-26T13:39:48.678+00:00",
+ "updatedAt": "2024-07-26T13:39:51.097+00:00",
"format": "svg",
"meta": {
"width": 14,
@@ -486,6 +487,7 @@
"size": 64701,
"name": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"createdAt": "2024-12-06T14:36:07.046+00:00",
+ "updatedAt": "2024-12-06T14:36:07.046+00:00",
"format": "jpg",
"meta": {
"width": 820,
diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.json
index ecf38edc86..9355144767 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1h06fyv",
+ "bundleVersion": "bundle-1l6lbch",
"build": {
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
@@ -7227,6 +7227,7 @@
"size": 19680,
"name": "e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3",
"createdAt": "2026-01-14T01:59:48.958+00:00",
+ "updatedAt": "2026-01-14T01:59:48.958+00:00",
"format": "mp3",
"meta": {},
"type": "file"
@@ -7237,6 +7238,7 @@
"size": 901185,
"name": "webm-example_2r_6VmRBjhAy3ldaqz0gk.webm",
"createdAt": "2026-01-14T02:59:19.806+00:00",
+ "updatedAt": "2026-01-14T02:59:19.806+00:00",
"format": "webm",
"meta": {},
"type": "file"
@@ -7247,6 +7249,7 @@
"size": 268326,
"name": "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png",
"createdAt": "2025-06-20T17:59:02.94+00:00",
+ "updatedAt": "2025-06-20T17:59:02.94+00:00",
"format": "png",
"meta": {
"width": 790,
@@ -7260,6 +7263,7 @@
"size": 2906,
"name": "small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp",
"createdAt": "2023-09-12T09:44:22.12+00:00",
+ "updatedAt": "2023-09-12T09:44:24.24+00:00",
"format": "webp",
"meta": {
"width": 100,
@@ -7273,6 +7277,7 @@
"size": 170479,
"name": "video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4",
"createdAt": "2026-01-14T02:59:28.168+00:00",
+ "updatedAt": "2026-01-14T02:59:28.168+00:00",
"format": "mp4",
"meta": {},
"type": "file"
@@ -7283,6 +7288,7 @@
"size": 210614,
"name": "_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg",
"createdAt": "2023-09-06T11:28:43.031+00:00",
+ "updatedAt": "2023-09-06T11:28:46.868+00:00",
"format": "jpeg",
"meta": {
"width": 1024,
diff --git a/packages/asset-uploader/src/asset-patch-core.ts b/packages/asset-uploader/src/asset-patch-core.ts
index dcdfc2747c..195bc75565 100644
--- a/packages/asset-uploader/src/asset-patch-core.ts
+++ b/packages/asset-uploader/src/asset-patch-core.ts
@@ -7,6 +7,7 @@ import {
diffMaps,
type Patch,
} from "./patch-utils";
+import { swapAssetFileWithClient } from "./revision";
export const createAssetRows = (assets: Iterable<Asset>, projectId: string) =>
Array.from(assets, (asset) => ({
@@ -128,7 +129,7 @@ export const deleteAssetsWithClient = async (
};
/**
- * patchAssetsWithClient can only delete, add, or update asset metadata.
+ * Persists asset additions, deletions, metadata updates, and file revisions.
*/
export const patchAssetsWithClient = async (
{ projectId, client }: { projectId: string; client: Client },
@@ -150,6 +151,7 @@ export const patchAssetsWithClient = async (
assetsMap,
patchedAssets,
(previous, asset) =>
+ previous.name === asset.name &&
previous.filename === asset.filename &&
previous.description === asset.description &&
previous.folderId === asset.folderId
@@ -159,6 +161,21 @@ export const patchAssetsWithClient = async (
}
for (const asset of updated) {
+ const previous = assetsMap.get(asset.id);
+ if (previous === undefined) {
+ throw new Error(`Asset ${asset.id} was not loaded`);
+ }
+ if (previous.name !== asset.name) {
+ await swapAssetFileWithClient(
+ {
+ projectId,
+ assetId: asset.id,
+ expectedName: previous.name,
+ replacementName: asset.name,
+ },
+ client
+ );
+ }
const { filename, description, folderId } = asset;
const updatedAsset = await client
.from("Asset")
diff --git a/packages/asset-uploader/src/db/load.test.ts b/packages/asset-uploader/src/db/load.test.ts
index 6ef8ac8017..2be97d1946 100644
--- a/packages/asset-uploader/src/db/load.test.ts
+++ b/packages/asset-uploader/src/db/load.test.ts
@@ -40,6 +40,7 @@ const assetRow = {
description: null,
size: 12345,
createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-02-01T00:00:00.000Z",
meta: JSON.stringify({ width: 800, height: 600 }),
status: "UPLOADED",
},
@@ -65,6 +66,8 @@ describe("loadAssetsByProject (msw)", () => {
projectId: "proj-1",
type: "image",
meta: { width: 800, height: 600 },
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-02-01T00:00:00.000Z",
});
});
diff --git a/packages/asset-uploader/src/index.server.ts b/packages/asset-uploader/src/index.server.ts
index 35b7127fb0..490cc589ea 100644
--- a/packages/asset-uploader/src/index.server.ts
+++ b/packages/asset-uploader/src/index.server.ts
@@ -4,5 +4,6 @@ export * from "./delete";
export * from "./patch";
export * from "./asset-patch-core";
export * from "./folder-persistence";
+export * from "./revision";
export * from "./clients/fs/fs";
export * from "./clients/s3/s3";
diff --git a/packages/asset-uploader/src/patch.test.ts b/packages/asset-uploader/src/patch.test.ts
index 88b409b731..b082c9066c 100644
--- a/packages/asset-uploader/src/patch.test.ts
+++ b/packages/asset-uploader/src/patch.test.ts
@@ -1,4 +1,5 @@
import { describe, test, expect } from "vitest";
+import { http, HttpResponse } from "msw";
import {
createTestServer,
db,
@@ -329,6 +330,48 @@ describe("patchAssets (msw)", () => {
]);
});
+ test("atomically swaps an asset file while preserving its id", async () => {
+ const projectId = uid();
+ const localAssetRow = { ...assetRow, projectId };
+ let swapInput: unknown;
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => json([localAssetRow])),
+ db.patch("Asset", () =>
+ json({
+ filename: localAssetRow.filename,
+ description: localAssetRow.description,
+ folderId: null,
+ })
+ ),
+ http.post(
+ "http://test-postgrest/rpc/swap_asset_file",
+ async ({ request }) => {
+ swapInput = await request.json();
+ return HttpResponse.json("updated");
+ }
+ )
+ );
+
+ await patchAssetsWithClient(
+ { projectId, client: testContext.postgrest.client },
+ [
+ {
+ op: "replace",
+ path: ["asset-1", "name"],
+ value: "photo_revision.jpg",
+ },
+ ]
+ );
+
+ expect(swapInput).toEqual({
+ project_id: projectId,
+ asset_id: "asset-1",
+ expected_name: "photo.jpg",
+ replacement_name: "photo_revision.jpg",
+ });
+ });
+
test("persists moving an asset to root as null", async () => {
const projectId = uid();
const localAssetRow = { ...assetRow, projectId, folderId: "folder" };
diff --git a/packages/asset-uploader/src/revision.test.ts b/packages/asset-uploader/src/revision.test.ts
new file mode 100644
index 0000000000..31830da257
--- /dev/null
+++ b/packages/asset-uploader/src/revision.test.ts
@@ -0,0 +1,295 @@
+import { describe, expect, test } from "vitest";
+import { http, HttpResponse } from "msw";
+import {
+ createTestServer,
+ db,
+ empty,
+ json,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import {
+ __testing__,
+ AssetRevisionConflictError,
+ updateAssetContent,
+} from "./revision";
+
+const { getRevisionFilename } = __testing__;
+const server = createTestServer();
+
+const createContext = (): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId: "user-1" },
+ getOwnerPlanFeatures: async () => ({}),
+ }) as unknown as AppContext;
+
+const ownershipHandler = db.get("Project", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("userId")) {
+ return json({ id: url.searchParams.get("id")?.replace("eq.", "") });
+ }
+ return json(null);
+});
+
+const oldFile = {
+ name: "settings_old-revision.json",
+ format: "json",
+ size: 2,
+ description: null,
+ status: "UPLOADED",
+ isDeleted: false,
+ uploaderProjectId: "project",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ meta: "{}",
+};
+
+const assetRow = {
+ id: "asset",
+ projectId: "project",
+ name: oldFile.name,
+ filename: null,
+ description: "Settings",
+ folderId: "data",
+ file: oldFile,
+};
+
+describe("asset content revisions", () => {
+ test("keeps the display basename when generating revision keys", () => {
+ expect(
+ getRevisionFilename({
+ name: "settings_old-revision.json",
+ filename: null,
+ })
+ ).toBe("settings.json");
+ expect(
+ getRevisionFilename({
+ name: "settings_old-revision.json",
+ filename: "configuration",
+ })
+ ).toBe("configuration.json");
+ });
+
+ test("uploads an immutable revision and keeps the asset id", async () => {
+ let revisionName = "";
+ let swapInput: unknown;
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => json(assetRow)),
+ db.post("File", async ({ request }) => {
+ const input = (await request.json()) as { name: string };
+ revisionName = input.name;
+ expect(input).toMatchObject({
+ name: expect.stringMatching(/^settings_.+\.json$/),
+ status: "UPLOADING",
+ uploaderProjectId: "project",
+ createdAt: oldFile.createdAt,
+ });
+ return empty({ status: 201 });
+ }),
+ db.get("File", () =>
+ json({
+ ...oldFile,
+ name: revisionName,
+ format: "file",
+ status: "UPLOADING",
+ })
+ ),
+ db.patch("File", () =>
+ json({
+ ...oldFile,
+ name: revisionName,
+ size: 7,
+ updatedAt: "2026-07-18T00:00:01.000Z",
+ })
+ ),
+ http.post(
+ "http://test-postgrest/rpc/swap_asset_file",
+ async ({ request }) => {
+ swapInput = await request.json();
+ return HttpResponse.json("updated");
+ }
+ )
+ );
+
+ const asset = await updateAssetContent(
+ {
+ assetId: "asset",
+ projectId: "project",
+ expectedName: oldFile.name,
+ data: new Blob(['{"a":1}']).stream(),
+ },
+ {
+ uploadFile: async (name, type, data) => {
+ expect(name).toBe(revisionName);
+ expect(type).toBe("file");
+ expect(await new Response(data as ReadableStream).text()).toBe(
+ '{"a":1}'
+ );
+ return { format: "json", size: 7, meta: {} };
+ },
+ },
+ createContext()
+ );
+
+ expect(asset).toMatchObject({
+ id: "asset",
+ projectId: "project",
+ name: revisionName,
+ description: "Settings",
+ folderId: "data",
+ format: "json",
+ createdAt: oldFile.createdAt,
+ updatedAt: "2026-07-18T00:00:01.000Z",
+ });
+ expect(swapInput).toEqual({
+ project_id: "project",
+ asset_id: "asset",
+ expected_name: oldFile.name,
+ replacement_name: revisionName,
+ });
+ });
+
+ test("rejects a stale revision before uploading", async () => {
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => json({ ...assetRow, name: "settings_newer.json" }))
+ );
+
+ await expect(
+ updateAssetContent(
+ {
+ assetId: "asset",
+ projectId: "project",
+ expectedName: oldFile.name,
+ data: new Blob(["stale"]).stream(),
+ },
+ {
+ uploadFile: async () => {
+ throw new Error("upload should not run");
+ },
+ },
+ createContext()
+ )
+ ).rejects.toBeInstanceOf(AssetRevisionConflictError);
+ });
+
+ test("discards an uploaded revision when the atomic swap conflicts", async () => {
+ let assetLoadCount = 0;
+ let revisionName = "";
+ let discardedRevision = false;
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => {
+ assetLoadCount += 1;
+ return json(
+ assetLoadCount === 1
+ ? assetRow
+ : { ...assetRow, name: "settings_concurrent.json" }
+ );
+ }),
+ db.post("File", async ({ request }) => {
+ revisionName = ((await request.json()) as { name: string }).name;
+ return empty({ status: 201 });
+ }),
+ db.get("File", () =>
+ json({
+ ...oldFile,
+ name: revisionName,
+ format: "file",
+ status: "UPLOADING",
+ })
+ ),
+ db.patch("File", async ({ request }) => {
+ const input = (await request.json()) as { isDeleted?: boolean };
+ if (input.isDeleted === true) {
+ discardedRevision = true;
+ return empty({ status: 204 });
+ }
+ return json({
+ ...oldFile,
+ name: revisionName,
+ size: 7,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ });
+ }),
+ http.post("http://test-postgrest/rpc/swap_asset_file", () =>
+ HttpResponse.json("conflict")
+ )
+ );
+
+ await expect(
+ updateAssetContent(
+ {
+ assetId: "asset",
+ projectId: "project",
+ expectedName: oldFile.name,
+ data: new Blob(["updated"]).stream(),
+ },
+ {
+ uploadFile: async () => ({ format: "json", size: 7, meta: {} }),
+ },
+ createContext()
+ )
+ ).rejects.toBeInstanceOf(AssetRevisionConflictError);
+ expect(discardedRevision).toBe(true);
+ });
+
+ test("accepts a revision when the swap commits without a response", async () => {
+ let assetLoadCount = 0;
+ let revisionName = "";
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => {
+ assetLoadCount += 1;
+ return json(
+ assetLoadCount === 1 ? assetRow : { ...assetRow, name: revisionName }
+ );
+ }),
+ db.post("File", async ({ request }) => {
+ revisionName = ((await request.json()) as { name: string }).name;
+ return empty({ status: 201 });
+ }),
+ db.get("File", () =>
+ json({
+ ...oldFile,
+ name: revisionName,
+ format: "file",
+ status: "UPLOADING",
+ })
+ ),
+ db.patch("File", () =>
+ json({
+ ...oldFile,
+ name: revisionName,
+ format: "json",
+ size: 7,
+ createdAt: "2026-07-18T00:00:00.000Z",
+ })
+ ),
+ http.post("http://test-postgrest/rpc/swap_asset_file", () =>
+ HttpResponse.error()
+ )
+ );
+
+ await expect(
+ updateAssetContent(
+ {
+ assetId: "asset",
+ projectId: "project",
+ expectedName: oldFile.name,
+ data: new Blob(["updated"]).stream(),
+ },
+ {
+ uploadFile: async () => ({ format: "json", size: 7, meta: {} }),
+ },
+ createContext()
+ )
+ ).resolves.toMatchObject({
+ id: "asset",
+ name: expect.stringMatching(/^settings_.+\.json$/),
+ format: "json",
+ });
+ });
+});
diff --git a/packages/asset-uploader/src/revision.ts b/packages/asset-uploader/src/revision.ts
new file mode 100644
index 0000000000..f29c6f0c7b
--- /dev/null
+++ b/packages/asset-uploader/src/revision.ts
@@ -0,0 +1,209 @@
+import { basename, extname } from "node:path";
+import { isTextFileAsset, type Asset } from "@webstudio-is/sdk";
+import {
+ authorizeProject,
+ AuthorizationError,
+ type AppContext,
+} from "@webstudio-is/trpc-interface/index.server";
+import type { Client } from "@webstudio-is/postgrest/index.server";
+import type { AssetClient } from "./client";
+import { uploadFileData } from "./upload";
+import { getUniqueFilename } from "./utils/get-unique-filename";
+import { sanitizeS3Key } from "./utils/sanitize-s3-key";
+import { formatAsset } from "./utils/format-asset";
+import { assertPostgrestSuccess } from "./patch-utils";
+
+export class AssetRevisionConflictError extends Error {}
+
+const getRevisionFilename = ({
+ name,
+ filename,
+}: {
+ name: string;
+ filename: string | null;
+}) => {
+ const extension = extname(name);
+ const storedBasename = basename(name, extension);
+ const suffixAt = storedBasename.lastIndexOf("_");
+ const displayBasename =
+ filename ??
+ (suffixAt === -1 ? storedBasename : storedBasename.slice(0, suffixAt));
+ return sanitizeS3Key(`${displayBasename}${extension}`);
+};
+
+export const swapAssetFileWithClient = async (
+ {
+ projectId,
+ assetId,
+ expectedName,
+ replacementName,
+ }: {
+ projectId: string;
+ assetId: string;
+ expectedName: string;
+ replacementName: string;
+ },
+ client: Client
+) => {
+ const result = await client.rpc("swap_asset_file", {
+ project_id: projectId,
+ asset_id: assetId,
+ expected_name: expectedName,
+ replacement_name: replacementName,
+ });
+ assertPostgrestSuccess(result);
+ const { data } = result;
+ if (data === "conflict") {
+ throw new AssetRevisionConflictError(
+ "This file changed since it was opened. Reload it before saving again."
+ );
+ }
+ if (data === "not_found") {
+ throw new Error("Asset not found");
+ }
+ if (data === "invalid_revision") {
+ throw new Error("Asset revision is not available");
+ }
+ if (data !== "updated") {
+ throw new Error("Unable to update asset content");
+ }
+};
+
+const loadAsset = async ({
+ assetId,
+ projectId,
+ client,
+}: {
+ assetId: string;
+ projectId: string;
+ client: Client;
+}) => {
+ const result = await client
+ .from("Asset")
+ .select(
+ "id, projectId, name, filename, description, folderId, file:File!inner(*)"
+ )
+ .eq("id", assetId)
+ .eq("projectId", projectId)
+ .single();
+ assertPostgrestSuccess(result);
+ const { data } = result;
+ if (data === null || data.file === null) {
+ throw new Error("Asset not found");
+ }
+ return data;
+};
+
+export const updateAssetContent = async (
+ {
+ assetId,
+ projectId,
+ expectedName,
+ data,
+ }: {
+ assetId: Asset["id"];
+ projectId: string;
+ expectedName: string;
+ data: ReadableStream<Uint8Array>;
+ },
+ assetClient: AssetClient,
+ context: AppContext
+): Promise<Asset> => {
+ const canEdit = await authorizeProject.hasProjectPermit(
+ { projectId, permit: "edit" },
+ context
+ );
+ if (canEdit === false) {
+ throw new AuthorizationError(
+ "You don't have access to edit this project assets"
+ );
+ }
+
+ const currentAsset = await loadAsset({
+ assetId,
+ projectId,
+ client: context.postgrest.client,
+ });
+ if (currentAsset.name !== expectedName) {
+ throw new AssetRevisionConflictError(
+ "This file changed since it was opened. Reload it before saving again."
+ );
+ }
+ if (isTextFileAsset({ format: currentAsset.file.format }) === false) {
+ throw new Error("This asset is not an editable text file");
+ }
+
+ const revisionName = getUniqueFilename(
+ getRevisionFilename({
+ name: currentAsset.name,
+ filename: currentAsset.filename,
+ })
+ );
+ const insertedFile = await context.postgrest.client.from("File").insert({
+ name: revisionName,
+ status: "UPLOADING",
+ format: "file",
+ size: 0,
+ uploaderProjectId: projectId,
+ createdAt: currentAsset.file.createdAt,
+ });
+ assertPostgrestSuccess(insertedFile);
+
+ const file = await uploadFileData(
+ revisionName,
+ data,
+ assetClient,
+ context,
+ undefined,
+ async (name, { postgrest }) => {
+ const deletedFile = await postgrest.client
+ .from("File")
+ .delete()
+ .eq("name", name);
+ assertPostgrestSuccess(deletedFile);
+ }
+ );
+ const revision = formatAsset({
+ assetId: currentAsset.id,
+ projectId: currentAsset.projectId,
+ filename: currentAsset.filename,
+ description: currentAsset.description,
+ folderId: currentAsset.folderId,
+ file,
+ });
+
+ try {
+ await swapAssetFileWithClient(
+ {
+ projectId,
+ assetId,
+ expectedName,
+ replacementName: revisionName,
+ },
+ context.postgrest.client
+ );
+ } catch (error) {
+ try {
+ const current = await loadAsset({
+ assetId,
+ projectId,
+ client: context.postgrest.client,
+ });
+ if (current.name === revisionName) {
+ return revision;
+ }
+ const discardedRevision = await context.postgrest.client
+ .from("File")
+ .update({ isDeleted: true })
+ .eq("name", revisionName);
+ assertPostgrestSuccess(discardedRevision);
+ } catch (cleanupError) {
+ console.error("Unable to discard an asset revision", cleanupError);
+ }
+ throw error;
+ }
+
+ return revision;
+};
+
+export const __testing__ = { getRevisionFilename };
diff --git a/packages/asset-uploader/src/upload.test.ts b/packages/asset-uploader/src/upload.test.ts
index db388bcf82..40089df535 100644
--- a/packages/asset-uploader/src/upload.test.ts
+++ b/packages/asset-uploader/src/upload.test.ts
@@ -79,6 +79,7 @@ describe("createUploadTicket", () => {
id: "asset-1",
projectId: "project-1",
name: expect.stringMatching(/^photo_.+\.png$/),
+ description: "Campaign photo",
folderId: "campaign",
});
return empty({ status: 201 });
@@ -90,6 +91,7 @@ describe("createUploadTicket", () => {
projectId: "project-1",
type: "image/png",
filename: "photo.png",
+ description: "Campaign photo",
folderId: "campaign",
},
createContext(),
@@ -390,4 +392,47 @@ describe("uploadFile", () => {
expect(assetDeleted).toBe(false);
expect(fileDeleted).toBe(false);
});
+
+ test("cleans up an uploaded file without an uploader project", async () => {
+ let assetDeleted = false;
+ let fileDeleted = false;
+ const file = {
+ name: "orphan.txt",
+ format: "txt",
+ size: 6,
+ status: "UPLOADED",
+ uploaderProjectId: null,
+ isDeleted: false,
+ meta: "{}",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-01-01T00:00:00.000Z",
+ };
+ server.use(
+ db.get("File", () => json({ ...file, status: "UPLOADING" })),
+ db.patch("File", () => json(file)),
+ db.delete("Asset", () => {
+ assetDeleted = true;
+ return empty({ status: 204 });
+ }),
+ db.delete("File", () => {
+ fileDeleted = true;
+ return empty({ status: 204 });
+ })
+ );
+
+ await expect(
+ uploadFile(
+ file.name,
+ new Blob(["orphan"]).stream(),
+ {
+ uploadFile: async () => ({ format: "txt", size: 6, meta: {} }),
+ },
+ createContext(),
+ undefined
+ )
+ ).rejects.toThrow("File uploader project is missing");
+
+ expect(assetDeleted).toBe(true);
+ expect(fileDeleted).toBe(true);
+ });
});
diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.ts
index d592f7a5c0..8552ab36ba 100644
--- a/packages/asset-uploader/src/upload.ts
+++ b/packages/asset-uploader/src/upload.ts
@@ -6,6 +6,7 @@ import {
} from "@webstudio-is/trpc-interface/index.server";
import { nanoid } from "nanoid";
import type { Asset } from "@webstudio-is/sdk";
+import type { Database } from "@webstudio-is/postgrest/index.server";
import type { AssetClient } from "./client";
import { getUniqueFilename } from "./utils/get-unique-filename";
import { sanitizeS3Key } from "./utils/sanitize-s3-key";
@@ -15,6 +16,7 @@ type UploadData = {
projectId: string;
type: string;
filename: string;
+ description?: string;
folderId?: string;
};
@@ -31,12 +33,25 @@ export type UploadErrorCleanup = (
context: AppContext
) => Promise<void>;
+const cleanupUploadError = async (
+ name: string,
+ context: AppContext,
+ onUploadError?: UploadErrorCleanup
+) => {
+ if (onUploadError) {
+ await onUploadError(name, context);
+ return;
+ }
+ await context.postgrest.client.from("Asset").delete().eq("name", name);
+ await context.postgrest.client.from("File").delete().eq("name", name);
+};
+
export const createUploadTicket = async (
data: UploadData,
context: AppContext,
createId: () => Asset["id"] = nanoid
): Promise<UploadTicket> => {
- const { projectId, type, filename, folderId } = data;
+ const { projectId, type, filename, description, folderId } = data;
const canEdit = await authorizeProject.hasProjectPermit(
{ projectId, permit: "edit" },
context
@@ -121,6 +136,7 @@ export const createUploadTicket = async (
id: assetId,
projectId,
name,
+ description,
folderId,
});
if (assetInsert.error) {
@@ -140,7 +156,7 @@ export const createUploadTicket = async (
throw new Error("Unable to reserve asset upload.");
};
-export const uploadFile = async (
+export const uploadFileData = async (
name: string,
data: ReadableStream<Uint8Array>,
client: AssetClient,
@@ -149,7 +165,7 @@ export const uploadFile = async (
| { width: number; height: number; format: string }
| undefined,
onUploadError?: UploadErrorCleanup
-): Promise<Asset> => {
+): Promise<Database["public"]["Tables"]["File"]["Row"]> => {
let file = await context.postgrest.client
.from("File")
.select("*")
@@ -187,7 +203,33 @@ export const uploadFile = async (
if (file.data === null) {
throw Error("File not found");
}
- const projectId = file.data.uploaderProjectId;
+ return file.data;
+ } catch (error) {
+ await cleanupUploadError(name, context, onUploadError);
+ throw error;
+ }
+};
+
+export const uploadFile = async (
+ name: string,
+ data: ReadableStream<Uint8Array>,
+ client: AssetClient,
+ context: AppContext,
+ assetInfoFallback:
+ | { width: number; height: number; format: string }
+ | undefined,
+ onUploadError?: UploadErrorCleanup
+): Promise<Asset> => {
+ const file = await uploadFileData(
+ name,
+ data,
+ client,
+ context,
+ assetInfoFallback,
+ onUploadError
+ );
+ try {
+ const projectId = file.uploaderProjectId;
if (typeof projectId !== "string") {
throw Error("File uploader project is missing");
}
@@ -209,16 +251,10 @@ export const uploadFile = async (
filename: asset.data.filename,
description: asset.data.description,
folderId: asset.data.folderId,
- file: file.data,
+ file,
});
} catch (error) {
- if (onUploadError) {
- await onUploadError(name, context);
- } else {
- await context.postgrest.client.from("Asset").delete().eq("name", name);
- await context.postgrest.client.from("File").delete().eq("name", name);
- }
-
+ await cleanupUploadError(name, context, onUploadError);
throw error;
}
};
diff --git a/packages/asset-uploader/src/utils/format-asset.test.ts b/packages/asset-uploader/src/utils/format-asset.test.ts
index e0cb25f220..78d20e4fbd 100644
--- a/packages/asset-uploader/src/utils/format-asset.test.ts
+++ b/packages/asset-uploader/src/utils/format-asset.test.ts
@@ -18,6 +18,7 @@ describe("formatAsset", () => {
description: null,
size: 50000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({
family: "Inter",
style: "normal",
@@ -33,6 +34,8 @@ describe("formatAsset", () => {
type: "font",
format: "woff2",
size: 50000,
+ createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: {
family: "Inter",
style: "normal",
@@ -50,6 +53,7 @@ describe("formatAsset", () => {
description: null,
size: 100000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({
width: 1920,
height: 1080,
@@ -80,6 +84,7 @@ describe("formatAsset", () => {
description: null,
size: 5000000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({
width: 1920,
height: 1080,
@@ -107,6 +112,7 @@ describe("formatAsset", () => {
description: null,
size: 3000000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({
width: 1280,
height: 720,
@@ -134,6 +140,7 @@ describe("formatAsset", () => {
description: null,
size: 2000000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({}),
},
});
@@ -158,6 +165,7 @@ describe("formatAsset", () => {
description: null,
size: 500000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({}),
},
});
@@ -185,6 +193,7 @@ describe("formatAsset", () => {
description: null,
size: 100000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({}),
},
});
@@ -202,6 +211,7 @@ describe("formatAsset", () => {
description: null,
size: 50000,
createdAt: "2024-01-01T00:00:00Z",
+ updatedAt: "2024-01-02T00:00:00Z",
meta: JSON.stringify({}),
},
});
diff --git a/packages/asset-uploader/src/utils/format-asset.ts b/packages/asset-uploader/src/utils/format-asset.ts
index 7437eaec7b..edd565b14f 100644
--- a/packages/asset-uploader/src/utils/format-asset.ts
+++ b/packages/asset-uploader/src/utils/format-asset.ts
@@ -20,6 +20,7 @@ export const formatAsset = ({
description: string | null;
size: number;
createdAt: string;
+ updatedAt: string;
meta: string;
};
}): Asset => {
@@ -34,6 +35,7 @@ export const formatAsset = ({
folderId: folderId ?? undefined,
size: file.size,
createdAt: file.createdAt,
+ updatedAt: file.updatedAt,
};
if (isFont) {
diff --git a/packages/cli/src/asset-files.test.ts b/packages/cli/src/asset-files.test.ts
index d796582b94..01f96a1790 100644
--- a/packages/cli/src/asset-files.test.ts
+++ b/packages/cli/src/asset-files.test.ts
@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";
import type { Asset } from "@webstudio-is/sdk";
import {
createLocalAssetDataReader,
+ createLocalUpdateAssetContentInput,
getLocalAssetPath,
materializeAssetFile,
} from "./asset-files";
@@ -62,6 +63,48 @@ test("creates a local asset data reader", async () => {
).toBe("asset");
});
+test("creates asset content readers from inline content or a file", async () => {
+ await writeFile("content.json", '{"source":"file"}', "utf8");
+ const fromContent = createLocalUpdateAssetContentInput({
+ assetId: "asset",
+ expectedName: "content_old.json",
+ content: '{"source":"inline"}',
+ readFile,
+ });
+ const fromPath = createLocalUpdateAssetContentInput({
+ assetId: "asset",
+ expectedName: "content_old.json",
+ path: "content.json",
+ readFile,
+ });
+
+ await expect(fromContent.readAssetData()).resolves.toBe(
+ '{"source":"inline"}'
+ );
+ await expect(fromPath.readAssetData()).resolves.toEqual(
+ Buffer.from('{"source":"file"}')
+ );
+});
+
+test("requires exactly one asset content source", () => {
+ const base = {
+ assetId: "asset",
+ expectedName: "content_old.json",
+ readFile,
+ };
+
+ expect(() => createLocalUpdateAssetContentInput(base)).toThrow(
+ "requires exactly one"
+ );
+ expect(() =>
+ createLocalUpdateAssetContentInput({
+ ...base,
+ path: "content.json",
+ content: "content",
+ })
+ ).toThrow("requires exactly one");
+});
+
test("materializes asset files from the synced asset cache before fetching", async () => {
await mkdir(".webstudio/assets", { recursive: true });
await writeFile(".webstudio/assets/image.png", "synced", "utf8");
diff --git a/packages/cli/src/asset-files.ts b/packages/cli/src/asset-files.ts
index f83d2215df..af1def5e94 100644
--- a/packages/cli/src/asset-files.ts
+++ b/packages/cli/src/asset-files.ts
@@ -93,6 +93,32 @@ export const createLocalUploadAssetsInput = <Asset extends { name: string }>({
readAssetData: createLocalAssetDataReader(readFile, assetsDir),
});
+export const createLocalUpdateAssetContentInput = ({
+ assetId,
+ expectedName,
+ path,
+ content,
+ readFile,
+}: {
+ assetId: string;
+ expectedName: string;
+ path?: string;
+ content?: string;
+ readFile: (path: string) => Promise<unknown>;
+}) => {
+ if ((path === undefined) === (content === undefined)) {
+ throw new Error(
+ "update-asset-content requires exactly one of path or content."
+ );
+ }
+ return {
+ assetId,
+ expectedName,
+ readAssetData: async () =>
+ path === undefined ? content : await readFile(resolve(path)),
+ };
+};
+
const downloadUrlToFileOnce = async (url: string, filePath: string) => {
const tempFilePath = `${filePath}.tmp`;
let writableStream: ReturnType<typeof createWriteStream> | undefined;
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index 2d43e9bc87..868c9ebf28 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -938,3 +938,40 @@ test("adapts MCP upload assets input to public API upload input", () => {
});
expect(input).toHaveProperty("readAssetData", expect.any(Function));
});
+
+test("adapts MCP asset content input to the shared revision client", async () => {
+ const input = getMcpOperationInput("update-asset-content", {
+ assetId: "asset-id",
+ expectedName: "settings_hash.json",
+ content: '{"theme":"dark"}',
+ }) as {
+ assetId: string;
+ expectedName: string;
+ readAssetData: () => Promise<unknown>;
+ };
+
+ expect(input).toMatchObject({
+ assetId: "asset-id",
+ expectedName: "settings_hash.json",
+ });
+ await expect(input.readAssetData()).resolves.toBe('{"theme":"dark"}');
+});
+
+test("exposes asset content editing through MCP discovery", () => {
+ const tool = listProjectSessionMcpTools(publicApiOperations).find(
+ ({ name }) => name === "update-asset-content"
+ );
+
+ expect(tool).toMatchObject({
+ name: "update-asset-content",
+ inputSchema: {
+ required: ["assetId", "expectedName"],
+ properties: {
+ assetId: expect.any(Object),
+ expectedName: expect.any(Object),
+ path: expect.any(Object),
+ content: expect.any(Object),
+ },
+ },
+ });
+});
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 08fd18fd6d..5fd95f21bb 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -48,6 +48,7 @@ import {
import {
createLocalUploadAssetInput,
createLocalUploadAssetsInput,
+ createLocalUpdateAssetContentInput,
downloadAssetFile,
getLocalAssetPath,
} from "../asset-files";
@@ -183,6 +184,25 @@ const getMcpUploadAssetsInput = (input: unknown) => {
});
};
+const getMcpUpdateAssetContentInput = (input: unknown) => {
+ if (
+ isPlainRecord(input) === false ||
+ typeof input.assetId !== "string" ||
+ typeof input.expectedName !== "string"
+ ) {
+ throw new Error(
+ "update-asset-content requires assetId and expectedName strings."
+ );
+ }
+ return createLocalUpdateAssetContentInput({
+ assetId: input.assetId,
+ expectedName: input.expectedName,
+ path: typeof input.path === "string" ? input.path : undefined,
+ content: typeof input.content === "string" ? input.content : undefined,
+ readFile,
+ });
+};
+
type PersistedMcpCheckpoint = {
tool: string;
message: string;
@@ -284,6 +304,9 @@ const getMcpOperationInput = (command: string, input: unknown) => {
if (command === "upload-assets") {
return getMcpUploadAssetsInput(input);
}
+ if (command === "update-asset-content") {
+ return getMcpUpdateAssetContentInput(input);
+ }
return input;
};
diff --git a/packages/design-system/src/components/dialog.stories.tsx b/packages/design-system/src/components/dialog.stories.tsx
index bea701efb3..660156e011 100644
--- a/packages/design-system/src/components/dialog.stories.tsx
+++ b/packages/design-system/src/components/dialog.stories.tsx
@@ -99,6 +99,7 @@ export const WithMaximize = () => (
</DialogDescription>
</div>
<DialogTitle
+ maximizable
suffix={
<DialogTitleActions>
<DialogMaximize />
diff --git a/packages/design-system/src/components/dialog.test.ts b/packages/design-system/src/components/dialog.test.ts
index d407fee6e4..a6afb8e9ad 100644
--- a/packages/design-system/src/components/dialog.test.ts
+++ b/packages/design-system/src/components/dialog.test.ts
@@ -56,7 +56,7 @@ describe("calculateCenteredPosition", () => {
});
describe("calculateDialogStyle", () => {
- test("maximized dialog fills boundary", () => {
+ test("maximized dialog leaves space around the boundary", () => {
const bounds = { x: 100, y: 50, width: 800, height: 600 };
const style = calculateDialogStyle(bounds, {
isMaximized: true,
@@ -65,10 +65,12 @@ describe("calculateDialogStyle", () => {
});
expect(style).toEqual({
- top: 50,
- left: 100,
- width: 800,
- height: 600,
+ top: 70,
+ left: 120,
+ width: 760,
+ height: 560,
+ maxWidth: 760,
+ maxHeight: 560,
});
});
diff --git a/packages/design-system/src/components/dialog.tsx b/packages/design-system/src/components/dialog.tsx
index b129801124..1c98f3874b 100644
--- a/packages/design-system/src/components/dialog.tsx
+++ b/packages/design-system/src/components/dialog.tsx
@@ -26,6 +26,7 @@ import { Separator } from "./separator";
import { Text } from "./text";
const DIALOG_TITLE_HEIGHT = 40;
+const DIALOG_MAXIMIZED_MARGIN = 20;
export const DialogTrigger = Primitive.Trigger;
@@ -189,11 +190,20 @@ const calculateDialogStyle = (
} = options;
if (isMaximized) {
+ const horizontalMargin = Math.min(
+ DIALOG_MAXIMIZED_MARGIN,
+ bounds.width / 2
+ );
+ const verticalMargin = Math.min(DIALOG_MAXIMIZED_MARGIN, bounds.height / 2);
+ const maximizedWidth = bounds.width - horizontalMargin * 2;
+ const maximizedHeight = bounds.height - verticalMargin * 2;
return {
- top: bounds.y,
- left: bounds.x,
- width: bounds.width,
- height: bounds.height,
+ top: bounds.y + verticalMargin,
+ left: bounds.x + horizontalMargin,
+ width: maximizedWidth,
+ height: maximizedHeight,
+ maxWidth: maximizedWidth,
+ maxHeight: maximizedHeight,
};
}
@@ -647,15 +657,32 @@ const titleStyle = css({
export const DialogTitle = ({
children,
suffix,
+ maximizable = false,
+ onDoubleClick,
...rest
}: ComponentProps<typeof PanelTitle> & {
suffix?: ReactNode;
closeLabel?: string;
+ maximizable?: boolean;
}) => {
- const { draggable } = useContext(DialogContext);
+ const { draggable, isMaximized, setIsMaximized } = useContext(DialogContext);
return (
- <div className={titleSlotStyle()}>
+ <div
+ className={titleSlotStyle()}
+ onDoubleClick={(event) => {
+ onDoubleClick?.(event);
+ if (
+ event.defaultPrevented ||
+ maximizable === false ||
+ (event.target instanceof Element &&
+ event.target.closest("button, a, input, textarea, select"))
+ ) {
+ return;
+ }
+ setIsMaximized(isMaximized === false);
+ }}
+ >
<PanelTitle {...rest} suffix={suffix ?? <DialogClose />}>
<Primitive.Title asChild>
<Text
diff --git a/packages/design-system/src/components/floating-panel.tsx b/packages/design-system/src/components/floating-panel.tsx
index fdffdc08b8..5e3c980d5a 100644
--- a/packages/design-system/src/components/floating-panel.tsx
+++ b/packages/design-system/src/components/floating-panel.tsx
@@ -327,6 +327,7 @@ export const FloatingPanel = ({
{content}
{typeof title === "string" ? (
<DialogTitle
+ maximizable={maximizable}
suffix={
<DialogTitleActions>
{titleSuffix}
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index 8a5837d99e..4446e32db4 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -96,6 +96,7 @@ import {
rewriteCssVariableRefs,
updateDesignTokenStyles,
updateAssetFolder,
+ updateProjectAssetContent,
updateDomain,
updateBreakpoint,
updatePage,
@@ -1125,6 +1126,7 @@ test("uploads assets as binary requests", async () => {
type: "image",
name: "image.png",
filename: "image.png",
+ description: "Campaign photo",
folderId: "campaign",
format: "png",
size: 3,
@@ -1144,6 +1146,9 @@ test("uploads assets as binary requests", async () => {
expect(init.body).toBe(file);
expect(init.headers).toBeInstanceOf(Headers);
expect((init.headers as Headers).get("x-auth-token")).toBe("token");
+ expect((init.headers as Headers).get("x-webstudio-asset-description")).toBe(
+ "Campaign photo"
+ );
expect((init.headers as Headers).get("content-type")).toBe(
"application/octet-stream"
);
@@ -1302,6 +1307,7 @@ test("uploads project asset descriptors with local data readers", async () => {
name: "image.png",
type: "image",
format: "png",
+ description: "Campaign photo",
folderId: "campaign",
meta: { width: 10, height: 20 },
},
@@ -1334,6 +1340,93 @@ test("uploads project asset descriptors with local data readers", async () => {
}
});
+test("updates asset content through the stable asset revision endpoint", async () => {
+ const revision = {
+ ...createImageAssetFixture({ id: "asset-id", name: "old_hash.png" }),
+ type: "file" as const,
+ format: "json",
+ meta: {},
+ name: "new_hash.json",
+ };
+ const request = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ asset: revision }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ await expect(
+ updateProjectAssetContent({
+ ...apiParams,
+ assetId: "asset/id",
+ expectedName: "old_hash.json",
+ readAssetData: async () => '{"theme":"dark"}',
+ request,
+ })
+ ).resolves.toEqual({ asset: revision });
+
+ const [url, init] = request.mock.calls[0] as unknown as [URL, RequestInit];
+ expect(url.pathname).toBe("/rest/assets/asset%2Fid/content");
+ expect(url.searchParams.get("projectId")).toBe(apiParams.projectId);
+ expect(url.searchParams.get("expectedName")).toBe("old_hash.json");
+ expect(init).toMatchObject({ method: "PUT", body: '{"theme":"dark"}' });
+ expect(new Headers(init.headers).get("x-auth-token")).toBe(
+ apiParams.authToken
+ );
+});
+
+test("surfaces asset content revision conflicts", async () => {
+ const request = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ errors: "File changed" }), {
+ status: 409,
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ await expect(
+ updateProjectAssetContent({
+ ...apiParams,
+ assetId: "asset-id",
+ expectedName: "old_hash.json",
+ readAssetData: async () => "stale",
+ request,
+ })
+ ).rejects.toMatchObject({ message: "File changed", status: 409 });
+});
+
+test("keeps browser asset content updates on the requested origin", async () => {
+ const revision = {
+ ...createImageAssetFixture({ id: "asset-id" }),
+ type: "file" as const,
+ format: "md",
+ meta: {},
+ };
+ const request = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ asset: revision }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ await updateProjectAssetContent({
+ ...apiParams,
+ origin:
+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-vite.wstd.dev:5175",
+ requestOrigin:
+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-vite.wstd.dev:5175",
+ assetId: "asset-id",
+ expectedName: "readme_hash.md",
+ readAssetData: async () => "# Readme",
+ request,
+ });
+
+ const [url] = request.mock.calls[0] as unknown as [URL];
+ expect(url.origin).toBe(
+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-vite.wstd.dev:5175"
+ );
+});
+
test("normalizes synced project bundles for local storage", () => {
const bundle = createPublishedProjectBundleFixture({
bundleVersion: "bundle-old",
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index aea1a6bff4..a6d4f6b094 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -322,6 +322,7 @@ const formatMebibytes = (bytes: number) =>
type Asset = PublishedProjectBundle["assets"][number];
type BinaryAssetData = Blob | ArrayBuffer | ArrayBufferView<ArrayBuffer>;
+type AssetContentData = BinaryAssetData | string;
type AssetUpload = {
asset: Asset;
@@ -398,6 +399,7 @@ export const uploadAsset = async (
headers: createHeaders({
...headers,
"x-auth-token": authToken,
+ "x-webstudio-asset-description": upload.asset.description ?? undefined,
"content-type": "application/octet-stream",
}),
}
@@ -567,6 +569,46 @@ export const uploadProjectAssets = async (
return { uploaded };
};
+type AssetContentUpdateResult =
+ | { asset: Asset }
+ | {
+ errors: string;
+ };
+
+export const updateProjectAssetContent = async (
+ params: Omit<AuthProjectParams, "authToken"> & {
+ authToken?: string;
+ assetId: string;
+ expectedName: string;
+ readAssetData: () => Promise<AssetContentData>;
+ request?: typeof fetch;
+ requestOrigin?: string;
+ }
+): Promise<{ asset: Asset }> => {
+ const request = params.request ?? fetch;
+ const { sourceOrigin } = parseBuilderUrl(params.origin);
+ const url = new URL(
+ `/rest/assets/${encodeURIComponent(params.assetId)}/content`,
+ params.requestOrigin ?? sourceOrigin
+ );
+ url.searchParams.set("projectId", params.projectId);
+ url.searchParams.set("expectedName", params.expectedName);
+ const response = await request(url, {
+ method: "PUT",
+ body: await params.readAssetData(),
+ headers: createHeaders({
+ ...params.headers,
+ "x-auth-token": params.authToken,
+ "content-type": "application/octet-stream",
+ }),
+ });
+ const result = (await response.json()) as AssetContentUpdateResult;
+ if ("errors" in result) {
+ throw Object.assign(new Error(result.errors), { status: response.status });
+ }
+ return result;
+};
+
export const loadProjectBundleByBuildId = async (
params: {
buildId: string;
diff --git a/packages/postgrest/src/index.server.ts b/packages/postgrest/src/index.server.ts
index 476d79c1f3..a5ad11233b 100644
--- a/packages/postgrest/src/index.server.ts
+++ b/packages/postgrest/src/index.server.ts
@@ -2,10 +2,26 @@ import type { Database } from "./__generated__/db-types";
import { PostgrestClient } from "@supabase/postgrest-js";
export type { Database } from "./__generated__/db-types";
-export type Client = PostgrestClient<Database>;
+type DatabaseWithAssetRevision = Omit<Database, "public"> & {
+ public: Omit<Database["public"], "Functions"> & {
+ Functions: Database["public"]["Functions"] & {
+ swap_asset_file: {
+ Args: {
+ asset_id: string;
+ expected_name: string;
+ project_id: string;
+ replacement_name: string;
+ };
+ Returns: string;
+ };
+ };
+ };
+};
+
+export type Client = PostgrestClient<DatabaseWithAssetRevision>;
export const createClient = (url: string, apiKey: string): Client => {
- const client = new PostgrestClient<Database>(url, {
+ const client = new PostgrestClient<DatabaseWithAssetRevision>(url, {
headers: {
apikey: apiKey,
Authorization: `Bearer ${apiKey}`,
diff --git a/packages/postgrest/supabase/tests/asset-content-revisions.sql b/packages/postgrest/supabase/tests/asset-content-revisions.sql
new file mode 100644
index 0000000000..5856e0efcd
--- /dev/null
+++ b/packages/postgrest/supabase/tests/asset-content-revisions.sql
@@ -0,0 +1,106 @@
+BEGIN;
+SET LOCAL search_path = pgtap, public;
+SELECT no_plan();
+
+INSERT INTO "User" ("id", "email", "username")
+VALUES ('revision-user', '[email protected]', 'revision-user');
+
+INSERT INTO "Project" ("id", "title", "domain", "userId")
+VALUES (
+ 'revision-project',
+ 'Revision project',
+ 'revision-project-domain',
+ 'revision-user'
+);
+
+INSERT INTO "File" (
+ "name",
+ "format",
+ "size",
+ "status",
+ "isDeleted",
+ "uploaderProjectId"
+)
+VALUES
+ ('settings_old.json', 'json', 2, 'UPLOADED', false, 'revision-project'),
+ ('settings_new.json', 'json', 7, 'UPLOADED', true, 'revision-project'),
+ ('settings_other.json', 'json', 7, 'UPLOADED', false, NULL);
+
+INSERT INTO "Asset" ("id", "projectId", "name")
+VALUES ('revision-asset', 'revision-project', 'settings_old.json');
+
+SELECT is(
+ swap_asset_file(
+ 'revision-project',
+ 'revision-asset',
+ 'settings_old.json',
+ 'settings_new.json'
+ ),
+ 'updated',
+ 'swaps an asset to the uploaded revision'
+);
+
+SELECT is(
+ (
+ SELECT "name" FROM "Asset"
+ WHERE "id" = 'revision-asset' AND "projectId" = 'revision-project'
+ ),
+ 'settings_new.json',
+ 'preserves the asset id while changing its file'
+);
+
+SELECT ok(
+ (SELECT "isDeleted" FROM "File" WHERE "name" = 'settings_old.json'),
+ 'marks the unreferenced old file as deleted'
+);
+
+SELECT isnt(
+ (SELECT "isDeleted" FROM "File" WHERE "name" = 'settings_new.json'),
+ true,
+ 'restores the replacement file before using it'
+);
+
+SELECT is(
+ swap_asset_file(
+ 'revision-project',
+ 'revision-asset',
+ 'settings_old.json',
+ 'settings_new.json'
+ ),
+ 'conflict',
+ 'rejects a stale expected file name'
+);
+
+SELECT is(
+ swap_asset_file(
+ 'revision-project',
+ 'revision-asset',
+ 'settings_new.json',
+ 'settings_other.json'
+ ),
+ 'invalid_revision',
+ 'rejects a replacement file that does not belong to the project'
+);
+
+SELECT is(
+ swap_asset_file(
+ 'revision-project',
+ 'revision-asset',
+ 'settings_new.json',
+ 'settings_old.json'
+ ),
+ 'updated',
+ 'can restore the previous revision for undo'
+);
+
+SELECT is(
+ (
+ SELECT "name" FROM "Asset"
+ WHERE "id" = 'revision-asset' AND "projectId" = 'revision-project'
+ ),
+ 'settings_old.json',
+ 'undo keeps the same logical asset id'
+);
+
+SELECT * FROM finish();
+ROLLBACK;
diff --git a/packages/prisma-client/prisma/migrations/20260718000000_asset_content_revisions/migration.sql b/packages/prisma-client/prisma/migrations/20260718000000_asset_content_revisions/migration.sql
new file mode 100644
index 0000000000..1ff85368c3
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20260718000000_asset_content_revisions/migration.sql
@@ -0,0 +1,53 @@
+CREATE OR REPLACE FUNCTION swap_asset_file(
+ project_id text,
+ asset_id text,
+ expected_name text,
+ replacement_name text
+) RETURNS text AS $$
+DECLARE
+ current_name text;
+BEGIN
+ SELECT "name"
+ INTO current_name
+ FROM "Asset"
+ WHERE "projectId" = project_id AND "id" = asset_id
+ FOR UPDATE;
+
+ IF current_name IS NULL THEN
+ RETURN 'not_found';
+ END IF;
+
+ IF current_name <> expected_name THEN
+ RETURN 'conflict';
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1
+ FROM "File"
+ WHERE
+ "name" = replacement_name
+ AND "status" = 'UPLOADED'
+ AND "uploaderProjectId" = project_id
+ ) THEN
+ RETURN 'invalid_revision';
+ END IF;
+
+ UPDATE "File"
+ SET "isDeleted" = false
+ WHERE "name" = replacement_name;
+
+ UPDATE "Asset"
+ SET "name" = replacement_name
+ WHERE "projectId" = project_id AND "id" = asset_id;
+
+ UPDATE "File"
+ SET "isDeleted" = true
+ WHERE
+ "name" = expected_name
+ AND NOT EXISTS (
+ SELECT 1 FROM "Asset" WHERE "name" = expected_name
+ );
+
+ RETURN 'updated';
+END;
+$$ LANGUAGE plpgsql;
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index c52aa01a8d..6da940e432 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -3700,6 +3700,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -3837,6 +3840,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -3899,6 +3905,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -6834,6 +6843,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -6971,6 +6983,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -7033,6 +7048,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -9979,6 +9997,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -10116,6 +10137,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -10178,6 +10202,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -13113,6 +13140,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -13250,6 +13280,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -13312,6 +13345,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -18942,6 +18978,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -19087,6 +19126,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -19149,6 +19191,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -22279,6 +22324,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -22424,6 +22472,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -22486,6 +22537,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -36684,6 +36738,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -36821,6 +36878,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -36883,6 +36943,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -39893,6 +39956,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -40030,6 +40096,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -40092,6 +40161,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -46218,6 +46290,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -46350,6 +46425,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -46412,6 +46490,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -52041,6 +52122,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -52173,6 +52257,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -52235,6 +52322,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -66223,7 +66313,7 @@ export const runtimeOperationContractData = [
properties: {
type: {
type: "string",
- enum: ["image", "font"],
+ enum: ["font", "image", "file"],
},
sort: {
type: "string",
@@ -66966,6 +67056,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
anyOf: [
{
@@ -67098,6 +67191,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
@@ -67160,6 +67256,9 @@ export const runtimeOperationContractData = [
createdAt: {
type: "string",
},
+ updatedAt: {
+ type: "string",
+ },
format: {
type: "string",
},
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 4280c57429..53ecce93c2 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -3296,6 +3296,41 @@ describe("project session mcp adapter", () => {
);
});
+ test("categorizes text asset editing with asset capabilities", async () => {
+ const updateAssetContent = publicOperation({
+ command: "update-asset-content",
+ id: "assets.updateContent",
+ method: "mutation",
+ permit: "edit",
+ description: "Update text asset content",
+ inputSchema: getTestInputSchema(
+ z.object({
+ assetId: z.string(),
+ expectedName: z.string(),
+ content: z.string(),
+ })
+ ),
+ readNamespaces: ["assets"],
+ writeNamespaces: ["assets"],
+ invalidatesNamespaces: ["assets"],
+ });
+ const adapter = createProjectSessionMcpCore({
+ operations: [...publicMcpOperations, updateAssetContent],
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ });
+
+ const index = await adapter.callTool({ name: "meta.index" });
+ const capabilities = (
+ index.structuredContent.data as {
+ capabilities: { area: string; tools: string[] }[];
+ }
+ ).capabilities;
+ const assets = capabilities.find(({ area }) => area === "assets");
+
+ expect(assets?.tools).toContain("update-asset-content");
+ });
+
test("rejects import without destination share link", async () => {
const adapter = createProjectSessionMcpCore({
operations: publicMcpOperations,
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index f802390bbc..7974c60966 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -3054,7 +3054,7 @@ const capabilityAreas = [
},
{
area: "assets",
- goal: "Manage asset folders and uploaded assets, including listing, creating, renaming, moving, duplicating, downloading, uploading, replacing, and deleting.",
+ goal: "Manage asset folders and uploaded assets, including listing, creating, renaming, moving, duplicating, downloading, uploading, editing text content, replacing, and deleting.",
tools: [
"list-asset-folders",
"create-asset-folder",
@@ -3067,6 +3067,7 @@ const capabilityAreas = [
"upload-asset",
"upload-assets",
"download-asset",
+ "update-asset-content",
"update-asset",
"duplicate-asset",
"set-image-descriptions",
diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.ts
index 4c45257d7a..d3217c68bd 100644
--- a/packages/project-build/src/runtime/assets.test.ts
+++ b/packages/project-build/src/runtime/assets.test.ts
@@ -304,6 +304,26 @@ describe("asset runtime operations", () => {
});
});
+ test("filters generic file assets", () => {
+ const file: Asset = {
+ id: "document",
+ projectId: "project",
+ name: "readme.md",
+ type: "file",
+ size: 12,
+ format: "md",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ meta: {},
+ };
+
+ expect(
+ listAssets(
+ { ...state, assets: new Map([[file.id, file]]) },
+ { type: "file" }
+ )
+ ).toMatchObject({ items: [{ id: "document", type: "file" }] });
+ });
+
test("gets the complete asset record", () => {
const asset = imageAsset("nested");
asset.description = "Campaign hero";
diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.ts
index 215191e46c..00453c1e9c 100644
--- a/packages/project-build/src/runtime/assets.ts
+++ b/packages/project-build/src/runtime/assets.ts
@@ -856,7 +856,7 @@ export const serializeAssetList = ({
assets: Asset[];
build?: AssetReferenceBuild;
input: PaginatedOutputInput & {
- type?: "image" | "font";
+ type?: Asset["type"];
withUsage?: boolean;
sort?: "name" | "size" | "createdAt" | "usage";
};
@@ -1011,7 +1011,7 @@ export const listAssets = (
| "dataSources"
>,
input: PaginatedOutputInput & {
- type?: "image" | "font";
+ type?: Asset["type"];
withUsage?: boolean;
sort?: "name" | "size" | "createdAt" | "usage";
} = {}
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index 115c0845ea..76ad07bcbd 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -90,6 +90,14 @@ const paginatedReadOperationIds = [
const maxCompactListBytes = 16 * 1024;
+test("assets.list accepts every stored asset type", () => {
+ const operation = getBuilderRuntimeOperation("assets.list");
+
+ expect(operation.inputSchema.parse({ type: "file" })).toEqual({
+ type: "file",
+ });
+});
+
test.each(paginatedReadOperationIds)(
"%s uses the shared paginated compact/verbose contract",
(operationId) => {
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index ba04c3e5a3..26a0347825 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -9,7 +9,11 @@ import {
getInputSchemaMetadata,
isHiddenPublicApiInputField,
} from "../contracts/input-schema";
-import { instanceFilterInput, type InputJsonSchema } from "@webstudio-is/sdk";
+import {
+ assetType,
+ instanceFilterInput,
+ type InputJsonSchema,
+} from "@webstudio-is/sdk";
import { pageCopyNamespaces } from "../contracts/namespaces";
import { builderRuntimeContext, type BuilderRuntimeContext } from "./context";
import { z } from "zod";
@@ -399,7 +403,7 @@ const scopedInstanceListInput = z.object({
});
const paginatedListInput = paginatedOutputInputSchema;
const assetListInput = z.object({
- type: z.enum(["image", "font"]).optional(),
+ type: assetType.optional(),
sort: z.enum(["name", "size", "createdAt", "usage"]).optional(),
withUsage: z.boolean().optional(),
...paginatedOutputInputSchema.shape,
diff --git a/packages/protocol/src/builder-api/local-operation-inputs.ts b/packages/protocol/src/builder-api/local-operation-inputs.ts
index 845949c09b..60783608c1 100644
--- a/packages/protocol/src/builder-api/local-operation-inputs.ts
+++ b/packages/protocol/src/builder-api/local-operation-inputs.ts
@@ -22,6 +22,13 @@ const localUploadAssetsInput = z.object({
assetsDir: z.string().optional(),
});
+const localUpdateAssetContentInput = z.object({
+ assetId: z.string().min(1),
+ expectedName: z.string().min(1),
+ path: z.string().min(1).optional(),
+ content: z.string().optional(),
+});
+
const localOperation = <
const Operation extends {
command: string;
@@ -59,4 +66,15 @@ export const localOnlyOperationInputs = [
},
localUploadAssetsInput
),
+ localOperation(
+ {
+ command: "update-asset-content",
+ id: "assets.updateContent",
+ method: "mutation",
+ client: "updateProjectAssetContent",
+ permit: "edit" as const,
+ invalidatesNamespaces: ["assets"] as const,
+ },
+ localUpdateAssetContentInput
+ ),
] as const;
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 5a5af5617e..02c9ba5511 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -749,6 +749,15 @@ const curatedPublicApiOperationDocumentation = [
"webstudio upload-assets --input assets.json --assets-dir .webstudio/assets --json",
],
},
+ {
+ command: "update-asset-content",
+ description:
+ "Replace a text asset's content while preserving its stable asset id; provide exactly one of path or content and use the current asset name as expectedName",
+ examples: [
+ 'MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"settings_hash.json","content":"{\\"theme\\":\\"dark\\"}"}',
+ 'MCP/API: update-asset-content {"assetId":"asset-id","expectedName":"styles_hash.css","path":"./styles.css"}',
+ ],
+ },
{
command: "find-asset-usage",
description: "Find where an asset is referenced in the project",
diff --git a/packages/protocol/src/builder-api/operations.test.ts b/packages/protocol/src/builder-api/operations.test.ts
index f19f95b36c..6226dc16c9 100644
--- a/packages/protocol/src/builder-api/operations.test.ts
+++ b/packages/protocol/src/builder-api/operations.test.ts
@@ -265,6 +265,9 @@ describe("public api operation catalog", () => {
expect(getPublicApiOperation("upload-asset").semanticOwner).toBe(
"local-side-effect"
);
+ expect(getPublicApiOperation("update-asset-content").semanticOwner).toBe(
+ "local-side-effect"
+ );
expect(getPublicApiOperation("publish").semanticOwner).toBe(
"server-infrastructure"
);
@@ -286,6 +289,13 @@ describe("public api operation catalog", () => {
expect(
getPublicApiOperation("upload-assets").invalidatesNamespaces
).toEqual(["assets"]);
+ expect(
+ getPublicApiOperation("update-asset-content").invalidatesNamespaces
+ ).toEqual(["assets"]);
+ expect(
+ getPublicApiOperation("update-asset-content").requiredInputFields
+ ).toEqual(["assetId", "expectedName"]);
+ expect(getPublicApiOperation("update-asset-content").permit).toBe("edit");
});
test("allows MCP uploads to target asset folders", () => {
diff --git a/packages/protocol/src/builder-api/operations.ts b/packages/protocol/src/builder-api/operations.ts
index af7816c0d6..69aa47baa1 100644
--- a/packages/protocol/src/builder-api/operations.ts
+++ b/packages/protocol/src/builder-api/operations.ts
@@ -120,7 +120,8 @@ const withDefaultPermit = <Operation extends PublicApiOperationInput>(
: operation.id === "build.patch"
? "raw-build-patch"
: operation.id === "assets.upload" ||
- operation.id === "assets.uploadMany"
+ operation.id === "assets.uploadMany" ||
+ operation.id === "assets.updateContent"
? "local-side-effect"
: "server-infrastructure",
runtimeOperationId: runtimeOperation?.id,
diff --git a/packages/sdk/src/assets.test.ts b/packages/sdk/src/assets.test.ts
index 3f0fb8bef9..8721bbd127 100644
--- a/packages/sdk/src/assets.test.ts
+++ b/packages/sdk/src/assets.test.ts
@@ -20,9 +20,34 @@ import {
acceptToMimeCategories,
getAssetMime,
doesAssetMatchMimePatterns,
+ getAssetTextEditorLanguage,
+ isTextFileAsset,
} from "./assets";
describe("allowed-file-types", () => {
+ describe("text editor support", () => {
+ test.each([
+ ["txt", "plain"],
+ ["csv", "plain"],
+ ["md", "markdown"],
+ ["js", "javascript"],
+ ["css", "css"],
+ ["json", "json"],
+ ["html", "html"],
+ ["xml", "xml"],
+ ["svg", "xml"],
+ ])("maps %s files to the %s editor", (format, language) => {
+ expect(getAssetTextEditorLanguage({ format })).toBe(language);
+ expect(isTextFileAsset({ format })).toBe(true);
+ });
+
+ test("marks binary and unknown formats as non-editable", () => {
+ expect(getAssetTextEditorLanguage({ format: "pdf" })).toBeUndefined();
+ expect(getAssetTextEditorLanguage({ format: "unknown" })).toBeUndefined();
+ expect(isTextFileAsset({ format: "pdf" })).toBe(false);
+ });
+ });
+
describe("getMimeTypeByExtension", () => {
test("returns correct MIME type for valid extension", () => {
expect(getMimeTypeByExtension("jpg")).toBe("image/jpeg");
@@ -469,6 +494,23 @@ describe("allowed-file-types", () => {
expect(url.search).toBe("?format=raw");
});
+ test.each(["tiff", "tif", "bmp", "ico", "avif"])(
+ "serves %s images directly without resizing",
+ (format) => {
+ const url = getAssetUrl(
+ {
+ ...mockImageAsset,
+ name: `photo.${format}`,
+ },
+ "https://example.com"
+ );
+
+ expect(url.href).toBe(
+ `https://example.com/cgi/asset/photo.${format}?format=raw`
+ );
+ }
+ );
+
test("generates correct URL for video assets", () => {
const url = getAssetUrl(mockVideoAsset, "https://example.com");
expect(url.href).toBe(
diff --git a/packages/sdk/src/assets.ts b/packages/sdk/src/assets.ts
index 33668d8c7d..ce7ce8062d 100644
--- a/packages/sdk/src/assets.ts
+++ b/packages/sdk/src/assets.ts
@@ -1,6 +1,40 @@
import warnOnce from "warn-once";
import type { Asset } from "./schema/assets";
+export const MIME_CATEGORIES = [
+ "image",
+ "video",
+ "audio",
+ "font",
+ "text",
+ "application",
+] as const;
+
+export type MimeCategory = (typeof MIME_CATEGORIES)[number];
+
+export type AssetTextEditorLanguage =
+ | "plain"
+ | "css"
+ | "html"
+ | "javascript"
+ | "json"
+ | "markdown"
+ | "xml";
+
+type MimeType = `${MimeCategory}/${string}`;
+type BinaryMimeType = `${Exclude<MimeCategory, "text">}/${string}`;
+
+const binaryFile = <Mime extends BinaryMimeType>(mimeType: Mime) =>
+ ({ mimeType, textEditor: false }) as const;
+
+const textFile = <
+ Mime extends MimeType,
+ Language extends AssetTextEditorLanguage,
+>(
+ mimeType: Mime,
+ textEditor: Language
+) => ({ mimeType, textEditor }) as const;
+
/**
* Central registry of allowed file types, extensions, and MIME types
* for asset uploads and serving.
@@ -12,64 +46,79 @@ import type { Asset } from "./schema/assets";
* Other formats (BMP, ICO, TIFF) are allowed for upload but served as-is without optimization.
*/
-export const ALLOWED_FILE_TYPES = {
+const assetFileTypes = {
// Documents
- pdf: "application/pdf",
- doc: "application/msword",
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
- xls: "application/vnd.ms-excel",
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- csv: "text/csv",
- ppt: "application/vnd.ms-powerpoint",
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ pdf: binaryFile("application/pdf"),
+ doc: binaryFile("application/msword"),
+ docx: binaryFile(
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+ ),
+ xls: binaryFile("application/vnd.ms-excel"),
+ xlsx: binaryFile(
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+ ),
+ csv: textFile("text/csv", "plain"),
+ ppt: binaryFile("application/vnd.ms-powerpoint"),
+ pptx: binaryFile(
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation"
+ ),
// Code
- txt: "text/plain",
- md: "text/markdown",
- js: "text/javascript",
- css: "text/css",
- json: "application/json",
- html: "text/html",
- xml: "application/xml",
+ txt: textFile("text/plain", "plain"),
+ md: textFile("text/markdown", "markdown"),
+ js: textFile("text/javascript", "javascript"),
+ css: textFile("text/css", "css"),
+ json: textFile("application/json", "json"),
+ html: textFile("text/html", "html"),
+ xml: textFile("application/xml", "xml"),
// Archives
- zip: "application/zip",
- rar: "application/vnd.rar",
+ zip: binaryFile("application/zip"),
+ rar: binaryFile("application/vnd.rar"),
// Audio
- mp3: "audio/mpeg",
- wav: "audio/wav",
- ogg: "audio/ogg",
- m4a: "audio/mp4",
+ mp3: binaryFile("audio/mpeg"),
+ wav: binaryFile("audio/wav"),
+ ogg: binaryFile("audio/ogg"),
+ m4a: binaryFile("audio/mp4"),
// Video
- mp4: "video/mp4",
- mov: "video/quicktime",
- avi: "video/x-msvideo",
- webm: "video/webm",
+ mp4: binaryFile("video/mp4"),
+ mov: binaryFile("video/quicktime"),
+ avi: binaryFile("video/x-msvideo"),
+ webm: binaryFile("video/webm"),
// Images
// Note: Cloudflare Image Resizing supports: jpg, jpeg, png, gif, webp, svg, avif
// Other formats (bmp, ico, tif, tiff) are served as-is without optimization
- jpg: "image/jpeg",
- jpeg: "image/jpeg",
- png: "image/png",
- gif: "image/gif",
- svg: "image/svg+xml",
- webp: "image/webp",
- avif: "image/avif",
- ico: "image/vnd.microsoft.icon", // Used for favicons
- bmp: "image/bmp", // Served without optimization
- tif: "image/tiff", // Served without optimization
- tiff: "image/tiff", // Served without optimization
+ jpg: binaryFile("image/jpeg"),
+ jpeg: binaryFile("image/jpeg"),
+ png: binaryFile("image/png"),
+ gif: binaryFile("image/gif"),
+ svg: textFile("image/svg+xml", "xml"),
+ webp: binaryFile("image/webp"),
+ avif: binaryFile("image/avif"),
+ ico: binaryFile("image/vnd.microsoft.icon"),
+ bmp: binaryFile("image/bmp"),
+ tif: binaryFile("image/tiff"),
+ tiff: binaryFile("image/tiff"),
// Fonts
- woff: "font/woff",
- woff2: "font/woff2",
- ttf: "font/ttf",
- otf: "font/otf",
+ woff: binaryFile("font/woff"),
+ woff2: binaryFile("font/woff2"),
+ ttf: binaryFile("font/ttf"),
+ otf: binaryFile("font/otf"),
} as const;
+export const ALLOWED_FILE_TYPES = Object.fromEntries(
+ Object.entries(assetFileTypes).map(([extension, { mimeType }]) => [
+ extension,
+ mimeType,
+ ])
+) as {
+ readonly [Extension in keyof typeof assetFileTypes]: (typeof assetFileTypes)[Extension]["mimeType"];
+};
+
export type AllowedFileExtension = keyof typeof ALLOWED_FILE_TYPES;
/**
@@ -80,20 +129,6 @@ export const ALLOWED_FILE_EXTENSIONS: ReadonlySet<AllowedFileExtension> =
Object.keys(ALLOWED_FILE_TYPES) as AllowedFileExtension[]
);
-/**
- * Set of allowed MIME type categories
- */
-export const MIME_CATEGORIES = [
- "image",
- "video",
- "audio",
- "font",
- "text",
- "application",
-] as const;
-
-export type MimeCategory = (typeof MIME_CATEGORIES)[number];
-
/**
* File extensions grouped by MIME category for UI display and filtering
*/
@@ -195,6 +230,17 @@ export const getMimeTypeByExtension = (
return ALLOWED_FILE_TYPES[extension.toLowerCase() as AllowedFileExtension];
};
+export const getAssetTextEditorLanguage = (
+ asset: Pick<Asset, "format">
+): AssetTextEditorLanguage | undefined => {
+ const fileType =
+ assetFileTypes[asset.format.toLowerCase() as keyof typeof assetFileTypes];
+ return fileType?.textEditor || undefined;
+};
+
+export const isTextFileAsset = (asset: Pick<Asset, "format">): boolean =>
+ getAssetTextEditorLanguage(asset) !== undefined;
+
/**
* Get MIME type from a filename
*/
@@ -206,6 +252,9 @@ export const getMimeTypeByFilename = (fileName: string): string => {
return getMimeTypeByExtension(extension) ?? "application/octet-stream";
};
+export const isResizableImageFileName = (fileName: string): boolean =>
+ RESIZABLE_IMAGE_MIME_TYPES.includes(getMimeTypeByFilename(fileName));
+
/**
* Check if a file extension is allowed
*/
@@ -413,25 +462,19 @@ export const decodePathFragment = (fragment: string): string => {
};
/**
- * Generates the appropriate URL for an asset based on its type and format.
- * - Images use /cgi/image/ with format=raw
- * - All other assets (videos, audio, fonts, documents) use /cgi/asset/ with format=raw
+ * Generates the appropriate URL for an asset based on its format.
*
* @param asset - The asset to generate URL for
* @param origin - Origin to prepend (e.g., "https://example.com"). When provided, returns an absolute URL.
* @returns A URL object. Use .pathname for relative paths, .href for absolute URLs
*/
-export const getAssetUrl = (asset: Asset, origin: string): URL => {
- let path: string;
- const assetType = detectAssetType(asset.name);
-
- if (assetType === "image") {
- path = `/cgi/image/${asset.name}?format=raw`;
- } else {
- // Videos, audio, fonts, documents all use /cgi/asset/
- path = `/cgi/asset/${asset.name}?format=raw`;
- }
-
+export const getAssetUrl = (
+ asset: Pick<Asset, "name">,
+ origin: string
+): URL => {
+ const path = isResizableImageFileName(asset.name)
+ ? `/cgi/image/${asset.name}?format=raw`
+ : `/cgi/asset/${asset.name}?format=raw`;
return new URL(path, origin);
};
diff --git a/packages/sdk/src/schema/assets.ts b/packages/sdk/src/schema/assets.ts
index 34e28006ef..905359f9b4 100644
--- a/packages/sdk/src/schema/assets.ts
+++ b/packages/sdk/src/schema/assets.ts
@@ -13,6 +13,7 @@ const baseAsset = {
description: z.union([z.string().optional(), z.null()]),
folderId: assetFolderId.optional(),
createdAt: z.string(),
+ updatedAt: z.string().optional(),
};
export const assetType = z.enum(["font", "image", "file"]);