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: Select unused assets before deleting (#6245)

Oleg Isonen471f504087d0
diff --git a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx
new file mode 100644
index 0000000000..34f38b6e4d
--- /dev/null
+++ b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.test.tsx
@@ -0,0 +1,202 @@
+import { act } from "react-dom/test-utils";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { TooltipProvider } from "@webstudio-is/design-system";
+import type { Asset } from "@webstudio-is/sdk";
+import { createDefaultPages } from "@webstudio-is/project-build";
+import {
+ $assetFolders,
+ $assets,
+ $breakpoints,
+ $dataSources,
+ $instances,
+ $pages,
+ $projectSettings,
+ $props,
+ $resources,
+ $styleSourceSelections,
+ $styleSources,
+ $styles,
+} from "~/shared/sync/data-stores";
+import {
+ $authPermit,
+ $builderMode,
+ $selectedPageId,
+} from "~/shared/nano-states";
+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";
+import {
+ DeleteUnusedAssetsDialog,
+ openDeleteUnusedAssetsDialog,
+} from "./delete-unused-assets";
+import { createAssetManagerTestRenderer } from "./test-utils";
+
+const renderer = createAssetManagerTestRenderer();
+registerContainers();
+
+const createAsset = (id: string): Asset => ({
+ id,
+ projectId: "project",
+ name: `${id}.png`,
+ format: "png",
+ size: 1,
+ type: "image",
+ meta: { width: 1, height: 1 },
+ createdAt: "2026-01-01T00:00:00.000Z",
+});
+
+beforeEach(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ callback(0);
+ return 0;
+ });
+ serverSyncStore.transactionManager.currentStack = [];
+ serverSyncStore.transactionManager.undoneStack = [];
+ serverSyncStore.popAll();
+ const pages = createDefaultPages({ rootInstanceId: "body" });
+ $pages.set(pages);
+ $selectedPageId.set(pages.homePageId);
+ $builderMode.set("design");
+ $authPermit.set("build");
+ $instances.set(
+ new Map([
+ [
+ "body",
+ {
+ type: "instance" as const,
+ id: "body",
+ component: "Body",
+ children: [],
+ },
+ ],
+ ])
+ );
+ $props.set(new Map());
+ $breakpoints.set(new Map());
+ $styleSourceSelections.set(new Map());
+ $styleSources.set(new Map());
+ $styles.set(new Map());
+ $dataSources.set(new Map());
+ $resources.set(new Map());
+ $projectSettings.set({ meta: {}, compiler: {} });
+ $assetFolders.set(new Map());
+ const first = createAsset("first");
+ const second = createAsset("second");
+ $assets.set(
+ new Map([
+ [first.id, first],
+ [second.id, second],
+ ])
+ );
+});
+
+afterEach(() => {
+ renderer.cleanup();
+ $assets.set(new Map());
+ vi.unstubAllGlobals();
+});
+
+test("selects unused assets individually and deletes only selected assets", () => {
+ act(() => openDeleteUnusedAssetsDialog());
+ renderer.render(
+ <TooltipProvider>
+ <DeleteUnusedAssetsDialog />
+ </TooltipProvider>
+ );
+
+ const first = document.querySelector<HTMLButtonElement>(
+ "#unused-asset-first"
+ );
+ const second = document.querySelector<HTMLButtonElement>(
+ "#unused-asset-second"
+ );
+ const selectAll = document.querySelector<HTMLButtonElement>(
+ "#select-all-unused-assets"
+ );
+
+ expect(first?.getAttribute("aria-checked")).toBe("true");
+ expect(second?.getAttribute("aria-checked")).toBe("true");
+ expect(selectAll?.getAttribute("aria-checked")).toBe("true");
+
+ act(() => selectAll?.click());
+
+ expect(first?.getAttribute("aria-checked")).toBe("false");
+ expect(second?.getAttribute("aria-checked")).toBe("false");
+ expect(
+ Array.from(document.querySelectorAll("button")).find(
+ (button) => button.textContent === "Delete"
+ )?.disabled
+ ).toBe(true);
+
+ act(() => selectAll?.click());
+ act(() => second?.click());
+
+ expect(second?.getAttribute("aria-checked")).toBe("false");
+ expect(selectAll?.getAttribute("aria-checked")).toBe("false");
+
+ act(() => selectAll?.click());
+
+ expect(first?.getAttribute("aria-checked")).toBe("true");
+ expect(second?.getAttribute("aria-checked")).toBe("true");
+
+ act(() => second?.click());
+ act(() => {
+ Array.from(document.querySelectorAll("button"))
+ .find((button) => button.textContent === "Delete")
+ ?.click();
+ });
+
+ expect($assets.get().has("first")).toBe(false);
+ expect($assets.get().has("second")).toBe(true);
+});
+
+test("does not delete a selected asset that becomes used while open", () => {
+ act(() => openDeleteUnusedAssetsDialog());
+ renderer.render(
+ <TooltipProvider>
+ <DeleteUnusedAssetsDialog />
+ </TooltipProvider>
+ );
+
+ act(() => {
+ $props.set(
+ new Map([
+ [
+ "image-source",
+ {
+ id: "image-source",
+ instanceId: "body",
+ name: "src",
+ type: "asset" as const,
+ value: "second",
+ },
+ ],
+ ])
+ );
+ });
+ expect(document.querySelector("#unused-asset-second")).toBeNull();
+
+ act(() => {
+ document.querySelector<HTMLButtonElement>("#unused-asset-first")?.click();
+ });
+ expect(
+ Array.from(document.querySelectorAll("button")).find(
+ (button) => button.textContent === "Delete"
+ )?.disabled
+ ).toBe(true);
+
+ act(() => {
+ Array.from(document.querySelectorAll("button"))
+ .find((button) => button.textContent === "Delete")
+ ?.click();
+ });
+
+ expect($assets.get().has("first")).toBe(true);
+ expect($assets.get().has("second")).toBe(true);
+});
diff --git a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
index ff60386c68..58b0ab74d9 100644
--- a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx
@@ -1,9 +1,11 @@
import { atom } from "nanostores";
import { useStore } from "@nanostores/react";
+import { useState } from "react";
import {
Dialog,
DialogActions,
DialogContent,
+ DialogDescription,
DialogTitle,
DialogClose,
ScrollArea,
@@ -13,6 +15,9 @@ import {
theme,
toast,
Box,
+ Checkbox,
+ CheckboxAndLabel,
+ Label,
} from "@webstudio-is/design-system";
import type { Asset } from "@webstudio-is/sdk";
import {
@@ -32,13 +37,21 @@ export const openDeleteUnusedAssetsDialog = () => {
$isDeleteUnusedAssetsDialogOpen.set(true);
};
-const getUnusedAssets = () => {
- const assets = $assets.get();
+const DeleteUnusedAssetsDialogContent = ({
+ onClose,
+}: {
+ onClose: () => void;
+}) => {
+ const assets = useStore($assets);
+ const pages = useStore($pages);
+ const projectSettings = useStore($projectSettings);
+ const props = useStore($props);
+ const styles = useStore($styles);
const usagesByAssetId = calculateUsagesByAssetId({
- pages: $pages.get(),
- projectSettings: $projectSettings.get(),
- props: $props.get(),
- styles: $styles.get(),
+ pages,
+ projectSettings,
+ props,
+ styles,
assets,
});
const unusedAssets: Asset[] = [];
@@ -48,35 +61,61 @@ const getUnusedAssets = () => {
unusedAssets.push(asset);
}
}
- return unusedAssets;
-};
-
-const DeleteUnusedAssetsDialogContent = ({
- onClose,
-}: {
- onClose: () => void;
-}) => {
- const unusedAssets = getUnusedAssets();
+ const [selectedAssetIds, setSelectedAssetIds] = useState(
+ () => new Set(unusedAssets.map((asset) => asset.id))
+ );
+ const selectedUnusedAssetIds = unusedAssets.flatMap((asset) =>
+ selectedAssetIds.has(asset.id) ? [asset.id] : []
+ );
+ const allAssetsSelected =
+ selectedUnusedAssetIds.length === unusedAssets.length;
return (
<>
<Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
{unusedAssets.length === 0 ? (
- <Text>There are no unused assets to delete.</Text>
+ <DialogDescription asChild>
+ <Text>There are no unused assets to delete.</Text>
+ </DialogDescription>
) : (
<>
- <Text>
- Delete {unusedAssets.length} unused{" "}
- {unusedAssets.length === 1 ? "asset" : "assets"} from the project?
- </Text>
+ <DialogDescription asChild>
+ <Text>
+ Select which unused assets to delete from the project.
+ </Text>
+ </DialogDescription>
<ScrollArea>
<Box css={{ maxHeight: 200 }}>
<Flex direction="column" gap="1">
{unusedAssets.map((asset) => (
- <Text key={asset.id} variant="mono" truncate>
- {formatAssetName(asset)}
- </Text>
+ <CheckboxAndLabel
+ key={asset.id}
+ css={{ overflow: "hidden" }}
+ >
+ <Checkbox
+ id={`unused-asset-${asset.id}`}
+ checked={selectedAssetIds.has(asset.id)}
+ onCheckedChange={(checked) => {
+ setSelectedAssetIds((currentAssetIds) => {
+ const nextAssetIds = new Set(currentAssetIds);
+ if (checked === true) {
+ nextAssetIds.add(asset.id);
+ } else {
+ nextAssetIds.delete(asset.id);
+ }
+ return nextAssetIds;
+ });
+ }}
+ />
+ <Label
+ htmlFor={`unused-asset-${asset.id}`}
+ text="mono"
+ truncate
+ >
+ {formatAssetName(asset)}
+ </Label>
+ </CheckboxAndLabel>
))}
</Flex>
</Box>
@@ -88,9 +127,11 @@ const DeleteUnusedAssetsDialogContent = ({
{unusedAssets.length > 0 && (
<Button
color="destructive"
+ disabled={selectedUnusedAssetIds.length === 0}
onClick={() => {
- const count = unusedAssets.length;
- deleteAssets(unusedAssets.map((asset) => asset.id));
+ const assetIds = selectedUnusedAssetIds;
+ const count = assetIds.length;
+ deleteAssets(assetIds, { force: false });
onClose();
toast.success(
`Deleted ${count} unused ${count === 1 ? "asset" : "assets"}`
@@ -106,6 +147,24 @@ const DeleteUnusedAssetsDialogContent = ({
{unusedAssets.length > 0 ? "Cancel" : "Close"}
</Button>
</DialogClose>
+ {unusedAssets.length > 0 && (
+ <Box css={{ marginRight: "auto" }}>
+ <CheckboxAndLabel>
+ <Checkbox
+ id="select-all-unused-assets"
+ checked={allAssetsSelected}
+ onCheckedChange={() => {
+ setSelectedAssetIds(
+ allAssetsSelected
+ ? new Set()
+ : new Set(unusedAssets.map((asset) => asset.id))
+ );
+ }}
+ />
+ <Label htmlFor="select-all-unused-assets">Select all</Label>
+ </CheckboxAndLabel>
+ </Box>
+ )}
</DialogActions>
</>
);
diff --git a/apps/builder/app/builder/shared/assets/delete-assets.ts b/apps/builder/app/builder/shared/assets/delete-assets.ts
index b2b2229da6..597b684a71 100644
--- a/apps/builder/app/builder/shared/assets/delete-assets.ts
+++ b/apps/builder/app/builder/shared/assets/delete-assets.ts
@@ -3,10 +3,13 @@ import { executeRuntimeMutation } from "~/shared/instance-utils/data";
import { onNextTransactionComplete } from "~/shared/sync/project-queue";
import { invalidateAssets } from "~/shared/resources";
-export const deleteAssets = (assetIds: Asset["id"][]) => {
+export const deleteAssets = (
+ assetIds: Asset["id"][],
+ { force = true }: { force?: boolean } = {}
+) => {
executeRuntimeMutation({
id: "assets.delete",
- input: { assetIdsOrPrefixes: assetIds, force: true },
+ input: { assetIds, force },
});
// Wait for server to confirm transaction, then invalidate cache
diff --git a/docs/university/foundations/anatomy-of-the-webstudio-builder.md b/docs/university/foundations/anatomy-of-the-webstudio-builder.md
index 316edb8106..13c8488018 100644
--- a/docs/university/foundations/anatomy-of-the-webstudio-builder.md
+++ b/docs/university/foundations/anatomy-of-the-webstudio-builder.md
@@ -114,7 +114,11 @@ Click on any asset to view its details panel, which shows:
- **Download** – Download the original asset file to your computer (Pro plan required)
- **Review & Delete** – When an asset is in use, shows where it's used before confirming deletion. Unused assets can be deleted directly.
-- **Delete unused assets** – Click the brush icon in the Assets Panel header to find and remove all unused assets at once. A dialog lists every unused asset so you can review before confirming deletion. This command is also available from the [Command Panel](commands-and-search.md).
+- **Delete unused assets** – Click the brush icon in the Assets Panel header to
+ review unused assets. All assets are selected by default; uncheck any you want
+ to keep or use **Select all** to change the complete selection. Confirming
+ deletes only selected assets. This command is also available from the
+ [Command Panel](commands-and-search.md).
{% hint style="info" %}
Assets that are currently used in your project will show a settings gear icon. Attempting to delete them will display a list of all usages so you can review before confirming.
diff --git a/docs/university/foundations/assets.md b/docs/university/foundations/assets.md
index c93a1e8b1c..10a49c9f80 100644
--- a/docs/university/foundations/assets.md
+++ b/docs/university/foundations/assets.md
@@ -135,7 +135,10 @@ Delete and download buttons are available inside the asset detail panel (gear ic
- **Unused assets** can be deleted immediately.
- **Assets in use** show a "Review & delete" button that lists every usage with clickable links to each location, so you can review the impact before confirming.
-- **Delete all unused assets** — click the brush icon in the Assets panel header to find and batch-delete all unreferenced assets in one action.
+- **Delete unused assets** — click the brush icon in the Assets panel header to
+ review all unreferenced assets. Every asset is selected by default. Uncheck
+ assets you want to keep, or use **Select all** to change the complete
+ selection. Confirming deletes only the selected assets.
## Downloading assets