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: show when asset is used (#5365)

Bogdan Chadkinfb466caed121
diff --git a/apps/builder/app/builder/shared/assets/use-assets.tsx b/apps/builder/app/builder/shared/assets/use-assets.tsx
index 16fab0b4b3..786623d4a6 100644
--- a/apps/builder/app/builder/shared/assets/use-assets.tsx
+++ b/apps/builder/app/builder/shared/assets/use-assets.tsx
@@ -2,25 +2,32 @@ import { useMemo } from "react";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import warnOnce from "warn-once";
-import type { Asset } from "@webstudio-is/sdk";
+import invariant from "tiny-invariant";
+import type { Asset, Page } from "@webstudio-is/sdk";
import type { AssetType } from "@webstudio-is/asset-uploader";
import { Box, toast, css, theme } from "@webstudio-is/design-system";
import { sanitizeS3Key } from "@webstudio-is/asset-uploader";
+import { Image, wsImageLoader } from "@webstudio-is/image";
+import type { ImageValue, StyleValue } from "@webstudio-is/css-engine";
import { restAssetsUploadPath, restAssetsPath } from "~/shared/router-utils";
-import type {
- AssetContainer,
- UploadedAssetContainer,
- UploadingAssetContainer,
-} from "./types";
+import { fetch } from "~/shared/fetch.client";
import type { ActionData } from "~/builder/shared/assets";
import {
$assets,
$authToken,
+ $pages,
$project,
+ $props,
+ $styles,
$uploadingFilesDataStore,
type UploadingFileData,
} from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
+import type {
+ AssetContainer,
+ UploadedAssetContainer,
+ UploadingAssetContainer,
+} from "./types";
import {
getFileName,
getMimeType,
@@ -28,9 +35,92 @@ import {
getSha256HashOfFile,
uploadingFileDataToAsset,
} from "./asset-utils";
-import { Image, wsImageLoader } from "@webstudio-is/image";
-import invariant from "tiny-invariant";
-import { fetch } from "~/shared/fetch.client";
+import { mapGetOrInsert } from "~/shared/shim";
+
+export type AssetUsage =
+ | { type: "favicon" }
+ | { type: "socialImage"; pageId: Page["id"] }
+ | { type: "marketplaceThumbnail"; pageId: Page["id"] }
+ | { type: "prop"; propId: string }
+ | { type: "style"; styleDeclKey: string };
+
+const traverseStyleValue = (
+ styleValue: StyleValue,
+ callback: (value: ImageValue) => void
+) => {
+ if (styleValue.type === "image") {
+ callback(styleValue);
+ }
+ if (styleValue.type === "tuple") {
+ for (const item of styleValue.value) {
+ traverseStyleValue(item, callback);
+ }
+ }
+ if (styleValue.type === "layers") {
+ for (const item of styleValue.value) {
+ traverseStyleValue(item, callback);
+ }
+ }
+};
+
+export const $usagesByAssetId = computed(
+ [$pages, $props, $styles],
+ (pages, props, styles) => {
+ const usagesByAsset = new Map<Asset["id"], AssetUsage[]>();
+ if (pages?.meta?.faviconAssetId) {
+ const usages = mapGetOrInsert(
+ usagesByAsset,
+ pages.meta.faviconAssetId,
+ []
+ );
+ usages.push({ type: "favicon" });
+ }
+ if (pages) {
+ for (const page of [pages.homePage, ...pages.pages]) {
+ if (page.meta.socialImageAssetId) {
+ const usages = mapGetOrInsert(
+ usagesByAsset,
+ page.meta.socialImageAssetId,
+ []
+ );
+ usages.push({ type: "socialImage", pageId: page.id });
+ }
+ if (page.marketplace?.thumbnailAssetId) {
+ const usages = mapGetOrInsert(
+ usagesByAsset,
+ page.marketplace.thumbnailAssetId,
+ []
+ );
+ usages.push({ type: "marketplaceThumbnail", pageId: page.id });
+ }
+ }
+ }
+ for (const prop of props.values()) {
+ if (
+ prop.type === "asset" &&
+ // ignore width and height properties which are specific to size
+ prop.name !== "width" &&
+ prop.name !== "height"
+ ) {
+ const usages = mapGetOrInsert(usagesByAsset, prop.value, []);
+ usages.push({ type: "prop", propId: prop.id });
+ }
+ }
+ for (const [styleDeclKey, styleDecl] of styles) {
+ traverseStyleValue(styleDecl.value, (imageValue) => {
+ if (imageValue.value.type === "asset") {
+ const usages = mapGetOrInsert(
+ usagesByAsset,
+ imageValue.value.value,
+ []
+ );
+ usages.push({ type: "style", styleDeclKey });
+ }
+ });
+ }
+ return usagesByAsset;
+ }
+);
export const deleteAssets = (assetIds: Asset["id"][]) => {
serverSyncStore.createTransaction([$assets], (assets) => {
diff --git a/apps/builder/app/builder/shared/image-manager/image-info-tigger.tsx b/apps/builder/app/builder/shared/image-manager/image-info-tigger.tsx
deleted file mode 100644
index 10ec8df20c..0000000000
--- a/apps/builder/app/builder/shared/image-manager/image-info-tigger.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { useState } from "react";
-import {
- SmallIconButton,
- Popover,
- PopoverTrigger,
- PopoverContent,
- PopoverTitle,
-} from "@webstudio-is/design-system";
-import { GearIcon } from "@webstudio-is/icons";
-import type { Asset } from "@webstudio-is/sdk";
-import { theme } from "@webstudio-is/design-system";
-import { ImageInfo } from "./image-info";
-
-const triggerVisibilityVar = `--ws-image-info-trigger-visibility`;
-
-export const imageInfoTriggerCssVars = ({ show }: { show: boolean }) => ({
- [triggerVisibilityVar]: show ? "visible" : "hidden",
-});
-
-export const ImageInfoTrigger = ({
- asset,
- onDelete,
-}: {
- asset: Asset;
- onDelete: (ids: Array<string>) => void;
-}) => {
- const [isInfoOpen, setInfoOpen] = useState(false);
- return (
- <Popover modal open={isInfoOpen} onOpenChange={setInfoOpen}>
- <PopoverTrigger asChild>
- <SmallIconButton
- title="Options"
- onClick={() => setInfoOpen(true)}
- tabIndex={-1}
- css={{
- visibility: `var(${triggerVisibilityVar}, hidden)`,
- position: "absolute",
- color: theme.colors.backgroundIconSubtle,
- top: theme.spacing[3],
- right: theme.spacing[3],
- cursor: "pointer",
- transition: "opacity 100ms ease",
- "& svg": {
- fill: `oklch(from ${theme.colors.white} l c h / 0.9)`,
- },
- "&:hover": {
- color: theme.colors.foregroundIconMain,
- },
- }}
- icon={<GearIcon />}
- />
- </PopoverTrigger>
- <PopoverContent>
- <PopoverTitle>Asset Details</PopoverTitle>
- <ImageInfo
- onDelete={(ids) => {
- setInfoOpen(false);
- onDelete(ids);
- }}
- asset={asset}
- />
- </PopoverContent>
- </Popover>
- );
-};
diff --git a/apps/builder/app/builder/shared/image-manager/image-info.tsx b/apps/builder/app/builder/shared/image-manager/image-info.tsx
index 7fd9852d73..575627ed92 100644
--- a/apps/builder/app/builder/shared/image-manager/image-info.tsx
+++ b/apps/builder/app/builder/shared/image-manager/image-info.tsx
@@ -1,11 +1,24 @@
+import prettyBytes from "pretty-bytes";
import { useStore } from "@nanostores/react";
import { getMimeByExtension } from "@webstudio-is/asset-uploader";
import {
Box,
Button,
+ css,
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
Flex,
Grid,
+ Popover,
+ PopoverContent,
+ PopoverTitle,
+ PopoverTrigger,
+ SmallIconButton,
+ styled,
Text,
+ textVariants,
theme,
Tooltip,
} from "@webstudio-is/design-system";
@@ -13,20 +26,185 @@ import {
AspectRatioIcon,
CloudIcon,
DimensionsIcon,
+ GearIcon,
PageIcon,
TrashIcon,
} from "@webstudio-is/icons";
-import type { Asset } from "@webstudio-is/sdk";
-import prettyBytes from "pretty-bytes";
-import { $authPermit } from "~/shared/nano-states";
+import type { Asset, Instance } from "@webstudio-is/sdk";
+import {
+ $authPermit,
+ $editingPageId,
+ $instances,
+ $pages,
+ $props,
+ $styles,
+ $styleSourceSelections,
+} from "~/shared/nano-states";
+import { deleteAssets, $usagesByAssetId, type AssetUsage } from "../assets";
import { getFormattedAspectRatio } from "./utils";
+import { hyphenateProperty } from "@webstudio-is/css-engine";
+import { $openProjectSettings } from "~/shared/nano-states/project-settings";
+import {
+ $awareness,
+ findAwarenessByInstanceId,
+ selectPage,
+} from "~/shared/awareness";
+import { $activeInspectorPanel, setActiveSidebarPanel } from "../nano-states";
-type ImageInfoProps = {
- asset: Asset;
- onDelete: (ids: Array<string>) => void;
+const buttonLinkClass = css({
+ all: "unset",
+ cursor: "pointer",
+ ...textVariants.link,
+}).toString();
+
+const AssetUsagesList = ({ usages }: { usages: AssetUsage[] }) => {
+ const props = useStore($props);
+ const styles = useStore($styles);
+ return (
+ <Text as="ul" css={{ paddingLeft: "1em", listStyleType: '"-"' }}>
+ {usages.map((usage, index) => {
+ if (usage.type === "favicon") {
+ return (
+ <li key={index}>
+ <button
+ className={buttonLinkClass}
+ onClick={() => {
+ $openProjectSettings.set("general");
+ setActiveSidebarPanel("auto");
+ }}
+ >
+ Favicon
+ </button>
+ </li>
+ );
+ }
+ if (usage.type === "socialImage") {
+ return (
+ <li key={index}>
+ <button
+ className={buttonLinkClass}
+ onClick={() => {
+ selectPage(usage.pageId);
+ setActiveSidebarPanel("pages");
+ $editingPageId.set(usage.pageId);
+ }}
+ >
+ Page social image
+ </button>
+ </li>
+ );
+ }
+ if (usage.type === "marketplaceThumbnail") {
+ return (
+ <li key={index}>
+ <button
+ className={buttonLinkClass}
+ onClick={() => {
+ selectPage(usage.pageId);
+ setActiveSidebarPanel("pages");
+ $editingPageId.set(usage.pageId);
+ }}
+ >
+ Marketplace page thumbnail
+ </button>
+ </li>
+ );
+ }
+ if (usage.type === "prop") {
+ return (
+ <li key={index}>
+ <button
+ className={buttonLinkClass}
+ onClick={() => {
+ const pages = $pages.get();
+ const instances = $instances.get();
+ const prop = $props.get().get(usage.propId);
+ if (!prop || !pages) {
+ return;
+ }
+ const awareness = findAwarenessByInstanceId(
+ pages,
+ instances,
+ prop.instanceId
+ );
+ $awareness.set(awareness);
+ setActiveSidebarPanel("auto");
+ $activeInspectorPanel.set("settings");
+ }}
+ >
+ "{props.get(usage.propId)?.name}" property
+ </button>
+ </li>
+ );
+ }
+ if (usage.type === "style") {
+ const styleDecl = styles.get(usage.styleDeclKey);
+ const property = styleDecl
+ ? hyphenateProperty(styleDecl.property)
+ : undefined;
+ return (
+ <li key={index}>
+ <button
+ className={buttonLinkClass}
+ onClick={() => {
+ const pages = $pages.get();
+ const instances = $instances.get();
+ const styleDecl = $styles.get().get(usage.styleDeclKey);
+ const styleSourceSelections = $styleSourceSelections.get();
+ if (!styleDecl) {
+ return;
+ }
+ let styleInstanceId: undefined | Instance["id"];
+ for (const {
+ instanceId,
+ values,
+ } of styleSourceSelections.values()) {
+ if (values.includes(styleDecl.styleSourceId)) {
+ styleInstanceId = instanceId;
+ break;
+ }
+ }
+ if (!styleInstanceId || !pages) {
+ return;
+ }
+ const awareness = findAwarenessByInstanceId(
+ pages,
+ instances,
+ styleInstanceId
+ );
+ $awareness.set(awareness);
+ setActiveSidebarPanel("auto");
+ $activeInspectorPanel.set("style");
+ }}
+ >
+ "{property}" style
+ </button>
+ </li>
+ );
+ }
+ usage satisfies never;
+ })}
+ </Text>
+ );
};
-export const ImageInfo = ({ asset, onDelete }: ImageInfoProps) => {
+const UsageDot = styled(Box, {
+ width: 6,
+ height: 6,
+ backgroundColor: theme.colors.foregroundDestructive,
+ border: "1px solid white",
+ boxShadow: "0 0 3px rgb(0, 0, 0)",
+ borderRadius: "50%",
+ pointerEvents: "none",
+});
+
+const ImageInfoContent = ({
+ asset,
+ usages,
+}: {
+ asset: Asset;
+ usages: AssetUsage[];
+}) => {
const { size, meta, id, name } = asset;
const parts = name.split(".");
@@ -34,11 +212,6 @@ export const ImageInfo = ({ asset, onDelete }: ImageInfoProps) => {
const authPermit = useStore($authPermit);
- const isDeleteDisabled = authPermit === "view";
- const tooltipContent = isDeleteDisabled
- ? "View mode. You can't delete assets."
- : undefined;
-
return (
<>
<Box css={{ width: 250, padding: theme.panel.padding }}>
@@ -61,7 +234,7 @@ export const ImageInfo = ({ asset, onDelete }: ImageInfoProps) => {
{getMimeByExtension(extension)}
</Text>
</Flex>
- {"width" in meta && "height" in meta ? (
+ {"width" in meta && "height" in meta && (
<>
<Flex align="center" gap={1}>
<DimensionsIcon />
@@ -76,21 +249,115 @@ export const ImageInfo = ({ asset, onDelete }: ImageInfoProps) => {
</Text>
</Flex>
</>
- ) : null}
+ )}
+ <Flex align="center" css={{ gap: theme.spacing[3] }}>
+ <Flex
+ css={{
+ width: 16,
+ height: 16,
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
+ <UsageDot />
+ </Flex>
+ <Text variant="labelsSentenceCase">{usages.length} uses</Text>
+ </Flex>
</Grid>
</Box>
<Box css={{ padding: theme.panel.padding }}>
- <Tooltip side="bottom" content={tooltipContent}>
+ {authPermit === "view" ? (
+ <Tooltip side="bottom" content="View mode. You can't delete assets.">
+ <Button disabled color="destructive" prefix={<TrashIcon />}>
+ Delete
+ </Button>
+ </Tooltip>
+ ) : usages.length === 0 ? (
<Button
color="destructive"
- onClick={() => onDelete([id])}
+ onClick={() => deleteAssets([id])}
prefix={<TrashIcon />}
- disabled={isDeleteDisabled}
>
Delete
</Button>
- </Tooltip>
+ ) : (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button color="destructive" prefix={<TrashIcon />}>
+ Delete
+ </Button>
+ </DialogTrigger>
+ <DialogContent minWidth={360}>
+ <DialogTitle>Delete asset?</DialogTitle>
+ <Box css={{ padding: theme.panel.padding }}>
+ <Text css={{ marginBottom: "1em" }}>
+ This asset is used in following places:
+ </Text>
+ <AssetUsagesList usages={usages} />
+ <Flex>
+ <Button
+ css={{
+ marginLeft: "auto",
+ marginTop: theme.panel.paddingBlock,
+ }}
+ color="destructive"
+ prefix={<TrashIcon />}
+ onClick={() => deleteAssets([id])}
+ >
+ Delete
+ </Button>
+ </Flex>
+ </Box>
+ </DialogContent>
+ </Dialog>
+ )}
</Box>
</>
);
};
+
+const triggerVisibilityVar = `--ws-image-info-trigger-visibility`;
+
+export const imageInfoCssVars = ({ show }: { show: boolean }) => ({
+ [triggerVisibilityVar]: show ? "visible" : "hidden",
+});
+
+export const ImageInfo = ({ asset }: { asset: Asset }) => {
+ const usagesByAssetId = useStore($usagesByAssetId);
+ const usages = usagesByAssetId.get(asset.id) ?? [];
+ return (
+ <>
+ <Popover modal>
+ <PopoverTrigger asChild>
+ <SmallIconButton
+ title="Options"
+ tabIndex={-1}
+ css={{
+ visibility: `var(${triggerVisibilityVar}, hidden)`,
+ position: "absolute",
+ color: theme.colors.backgroundIconSubtle,
+ top: theme.spacing[3],
+ right: theme.spacing[3],
+ cursor: "pointer",
+ transition: "opacity 100ms ease",
+ "& svg": {
+ fill: `oklch(from ${theme.colors.white} l c h / 0.9)`,
+ },
+ "&:hover": {
+ color: theme.colors.foregroundIconMain,
+ },
+ }}
+ icon={<GearIcon />}
+ />
+ </PopoverTrigger>
+ <PopoverContent>
+ <PopoverTitle>Asset Details</PopoverTitle>
+ <ImageInfoContent asset={asset} usages={usages} />
+ </PopoverContent>
+ </Popover>
+ {usages.length === 0 && (
+ <UsageDot css={{ position: "absolute", top: 9, right: 9 }} />
+ )}
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/shared/image-manager/image-manager.tsx b/apps/builder/app/builder/shared/image-manager/image-manager.tsx
index 5549e94fd5..ddbcb94b3c 100644
--- a/apps/builder/app/builder/shared/image-manager/image-manager.tsx
+++ b/apps/builder/app/builder/shared/image-manager/image-manager.tsx
@@ -11,12 +11,7 @@ import {
acceptToMimePatterns,
doesAssetMatchMimePatterns,
} from "@webstudio-is/asset-uploader";
-import {
- AssetsShell,
- type AssetContainer,
- useAssets,
- deleteAssets,
-} from "../assets";
+import { AssetsShell, type AssetContainer, useAssets } from "../assets";
import { ImageThumbnail } from "./image-thumbnail";
const useLogic = ({
@@ -85,7 +80,6 @@ const useLogic = ({
return {
searchProps,
- handleDelete: deleteAssets,
filteredItems,
handleSelect,
selectedIndex,
@@ -99,13 +93,10 @@ type ImageManagerProps = {
};
export const ImageManager = ({ accept, onChange }: ImageManagerProps) => {
- const {
- handleDelete,
- handleSelect,
- filteredItems,
- searchProps,
- selectedIndex,
- } = useLogic({ onChange, accept });
+ const { handleSelect, filteredItems, searchProps, selectedIndex } = useLogic({
+ onChange,
+ accept,
+ });
// https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/accept
// https://github.com/webstudio-is/webstudio/blob/83503e39b0e1561ea93cfcff92aa35b54c15fefa/packages/sdk-components-react/src/video.ws.ts#L34
@@ -138,7 +129,6 @@ export const ImageManager = ({ accept, onChange }: ImageManagerProps) => {
<ImageThumbnail
key={assetContainer.asset.id}
assetContainer={assetContainer}
- onDelete={handleDelete}
onSelect={handleSelect}
onChange={(assetContainer) => {
if (assetContainer.asset.type === "image") {
diff --git a/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsx b/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsx
index e2a4ff2dd6..a12b02972a 100644
--- a/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsx
+++ b/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsx
@@ -1,7 +1,7 @@
import type { KeyboardEvent, FocusEvent } from "react";
import { Box, styled } from "@webstudio-is/design-system";
import { UploadingAnimation } from "./uploading-animation";
-import { ImageInfoTrigger, imageInfoTriggerCssVars } from "./image-info-tigger";
+import { ImageInfo, imageInfoCssVars } from "./image-info";
import type { AssetContainer } from "~/builder/shared/assets";
import { Filename } from "./filename";
import { Image } from "./image";
@@ -73,7 +73,7 @@ const ThumbnailContainer = styled(Box, {
overflow: "hidden",
padding: 2,
"&:hover": {
- ...imageInfoTriggerCssVars({ show: true }),
+ ...imageInfoCssVars({ show: true }),
backgroundColor: theme.colors.backgroundAssetcardHover,
},
variants: {
@@ -87,7 +87,7 @@ const ThumbnailContainer = styled(Box, {
outline: `1px solid ${theme.colors.borderFocus}`,
outlineOffset: -1,
backgroundColor: theme.colors.backgroundAssetcardHover,
- ...imageInfoTriggerCssVars({ show: true }),
+ ...imageInfoCssVars({ show: true }),
},
},
},
@@ -102,7 +102,6 @@ const Thumbnail = styled(Box, {
type ImageThumbnailProps = {
assetContainer: AssetContainer;
- onDelete: (ids: Array<string>) => void;
onSelect: (assetContainer?: AssetContainer) => void;
onChange?: (assetContainer: AssetContainer) => void;
state?: "selected";
@@ -110,7 +109,6 @@ type ImageThumbnailProps = {
export const ImageThumbnail = ({
assetContainer,
- onDelete,
onSelect,
onChange,
state,
@@ -175,12 +173,7 @@ export const ImageThumbnail = ({
<Filename variant={"tiny"}>{name}</Filename>
</Box>
{assetContainer.status === "uploaded" && (
- <ImageInfoTrigger
- asset={assetContainer.asset}
- onDelete={(ids) => {
- onDelete(ids);
- }}
- />
+ <ImageInfo asset={assetContainer.asset} />
)}
{isUploading && <UploadingAnimation />}
</ThumbnailContainer>
diff --git a/apps/builder/app/shared/shim.ts b/apps/builder/app/shared/shim.ts
index 4ddf0d66a5..8490300fcf 100644
--- a/apps/builder/app/shared/shim.ts
+++ b/apps/builder/app/shared/shim.ts
@@ -59,3 +59,17 @@ export const objectGroupBy = <Item, Key>(
) => {
return Object.fromEntries(mapGroupBy(array, getKey));
};
+
+// https://github.com/tc39/proposal-upsert
+export const mapGetOrInsert = <Key, Value>(
+ map: Map<Key, Value>,
+ key: Key,
+ defaultValue: Value
+): Value => {
+ let value = map.get(key);
+ if (value === undefined) {
+ value = defaultValue;
+ map.set(key, value);
+ }
+ return value;
+};
diff --git a/packages/icons/src/index.stories.tsx b/packages/icons/src/index.stories.tsx
index 693c1dc9a8..b21029e304 100644
--- a/packages/icons/src/index.stories.tsx
+++ b/packages/icons/src/index.stories.tsx
@@ -33,7 +33,7 @@ export const Icons = ({ testColor }: { testColor: boolean }): ReactNode => {
justifyContent: "center",
}}
>
- <Icon width="32" height="32" fill="black" color="black" />
+ <Icon width="32" height="32" color="black" />
<div
style={{
marginTop: 16,