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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: replace asset option for image assets in asset details (#5676)
Shrek72a4cecbb22b
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsxindex d5d3269150..31a7da1757 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx@@ -1,10 +1,10 @@import isValidFilename from "valid-filename";-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useDebouncedCallback } from "use-debounce";import prettyBytes from "pretty-bytes";import { computed } from "nanostores";import { useStore } from "@nanostores/react";-import { getMimeTypeByExtension } from "@webstudio-is/sdk";+import { getMimeTypeByExtension, IMAGE_MIME_TYPES } from "@webstudio-is/sdk";import type { Asset, Pages, Props, Styles, Instance } from "@webstudio-is/sdk";import type {ImageValue,@@ -46,6 +46,7 @@ import {GearIcon,InfoCircleIcon,PageIcon,+ RefreshCcwIcon,TrashIcon,} from "@webstudio-is/icons";import { hyphenateProperty } from "@webstudio-is/css-engine";@@ -67,7 +68,8 @@ import {selectPage,} from "~/shared/awareness";import { updateWebstudioData } from "~/shared/instance-utils";-import { deleteAssets } from "~/builder/shared/assets";+import { deleteAssets, replaceAsset } from "~/builder/shared/assets";+import { validateFiles } from "~/builder/shared/assets/asset-upload";import {$activeInspectorPanel,setActiveSidebarPanel,@@ -435,6 +437,20 @@ const AssetInfoContent = ({);const authPermit = useStore($authPermit);+ const replaceInputRef = useRef<HTMLInputElement>(null);++ const handleReplaceFile = useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ const files = validateFiles(Array.from(event.target.files ?? []));+ const file = files[0];+ if (file) {+ replaceAsset(id, file);+ }+ // Reset input so the same file can be selected again+ event.target.value = "";+ },+ [id]+ );let downloadError: undefined | string;if (authPermit === "view") {@@ -444,6 +460,12 @@ const AssetInfoContent = ({downloadError = "Upgrade to Pro to download assets.";}+ const isImage = asset.type === "image";+ let replaceError: undefined | string;+ if (authPermit === "view") {+ replaceError = "View mode. You can't replace assets.";+ }+return (<><Box css={{ padding: theme.panel.padding }}>@@ -592,23 +614,49 @@ const AssetInfoContent = ({</Dialog>)}- {downloadError ? (- <Tooltip side="bottom" content={downloadError}>- <IconButton disabled>- <DownloadIcon />- </IconButton>- </Tooltip>- ) : (- <Tooltip side="bottom" content="Download asset">- <IconButton- as="a"- download={formatAssetName(asset)}- href={getAssetUrl(asset, window.location.origin).href}- >- <DownloadIcon />- </IconButton>- </Tooltip>- )}+ <Flex gap="1">+ {isImage && (+ <>+ <input+ ref={replaceInputRef}+ type="file"+ accept={IMAGE_MIME_TYPES.join(", ")}+ style={{ display: "none" }}+ onChange={handleReplaceFile}+ />+ {replaceError ? (+ <Tooltip side="bottom" content={replaceError}>+ <IconButton disabled>+ <RefreshCcwIcon />+ </IconButton>+ </Tooltip>+ ) : (+ <Tooltip side="bottom" content="Replace asset">+ <IconButton onClick={() => replaceInputRef.current?.click()}>+ <RefreshCcwIcon />+ </IconButton>+ </Tooltip>+ )}+ </>+ )}+ {downloadError ? (+ <Tooltip side="bottom" content={downloadError}>+ <IconButton disabled>+ <DownloadIcon />+ </IconButton>+ </Tooltip>+ ) : (+ <Tooltip side="bottom" content="Download asset">+ <IconButton+ as="a"+ download={formatAssetName(asset)}+ href={getAssetUrl(asset, window.location.origin).href}+ >+ <DownloadIcon />+ </IconButton>+ </Tooltip>+ )}+ </Flex></Flex></>);diff --git a/apps/builder/app/builder/shared/assets/index.ts b/apps/builder/app/builder/shared/assets/index.tsindex 4c7fef7695..cad53f2caf 100644--- a/apps/builder/app/builder/shared/assets/index.ts+++ b/apps/builder/app/builder/shared/assets/index.ts@@ -1,5 +1,6 @@export { useAssets } from "./use-assets";export * from "./delete-assets";+export { replaceAsset } from "./replace-asset";export { uploadAssets } from "./upload-assets";export * from "./types";export * from "./separator";diff --git a/apps/builder/app/builder/shared/assets/replace-asset.test.ts b/apps/builder/app/builder/shared/assets/replace-asset.test.tsnew file mode 100644index 0000000000..662904d568--- /dev/null+++ b/apps/builder/app/builder/shared/assets/replace-asset.test.ts@@ -0,0 +1,85 @@+import { describe, test, expect } from "vitest";+import type { StyleValue } from "@webstudio-is/css-engine";+import { __testing__ } from "./replace-asset";++const { replaceAssetInStyleValue } = __testing__;++describe("replaceAssetInStyleValue", () => {+ test("replaces asset id in a direct image value", () => {+ const value: StyleValue = {+ type: "image",+ value: { type: "asset", value: "old-id" },+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "image",+ value: { type: "asset", value: "new-id" },+ });+ });++ test("does not mutate image value with a different asset id", () => {+ const value: StyleValue = {+ type: "image",+ value: { type: "asset", value: "other-id" },+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "image",+ value: { type: "asset", value: "other-id" },+ });+ });++ test("does not mutate image value with url type", () => {+ const value: StyleValue = {+ type: "image",+ value: { type: "url", url: "https://example.com/img.png" },+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "image",+ value: { type: "url", url: "https://example.com/img.png" },+ });+ });++ test("replaces asset id inside a tuple value", () => {+ const value: StyleValue = {+ type: "tuple",+ value: [+ { type: "image", value: { type: "asset", value: "old-id" } },+ { type: "image", value: { type: "asset", value: "other-id" } },+ ],+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "tuple",+ value: [+ { type: "image", value: { type: "asset", value: "new-id" } },+ { type: "image", value: { type: "asset", value: "other-id" } },+ ],+ });+ });++ test("replaces asset id inside a layers value", () => {+ const value: StyleValue = {+ type: "layers",+ value: [+ { type: "image", value: { type: "asset", value: "old-id" } },+ { type: "image", value: { type: "asset", value: "old-id" } },+ ],+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "layers",+ value: [+ { type: "image", value: { type: "asset", value: "new-id" } },+ { type: "image", value: { type: "asset", value: "new-id" } },+ ],+ });+ });++ test("does not mutate non-image value types", () => {+ const value: StyleValue = { type: "keyword", value: "auto" };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({ type: "keyword", value: "auto" });+ });+});diff --git a/apps/builder/app/builder/shared/assets/replace-asset.ts b/apps/builder/app/builder/shared/assets/replace-asset.tsnew file mode 100644index 0000000000..edf0434fc3--- /dev/null+++ b/apps/builder/app/builder/shared/assets/replace-asset.ts@@ -0,0 +1,125 @@+import type { Asset } from "@webstudio-is/sdk";+import { toast } from "@webstudio-is/design-system";+import { $assets, $pages, $props, $styles } from "~/shared/nano-states";+import { serverSyncStore } from "~/shared/sync/sync-stores";+import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { invalidateAssets } from "~/shared/resources";+import { uploadAssets } from "./upload-assets";+import type { StyleValue } from "@webstudio-is/css-engine";++/**+ * Replace an image asset with a new file.+ *+ * 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+ * 5. Deletes the old asset+ */+export const replaceAsset = async (+ oldAssetId: Asset["id"],+ file: File+): Promise<void> => {+ const oldAsset = $assets.get().get(oldAssetId);+ if (!oldAsset) {+ toast.error("Original asset not found");+ return;+ }++ const fileToAssetId = await uploadAssets("image", [file]);+ const newAssetId = fileToAssetId.get(file);++ if (!newAssetId) {+ toast.error("Failed to upload replacement asset");+ return;+ }++ await waitForAsset(newAssetId);++ serverSyncStore.createTransaction(+ [$pages, $props, $styles, $assets],+ (pages, props, styles, assets) => {+ const updatedNewAsset = assets.get(newAssetId);+ if (updatedNewAsset) {+ updatedNewAsset.description = oldAsset.description;+ }++ for (const prop of props.values()) {+ if (prop.type === "asset" && prop.value === oldAssetId) {+ prop.value = newAssetId;+ }+ }++ for (const styleDecl of styles.values()) {+ replaceAssetInStyleValue(styleDecl.value, oldAssetId, newAssetId);+ }++ if (pages) {+ if (pages.meta?.faviconAssetId === oldAssetId) {+ pages.meta.faviconAssetId = newAssetId;+ }+ for (const page of [pages.homePage, ...pages.pages]) {+ if (page.meta.socialImageAssetId === oldAssetId) {+ page.meta.socialImageAssetId = newAssetId;+ }+ if (page.marketplace?.thumbnailAssetId === oldAssetId) {+ page.marketplace.thumbnailAssetId = newAssetId;+ }+ }+ }++ assets.delete(oldAssetId);+ }+ );++ onNextTransactionComplete(() => {+ invalidateAssets();+ });++ toast.success("Asset replaced successfully");+};++const replaceAssetInStyleValue = (+ styleValue: StyleValue,+ oldAssetId: string,+ newAssetId: string+): void => {+ if (+ styleValue.type === "image" &&+ styleValue.value.type === "asset" &&+ styleValue.value.value === oldAssetId+ ) {+ styleValue.value.value = newAssetId;+ }+ if (styleValue.type === "tuple") {+ for (const item of styleValue.value) {+ replaceAssetInStyleValue(item, oldAssetId, newAssetId);+ }+ }+ if (styleValue.type === "layers") {+ for (const item of styleValue.value) {+ replaceAssetInStyleValue(item, oldAssetId, newAssetId);+ }+ }+};++const waitForAsset = (assetId: string): Promise<Asset> => {+ // Check if asset already exists (avoids TDZ with synchronous subscribe callback)+ const existingAsset = $assets.get().get(assetId);+ if (existingAsset !== undefined) {+ 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) => {+ const asset = assets.get(assetId);+ if (asset !== undefined) {+ unsubscribe();+ resolve(asset);+ }+ });+ });+};++export const __testing__ = { replaceAssetInStyleValue };diff --git a/apps/builder/docs/test-cases.md b/apps/builder/docs/test-cases.mdindex 3bad852fb3..b47e5f4d8c 100644--- a/apps/builder/docs/test-cases.md+++ b/apps/builder/docs/test-cases.md@@ -107,6 +107,13 @@- Upload an image- Check it loads and shows a progress bar- Delete an asset by clicking on the `x` icon and then the delete button in the tooltip+ - Click on an image asset to open asset details+ - Click the replace (reverse) icon button next to the download button+ - Select a new image file from the file picker+ - Check that the asset is replaced and the new image is shown+ - Check that all usages of the old asset (image `src` props, background image styles, favicon, social image) now reference the new file+ - Check that the original asset's filename is preserved on the new asset+ - Verify the replace button is absent for non-image assets (e.g. fonts)1. Navigator view settingsdiff --git a/packages/icons/icons/refresh-ccw.svg b/packages/icons/icons/refresh-ccw.svgnew file mode 100644index 0000000000..95c1f5077c--- /dev/null+++ b/packages/icons/icons/refresh-ccw.svg@@ -0,0 +1,16 @@+<svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+>+ <path+ d="M21 12C21 9.61305 20.0519 7.32387 18.3639 5.63604C16.6761 3.94821 14.387 3 12 3C9.48395 3.00947 7.06897 3.99123 5.26 5.74L3 8M3 8V3M3 8H8M3 12C3 14.387 3.94821 16.6761 5.63604 18.3639C7.32387 20.0519 9.61305 21 12 21C14.5161 20.9905 16.9311 20.0088 18.74 18.2599L21 16.0001M21 16.0001H16.0001M21 16.0001V21"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ </path>+</svg>diff --git a/packages/icons/src/__generated__/components.tsx b/packages/icons/src/__generated__/components.tsxindex f61560fe7c..05ca3b75bd 100644--- a/packages/icons/src/__generated__/components.tsx+++ b/packages/icons/src/__generated__/components.tsx@@ -4377,6 +4377,31 @@ export const RangeCoverIcon: IconComponent = forwardRef();RangeCoverIcon.displayName = "RangeCoverIcon";+export const RefreshCcwIcon: IconComponent = forwardRef(+ ({ fill = "none", size = 16, ...props }, forwardedRef) => {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ width={size}+ height={size}+ fill={fill}+ {...props}+ ref={forwardedRef}+ >+ <path+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="2"+ d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8m0 0V3m0 5h5m-5 4a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16m0 0h-5m5 0v5"+ />+ </svg>+ );+ }+);+RefreshCcwIcon.displayName = "RefreshCcwIcon";+export const RefreshIcon: IconComponent = forwardRef(({ fill = "none", size = 16, ...props }, forwardedRef) => {return (diff --git a/packages/icons/src/__generated__/svg.ts b/packages/icons/src/__generated__/svg.tsindex 16953a59ed..c22f394b5e 100644--- a/packages/icons/src/__generated__/svg.ts+++ b/packages/icons/src/__generated__/svg.ts@@ -324,6 +324,8 @@ export const RangeContainIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="nexport const RangeCoverIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M11 13.5v-1c0-.552-.597-1-1.333-1H6.333c-.736 0-1.333.448-1.333 1v1c0 .552.597 1 1.333 1h3.334c.736 0 1.333-.448 1.333-1ZM1.5 9.5h13M1.452 1.5h13"/></svg>`;+export const RefreshCcwIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8m0 0V3m0 5h5m-5 4a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16m0 0h-5m5 0v5"/></svg>`;+export const RefreshIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path fill="currentColor" fill-rule="evenodd" d="M8 1.5h-.002A7 7 0 0 0 3.16 3.467l-.006.006-.653.653V2a.5.5 0 0 0-1 0v3.333a.498.498 0 0 0 .144.352l.005.004A.498.498 0 0 0 2 5.833h3.357a.5.5 0 1 0 0-1h-2.15l.65-.65A6 6 0 0 1 8.001 2.5 5.5 5.5 0 0 1 13.5 8a.5.5 0 0 0 1 0A6.5 6.5 0 0 0 8 1.5Zm-6 6a.5.5 0 0 1 .5.5A5.5 5.5 0 0 0 8 13.5a6 6 0 0 0 4.143-1.683l.759-.76h-2.235a.5.5 0 1 1 0-1H14a.5.5 0 0 1 .5.5v3.334a.5.5 0 0 1-1 0v-2.017l-.653.653-.006.006A7 7 0 0 1 8 14.5H8A6.5 6.5 0 0 1 1.5 8a.5.5 0 0 1 .5-.5Z" clip-rule="evenodd"/></svg>`;export const RepeatColumnIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M10.25 12.417V3.083c0-.736-.597-1.333-1.333-1.333H7.083c-.736 0-1.333.597-1.333 1.333v9.334c0 .736.597 1.333 1.333 1.333h1.834c.736 0 1.333-.597 1.333-1.333ZM10.25 5.75h-4M10.25 9.75h-4"/></svg>`;