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
Use resizer when we are rendering the thumbnails in image manager (#642)
Ivan Starkov86506a7fd3de
diff --git a/apps/designer/app/designer/features/props-panel/control.tsx b/apps/designer/app/designer/features/props-panel/control.tsxindex 0386d7f49a..f8ff70cf6d 100644--- a/apps/designer/app/designer/features/props-panel/control.tsx+++ b/apps/designer/app/designer/features/props-panel/control.tsx@@ -157,10 +157,8 @@ const ImageControl = ({ asset, onChange }: ImageControlProps) => {title="Images"content={<ImageManager- onChange={(clientAsset) => {- if (clientAsset.status === "uploaded") {- onChange(clientAsset.asset);- }+ onChange={(asset) => {+ onChange(asset);}}/>}diff --git a/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsx b/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsxindex b26d60678d..bf30d49346 100644--- a/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsx+++ b/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsx@@ -22,17 +22,17 @@ const allFontWeights: Array<FontWeightItem> = (const useAvailableFontWeights = (currentFamily: string): Array<FontWeightItem> => {- const { assets } = useAssets("font");+ const { assetContainers } = useAssets("font");// Find all font weights that are available for the current font family.return useMemo(() => {const found = allFontWeights.filter((option) => {- return assets.find((clientAsset) => {- if (clientAsset.status !== "uploaded") {+ return assetContainers.find((assetContainer) => {+ if (assetContainer.status !== "uploaded") {return false;}- const { asset } = clientAsset;+ const { asset } = assetContainer;return ("meta" in asset &&@@ -43,7 +43,7 @@ const useAvailableFontWeights = (});});return found.length === 0 ? allFontWeights : found;- }, [currentFamily, assets]);+ }, [currentFamily, assetContainers]);};const useLabels = (diff --git a/apps/designer/app/designer/features/style-panel/controls/image/image-control.tsx b/apps/designer/app/designer/features/style-panel/controls/image/image-control.tsxindex 1b7773e3a8..a63af97951 100644--- a/apps/designer/app/designer/features/style-panel/controls/image/image-control.tsx+++ b/apps/designer/app/designer/features/style-panel/controls/image/image-control.tsx@@ -12,7 +12,7 @@ export const ImageControl = ({setProperty,styleConfig,}: ControlProps) => {- const { assets } = useAssets("image");+ const { assetContainers } = useAssets("image");// @todo show which instance we inherited the value fromconst value = getFinalValue({currentStyle,@@ -26,9 +26,8 @@ export const ImageControl = ({const setValue = setProperty(styleConfig.property);- const selectedAsset = assets.find(- (clientAsset) =>- (clientAsset.asset?.id ?? clientAsset.preview?.id) === toValue(value)+ const selectedAsset = assetContainers.find(+ (assetContainer) => assetContainer.asset.id === toValue(value));return (@@ -36,16 +35,14 @@ export const ImageControl = ({title="Images"content={<ImageManager- onChange={(clientAsset) => {- if (clientAsset.status === "uploaded") {- // @todo looks like a bug fix next PRs- setValue(clientAsset.asset.id);- }+ onChange={(asset) => {+ // @todo looks like a bug fix next PRs+ setValue(asset.id);}}/>}>- <TextField defaultValue={selectedAsset?.asset?.name} />+ <TextField defaultValue={selectedAsset?.asset.name} /></ValuePickerPopover>);};diff --git a/apps/designer/app/designer/shared/assets/types.ts b/apps/designer/app/designer/shared/assets/types.tsindex 2840f5609d..0b691a0909 100644--- a/apps/designer/app/designer/shared/assets/types.ts+++ b/apps/designer/app/designer/shared/assets/types.ts@@ -5,39 +5,28 @@ type PreviewAsset = Pick<"path" | "name" | "id" | "format" | "description">;-export type UploadedClientAsset = {+export type UploadedAssetContainer = {status: "uploaded";asset: Asset;- preview: PreviewAsset | undefined;};-export type UploadingClientAsset = {+export type UploadingAssetContainer = {status: "uploading";- asset: Asset | undefined;- preview: PreviewAsset;+ asset: Asset | PreviewAsset;};/*** Used for optimistic UI only**/-export type DeletingClientAsset = {+export type DeletingAssetContainer = {status: "deleting";asset: Asset;- preview: PreviewAsset | undefined;};-/**- * On the client side, we need more information about the asset than the server provides.- */-export type ClientAsset =- | UploadedClientAsset- | UploadingClientAsset- | DeletingClientAsset;-/*** Assets that can be shown in the UI*/-export type RenderableAsset = UploadedClientAsset | UploadingClientAsset;+export type AssetContainer = UploadedAssetContainer | UploadingAssetContainer;export type ActionData = {uploadedAssets?: Array<Asset>;diff --git a/apps/designer/app/designer/shared/assets/update-state-assets.test.ts b/apps/designer/app/designer/shared/assets/update-asset-containers.test.tssimilarity index 84%rename from apps/designer/app/designer/shared/assets/update-state-assets.test.tsrename to apps/designer/app/designer/shared/assets/update-asset-containers.test.tsindex c8fdeaff9d..00c9f202c6 100644--- a/apps/designer/app/designer/shared/assets/update-state-assets.test.ts+++ b/apps/designer/app/designer/shared/assets/update-asset-containers.test.ts@@ -1,17 +1,16 @@import { describe, test, expect } from "@jest/globals";import type { Asset } from "@webstudio-is/asset-uploader";import {- UploadedClientAsset,- UploadingClientAsset,- DeletingClientAsset,- ClientAsset,+ UploadedAssetContainer,+ UploadingAssetContainer,+ DeletingAssetContainer,+ AssetContainer,} from "./types";-import { updateStateAssets } from "./update-state-assets";+import { updateStateAssets } from "./update-asset-containers";-const getAssetId = (clientAsset: ClientAsset): string =>- clientAsset.status === "uploading"- ? clientAsset.preview.id- : clientAsset.asset.id;+const getAssetId = (+ assetContainer: AssetContainer | DeletingAssetContainer+): string => assetContainer.asset.id;const createServerAsset = (id: string, name?: string): Asset => ({id,@@ -27,32 +26,29 @@ const createServerAsset = (id: string, name?: string): Asset => ({path: "",});-const createAsset = (id: string, name?: string): UploadedClientAsset => ({+const createAsset = (id: string, name?: string): UploadedAssetContainer => ({status: "uploaded",asset: createServerAsset(id, name),- preview: undefined,});-const createPreviewAsset = (id: string): UploadingClientAsset => {+const createPreviewAsset = (id: string): UploadingAssetContainer => {return {status: "uploading",- asset: undefined,- preview: createAsset(id).asset,+ asset: createAsset(id).asset,};};const createPreviewAndAsset = (id: string,name?: string-): UploadedClientAsset => {+): UploadedAssetContainer => {return {status: "uploaded",asset: createAsset(id, name).asset,- preview: createAsset(id).asset,};};-const createDeletingAsset = (id: string): DeletingClientAsset => {+const createDeletingAsset = (id: string): DeletingAssetContainer => {return {...createAsset(id),status: "deleting",diff --git a/apps/designer/app/designer/shared/assets/update-state-assets.ts b/apps/designer/app/designer/shared/assets/update-asset-containers.tssimilarity index 79%rename from apps/designer/app/designer/shared/assets/update-state-assets.tsrename to apps/designer/app/designer/shared/assets/update-asset-containers.tsindex ae32ab649d..e6682391ad 100644--- a/apps/designer/app/designer/shared/assets/update-state-assets.ts+++ b/apps/designer/app/designer/shared/assets/update-asset-containers.ts@@ -1,6 +1,6 @@import deepEqual from "fast-deep-equal";import type { Asset } from "@webstudio-is/asset-uploader";-import { ClientAsset } from "./types";+import { AssetContainer, DeletingAssetContainer } from "./types";/*** Update local assets (containing optimistic data) with data from the server@@ -10,16 +10,17 @@ import { ClientAsset } from "./types";* - updateAssets(assets, data) must be referentially equal to updateAssets(updateAssets(assets, data), data)*/export const updateStateAssets = <T>(- clientAssets: ClientAsset[],+ assetContainer: (AssetContainer | DeletingAssetContainer)[],serverAssets: Asset[]) => {- let nextAssets: ClientAsset[] = [...clientAssets];+ let nextAssets: (AssetContainer | DeletingAssetContainer)[] = [+ ...assetContainer,+ ];// Merging data with existing assets, trying to preserve sortingfor (const serverAsset of serverAssets) {// The same asset is already in the assetsconst sameIndex = nextAssets.findIndex(- (nextAsset) =>- (nextAsset.asset?.id ?? nextAsset.preview?.id) === serverAsset.id+ (nextAsset) => nextAsset.asset.id === serverAsset.id);if (sameIndex !== -1) {@@ -27,8 +28,6 @@ export const updateStateAssets = <T>(nextAssets[sameIndex] = {status: "uploaded",asset: serverAsset,- // preserve preview to avoid image flickering- preview: nextAssets[sameIndex].preview,};}continue;@@ -38,7 +37,6 @@ export const updateStateAssets = <T>(nextAssets.push({status: "uploaded",asset: serverAsset,- preview: undefined,});}@@ -57,8 +55,8 @@ export const updateStateAssets = <T>(return true;});- if (deepEqual(nextAssets, clientAssets)) {- return clientAssets;+ if (deepEqual(nextAssets, assetContainer)) {+ return assetContainer;}return nextAssets;diff --git a/apps/designer/app/designer/shared/assets/use-assets.tsx b/apps/designer/app/designer/shared/assets/use-assets.tsxindex ad85ea8f42..377fe9086f 100644--- a/apps/designer/app/designer/shared/assets/use-assets.tsx+++ b/apps/designer/app/designer/shared/assets/use-assets.tsx@@ -16,12 +16,13 @@ import {import { type FontFormat, FONT_FORMATS } from "@webstudio-is/fonts";import { toast } from "@webstudio-is/design-system";import { restAssetsPath } from "~/shared/router-utils";-import { useClientAssets, useProject } from "../nano-states";+import { useAssetsContainer, useProject } from "../nano-states";import { sanitizeS3Key } from "@webstudio-is/asset-uploader";import type {- RenderableAsset,- ClientAsset,- UploadingClientAsset,+ AssetContainer,+ DeletingAssetContainer,+ UploadedAssetContainer,+ UploadingAssetContainer,} from "./types";import { usePersistentFetcher } from "~/shared/fetcher";import type { ActionData } from "~/designer/shared/assets";@@ -33,7 +34,7 @@ import {import { Publish } from "~/shared/pubsub";import { useFetcher } from "@remix-run/react";import warnOnce from "warn-once";-import { updateStateAssets } from "./update-state-assets";+import { updateStateAssets } from "./update-asset-containers";declare module "~/shared/pubsub" {export interface PubsubMap {@@ -42,16 +43,24 @@ declare module "~/shared/pubsub" {}export const usePublishAssets = (publish: Publish) => {- const [clientAssets] = useClientAssets();+ const [assetContainers] = useAssetsContainer();useEffect(() => {publish({type: "updateAssets",- payload: clientAssets- .filter((clientAsset) => clientAsset.status === "uploaded")- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- for "status" === "uploaded" asset is defined- .map((clientAsset) => clientAsset.asset!),+ payload: assetContainers+ .filter((assetContainer) => assetContainer.status === "uploaded")+ .map((assetContainer) => {+ // This check is only to fix that ts can't detect type based on the filter above+ if (assetContainer.status !== "uploaded") {+ throw new Error(+ `Impossible, asset must have status "uploaded" see filter above`+ );+ }++ return assetContainer.asset;+ }),});- }, [clientAssets, publish]);+ }, [assetContainers, publish]);};export type UploadData = FetcherData<ActionData>;@@ -59,11 +68,11 @@ export type UploadData = FetcherData<ActionData>;const toUploadingAssetsAndFormData = (type: AssetType,files: File[]-): Promise<[UploadingClientAsset, FormData][]> => {- const assets: Array<Promise<[UploadingClientAsset, FormData]>> = [];+): Promise<[UploadingAssetContainer, FormData][]> => {+ const assets: Array<Promise<[UploadingAssetContainer, FormData]>> = [];for (const file of files) {- const promise = new Promise<[UploadingClientAsset, FormData]>(+ const promise = new Promise<[UploadingAssetContainer, FormData]>((resolve, reject) => {const reader = new FileReader();reader.addEventListener("load", (event) => {@@ -83,8 +92,7 @@ const toUploadingAssetsAndFormData = (resolve([{status: "uploading",- asset: undefined,- preview: {+ asset: {format: file.type.split("/")[1],path: String(dataUri),name: file.name,@@ -124,7 +132,7 @@ const getFilesFromInput = (type: AssetType, input: HTMLInputElement) => {type AssetsContext = {handleSubmit: (type: AssetType, files: File[]) => Promise<void>;- assets: Array<ClientAsset>;+ assetContainers: Array<AssetContainer | DeletingAssetContainer>;handleDelete: (ids: Array<string>) => void;};@@ -132,29 +140,32 @@ const Context = createContext<AssetsContext | undefined>(undefined);export const AssetsProvider = ({ children }: { children: ReactNode }) => {const [project] = useProject();- const [clientAssets, setClientAssets] = useClientAssets();+ const [assetContainers, setAssetContainers] = useAssetsContainer();const { load, data: serverAssets } = useFetcher<Asset[]>();const submit = usePersistentFetcher();- const assetsRef = useRef(clientAssets);+ const assetContainersRef = useRef(assetContainers);const action = project && restAssetsPath({ projectId: project.id });- assetsRef.current = clientAssets;+ assetContainersRef.current = assetContainers;useEffect(() => {- if (action && clientAssets.length === 0) {+ if (action && assetContainers.length === 0) {load(action);}- }, [action, clientAssets.length, load]);+ }, [action, assetContainers.length, load]);useEffect(() => {if (serverAssets !== undefined) {- const nextAssets = updateStateAssets(clientAssets, serverAssets);+ const nextAssetContainers = updateStateAssets(+ assetContainers,+ serverAssets+ );- if (nextAssets !== clientAssets) {- setClientAssets(nextAssets);+ if (nextAssetContainers !== assetContainers) {+ setAssetContainers(nextAssetContainers);}}- }, [serverAssets, clientAssets, setClientAssets]);+ }, [serverAssets, assetContainers, setAssetContainers]);const handleDeleteAfterSubmit = (data: UploadData) => {// We need to remove assets only at updateStateAssets.@@ -166,24 +177,27 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {if (data.status === "error") {// We don't know what's wrong, remove the "deleting" status from assets and wait for the load to fix it- const assets = assetsRef.current;- const nextAssets = assets.map((asset) => {- if (asset.status === "deleting") {- const newAsset: ClientAsset = { ...asset, status: "uploaded" };- return newAsset;+ const assetContainers = assetContainersRef.current;+ const nextAssetContainers = assetContainers.map((assetContainer) => {+ if (assetContainer.status === "deleting") {+ const uploadedAssetContainer: UploadedAssetContainer = {+ ...assetContainer,+ status: "uploaded",+ };+ return uploadedAssetContainer;}- return asset;+ return assetContainer;});- setClientAssets(nextAssets);+ setAssetContainers(nextAssetContainers);return toastUnknownFieldErrors(normalizeErrors(data.errors), []);}};const handleAfterSubmit = (assetId: string) => (data: UploadData) => {- const assets = assetsRef.current;+ const assetContainers = assetContainersRef.current;if (action) {load(action);@@ -191,10 +205,11 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {if (data.status === "error") {// We don't know what's wrong, remove uploading asset and wait for the load to fix it- setClientAssets(- assets.filter(- (asset) =>- asset.status !== "uploading" || asset.preview.id !== assetId+ setAssetContainers(+ assetContainers.filter(+ (assetContainer) =>+ assetContainer.status !== "uploading" ||+ assetContainer.asset.id !== assetId));@@ -213,49 +228,53 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {toast.error("Could not upload an asset");// remove uploading asset and wait for the load to fix it- setClientAssets(- assets.filter(- (asset) =>- asset.status !== "uploading" || asset.preview.id !== assetId+ setAssetContainers(+ assetContainers.filter(+ (assetContainer) =>+ assetContainer.status !== "uploading" ||+ assetContainer.asset.id !== assetId));return;}- setClientAssets(- assets.map((asset) => {- if (asset.status === "uploading" && asset.preview.id === assetId) {+ setAssetContainers(+ assetContainers.map((assetContainer) => {+ if (+ assetContainer.status === "uploading" &&+ assetContainer.asset.id === assetId+ ) {// We can start using the uploaded asset for image previews etc- return { ...asset, asset: uploadedAsset };+ return { ...assetContainer, asset: uploadedAsset };}- return asset;+ return assetContainer;}));};const handleDelete = (ids: Array<string>) => {const formData = new FormData();- const assets = assetsRef.current;+ const assetContainer = assetContainersRef.current;- const nextAssets = [...assets];+ const nextAssetContainers = [...assetContainer];for (const id of ids) {formData.append("assetId", id);// Mark assets as deleting- const index = nextAssets.findIndex(- (nextAsset) => nextAsset.asset?.id === id+ const index = nextAssetContainers.findIndex(+ (nextAssetContainer) => nextAssetContainer.asset.id === id);if (index !== -1) {- const asset = nextAssets[index];+ const asset = nextAssetContainers[index];if (asset.status === "uploaded") {- const newAsset: ClientAsset = {+ const newAsset: DeletingAssetContainer = {...asset,status: "deleting",};- nextAssets[index] = newAsset;+ nextAssetContainers[index] = newAsset;continue;}@@ -263,7 +282,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {}}- setClientAssets(nextAssets);+ setAssetContainers(nextAssetContainers);submit<UploadData>(formData,@@ -279,13 +298,16 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {files);- const assets = assetsRef.current;- setClientAssets([+ const assets = assetContainersRef.current;+ setAssetContainers([...uploadingAssetsAndFormData.map(([previewAsset]) => previewAsset),...assets,]);- for (const [uploadingAsset, formData] of uploadingAssetsAndFormData) {+ for (const [+ uploadingAssetContainer,+ formData,+ ] of uploadingAssetsAndFormData) {submit<UploadData>(formData,{@@ -293,7 +315,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {action,encType: "multipart/form-data",},- handleAfterSubmit(uploadingAsset.preview.id)+ handleAfterSubmit(uploadingAssetContainer.asset.id));}} catch (error) {@@ -305,16 +327,16 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {return (<Context.Provider- value={{ handleSubmit, assets: clientAssets, handleDelete }}+ value={{ handleSubmit, assetContainers: assetContainers, handleDelete }}>{children}</Context.Provider>);};-const filterByType = (clientAssets: RenderableAsset[], type: AssetType) => {- return clientAssets.filter((clientAsset) => {- const format = clientAsset.asset?.format ?? clientAsset.preview?.format;+const filterByType = (assetContainers: AssetContainer[], type: AssetType) => {+ return assetContainers.filter((assetContainer) => {+ const format = assetContainer.asset.format;const isFont = FONT_FORMATS.has(format as FontFormat);if (type === "font") {@@ -326,36 +348,36 @@ const filterByType = (clientAssets: RenderableAsset[], type: AssetType) => {};export const useAssets = (type: AssetType) => {- const assetsContext = useContext(Context);- if (!assetsContext) {+ const assetContainersContext = useContext(Context);+ if (!assetContainersContext) {throw new Error("useAssets is used without AssetsProvider");}const assetsByType = useMemo(() => {// In no case we need to have access to deleting assets// But we need them for optiistic updates, filter out here- const activeAssets: RenderableAsset[] = [];+ const assetContainers: AssetContainer[] = [];- for (const asset of assetsContext.assets) {+ for (const asset of assetContainersContext.assetContainers) {if (asset.status !== "deleting") {- activeAssets.push(asset);+ assetContainers.push(asset);}}- return filterByType(activeAssets, type);- }, [assetsContext.assets, type]);+ return filterByType(assetContainers, type);+ }, [assetContainersContext.assetContainers, type]);const handleSubmit = (input: HTMLInputElement) => {const formsData = getFilesFromInput(type, input);- assetsContext.handleSubmit(type, formsData);+ assetContainersContext.handleSubmit(type, formsData);};return {/*** Already loaded assets or assets that are being uploaded*/- assets: assetsByType,+ assetContainers: assetsByType,handleSubmit,- handleDelete: assetsContext.handleDelete,+ handleDelete: assetContainersContext.handleDelete,};};diff --git a/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx b/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsxindex 200a4c24ee..bb091229d4 100644--- a/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx+++ b/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx@@ -29,9 +29,10 @@ const useLogic = ({onChange: (value: string) => void;value: string;}) => {- const { assets, handleDelete: handleDeleteAssets } = useAssets("font");+ const { assetContainers, handleDelete: handleDeleteAssets } =+ useAssets("font");const [selectedIndex, setSelectedIndex] = useState(-1);- const fontItems = useMemo(() => toItems(assets), [assets]);+ const fontItems = useMemo(() => toItems(assetContainers), [assetContainers]);const { filteredItems, resetFilteredItems, setFilteredItems } = useFilter({items: fontItems,onReset() {@@ -66,7 +67,7 @@ const useLogic = ({const handleDelete = (index: number) => {const family = groupedItems[index].label;- const ids = filterIdsByFamily(family, assets);+ const ids = filterIdsByFamily(family, assetContainers);handleDeleteAssets(ids);if (index === currentIndex) {setCurrentIndex(-1);diff --git a/apps/designer/app/designer/shared/fonts-manager/item-utils.ts b/apps/designer/app/designer/shared/fonts-manager/item-utils.tsindex 8353c11529..9767d78338 100644--- a/apps/designer/app/designer/shared/fonts-manager/item-utils.ts+++ b/apps/designer/app/designer/shared/fonts-manager/item-utils.ts@@ -1,25 +1,27 @@import { SYSTEM_FONTS } from "@webstudio-is/fonts";import { matchSorter } from "match-sorter";-import { RenderableAsset } from "../assets";+import { AssetContainer } from "../assets";export type Item = {label: string;type: "uploaded" | "system";};-export const toItems = (clientAssets: Array<RenderableAsset>): Array<Item> => {+export const toItems = (+ assetContainers: Array<AssetContainer>+): Array<Item> => {const system = Array.from(SYSTEM_FONTS.keys()).map((label) => ({label,type: "system",}));// We can have 2+ assets with the same family name, so we use a map to dedupe.const uploaded = new Map();- for (const clientAsset of clientAssets) {- if (clientAsset.status !== "uploaded") {+ for (const assetContainer of assetContainers) {+ if (assetContainer.status !== "uploaded") {continue;}- const { asset } = clientAsset;+ const { asset } = assetContainer;// @todo need to teach ts the right type from useAssetsif ("meta" in asset && "family" in asset.meta) {uploaded.set(asset.meta.family, {@@ -33,16 +35,16 @@ export const toItems = (clientAssets: Array<RenderableAsset>): Array<Item> => {export const filterIdsByFamily = (family: string,- clientAssets: Array<RenderableAsset>+ assetContainers: Array<AssetContainer>) => {// One family may have multiple assets for different formats, so we need to find them all.return (- clientAssets- .filter((clientAsset) => {- if (clientAsset.status !== "uploaded") {+ assetContainers+ .filter((assetContainer) => {+ if (assetContainer.status !== "uploaded") {return false;}- const { asset } = clientAsset;+ const { asset } = assetContainer;// @todo need to teach TS the right type from useAssetsreturn ("meta" in asset &&@@ -51,7 +53,7 @@ export const filterIdsByFamily = ();})// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- we filtered out non uploaded items- .map((clientAssets) => clientAssets.asset!.id)+ .map((assetContainer) => assetContainer.asset!.id));};diff --git a/apps/designer/app/designer/shared/image-manager/image-manager.tsx b/apps/designer/app/designer/shared/image-manager/image-manager.tsxindex 9bbc6f2c8c..e959999850 100644--- a/apps/designer/app/designer/shared/image-manager/image-manager.tsx+++ b/apps/designer/app/designer/shared/image-manager/image-manager.tsx@@ -2,35 +2,29 @@ import { useState } from "react";import { findNextListIndex, Grid } from "@webstudio-is/design-system";import {AssetsShell,- type RenderableAsset,+ type AssetContainer,useAssets,useSearch,} from "../assets";import { useFilter } from "../assets/use-filter";import { ImageThumbnail } from "./image-thumbnail";import { matchSorter } from "match-sorter";+import { Asset } from "@webstudio-is/asset-uploader";-const filterItems = (search: string, items: RenderableAsset[]) => {+const filterItems = (search: string, items: AssetContainer[]) => {return matchSorter(items, search, {- keys: [- (item) =>- item.status === "uploading" ? item.preview.name : item.asset.name,- ],+ keys: [(item) => item.asset.name],});};-const useLogic = ({- onChange,-}: {- onChange?: (asset: RenderableAsset) => void;-}) => {- const { assets, handleDelete } = useAssets("image");+const useLogic = ({ onChange }: { onChange?: (asset: Asset) => void }) => {+ const { assetContainers, handleDelete } = useAssets("image");const [selectedIndex, setSelectedIndex] = useState(-1);// @todo filter out deleting assetsconst { filteredItems, resetFilteredItems, setFilteredItems } = useFilter({- items: assets,+ items: assetContainers,onReset() {searchProps.onCancel();},@@ -42,15 +36,15 @@ const useLogic = ({if (search === "") {return resetFilteredItems();}- const items = filterItems(search, assets);+ const items = filterItems(search, assetContainers);setFilteredItems(items);},onSelect(direction) {if (direction === "current") {setSelectedIndex(selectedIndex);- const asset = filteredItems[selectedIndex];- if (asset?.status === "uploaded") {- onChange?.(asset);+ const assetContainer = filteredItems[selectedIndex];+ if (assetContainer.status === "uploaded") {+ onChange?.(assetContainer.asset);}return;}@@ -63,11 +57,9 @@ const useLogic = ({},});- const handleSelect = (clientAsset?: RenderableAsset) => {+ const handleSelect = (assetContainer?: AssetContainer) => {const selectedIndex = filteredItems.findIndex(- (item) =>- (item.asset?.id ?? item.preview?.id) ===- (clientAsset?.asset?.id ?? clientAsset?.preview?.id)+ (item) => item.asset.id === assetContainer?.asset.id);setSelectedIndex(selectedIndex);};@@ -82,7 +74,7 @@ const useLogic = ({};type ImageManagerProps = {- onChange?: (asset: RenderableAsset) => void;+ onChange?: (asset: Asset) => void;};export const ImageManager = ({ onChange }: ImageManagerProps) => {@@ -101,13 +93,18 @@ export const ImageManager = ({ onChange }: ImageManagerProps) => {type="image"><Grid columns={3} gap={2}>- {filteredItems.map((clientAsset, index) => (+ {filteredItems.map((assetContainer, index) => (<ImageThumbnail- key={clientAsset.asset?.id ?? clientAsset.preview?.id}- asset={clientAsset}+ key={assetContainer.asset.id}+ assetContainer={assetContainer}onDelete={handleDelete}onSelect={handleSelect}- onChange={onChange}+ onChange={(assetContainer) => {+ // @todo we probably should not allow select uploading images too+ if (assetContainer.status === "uploaded") {+ onChange?.(assetContainer.asset);+ }+ }}state={index === selectedIndex ? "selected" : undefined}/>))}diff --git a/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsx b/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsxindex de1b2a72c1..3db3707d1a 100644--- a/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsx+++ b/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsx@@ -1,33 +1,10 @@-import {- useEffect,- useState,- type KeyboardEvent,- type FocusEvent,-} from "react";+import { type KeyboardEvent, type FocusEvent } from "react";import { Box, styled } from "@webstudio-is/design-system";-import placeholderImage from "~/shared/images/image-placeholder.svg";-import brokenImage from "~/shared/images/broken-image-placeholder.svg";import { UploadingAnimation } from "./uploading-animation";import { ImageInfoTrigger, imageInfoTriggerCssVars } from "./image-info-tigger";-import type { RenderableAsset } from "~/designer/shared/assets";+import type { AssetContainer } from "~/designer/shared/assets";import { Filename } from "./filename";--const useImageWithFallback = ({- path = placeholderImage,-}: {- path?: string;-}) => {- const [src, setSrc] = useState(placeholderImage);-- useEffect(() => {- const newImage = new Image();- newImage.onload = () => setSrc(path);- newImage.onerror = () => setSrc(brokenImage);- newImage.src = path;- }, [path]);-- return src;-};+import { Image } from "./image";const ThumbnailContainer = styled(Box, {position: "relative",@@ -59,55 +36,41 @@ const ThumbnailContainer = styled(Box, {});const Thumbnail = styled(Box, {- width: "$spacing$19",+ width: "100%",height: "$spacing$19",- backgroundSize: "contain",- backgroundRepeat: "no-repeat",- backgroundPosition: "center",flexShrink: 0,+ position: "relative",});type ImageThumbnailProps = {- asset: RenderableAsset;+ assetContainer: AssetContainer;onDelete: (ids: Array<string>) => void;- onSelect: (asset?: RenderableAsset) => void;- onChange?: (asset: RenderableAsset) => void;+ onSelect: (assetContainer?: AssetContainer) => void;+ onChange?: (assetContainer: AssetContainer) => void;state?: "selected";};export const ImageThumbnail = ({- asset: clientAsset,+ assetContainer,onDelete,onSelect,onChange,state,}: ImageThumbnailProps) => {- const asset =- clientAsset.status === "uploading"- ? clientAsset.preview- : clientAsset.asset;+ const { asset, status } = assetContainer;- const { status } = clientAsset;-- const { path, name } = asset;-- const description =- "description" in asset && asset.description- ? (asset.description as string)- : name;+ const { name, description } = asset;const isUploading = status === "uploading";- const src = useImageWithFallback({ path });-return (<ThumbnailContainer- title={description}+ title={description ?? name}tabIndex={0}status={status}state={state}onFocus={() => {- onSelect?.(clientAsset);+ onSelect?.(assetContainer);}}onBlur={(event: FocusEvent) => {const isFocusWithin = event.currentTarget.contains(event.relatedTarget);@@ -116,19 +79,25 @@ export const ImageThumbnail = ({}}}onKeyDown={(event: KeyboardEvent) => {- if (event.code === "Enter" && clientAsset.status === "uploaded") {- onChange?.(clientAsset);+ if (event.code === "Enter" && assetContainer.status === "uploaded") {+ onChange?.(assetContainer);}}}><Thumbnail- css={{ backgroundImage: `url("${src}")` }}onClick={() => {- if (clientAsset.status === "uploaded") {- onChange?.(clientAsset);+ if (assetContainer.status === "uploaded") {+ onChange?.(assetContainer);}}}- />+ >+ <Image+ assetContainer={assetContainer}+ alt={description ?? name}+ // width={64} used for Image optimizations it should be approximately equal to the width of the picture on the screen in px+ width={64}+ />+ </Thumbnail><Boxcss={{width: "100%",@@ -138,9 +107,9 @@ export const ImageThumbnail = ({><Filename variant={"tiny"}>{name}</Filename></Box>- {clientAsset.status === "uploaded" && (+ {assetContainer.status === "uploaded" && (<ImageInfoTrigger- asset={clientAsset.asset}+ asset={assetContainer.asset}onDelete={(ids) => {onDelete(ids);}}diff --git a/apps/designer/app/designer/shared/image-manager/image.tsx b/apps/designer/app/designer/shared/image-manager/image.tsxnew file mode 100644index 0000000000..aef594c84d--- /dev/null+++ b/apps/designer/app/designer/shared/image-manager/image.tsx@@ -0,0 +1,72 @@+import { useMemo } from "react";+import { styled } from "@webstudio-is/design-system";+import { Image as WebstudioImage, loaders } from "@webstudio-is/image";+import env from "~/shared/env";+import type { AssetContainer } from "../assets";+import brokenImage from "~/shared/images/broken-image-placeholder.svg";++type ImageProps = {+ assetContainer: AssetContainer;+ alt: string;+ width: number;+};++const StyledWebstudioImage = styled(WebstudioImage, {+ position: "absolute",+ width: "100%",+ height: "100%",+ objectFit: "contain",++ // This is shown only if an image was not loaded and broken+ // From the spec:+ // - The pseudo-elements generated by ::before and ::after are contained by the element's formatting box,+ // and thus don't apply to "replaced" elements such as <img>, or to <br> elements+ // Not in spec but supported by all browsers:+ // - broken image is not a "replaced" element so this style is applied+ "&::after": {+ content: "' '",+ position: "absolute",+ width: "100%",+ height: "100%",+ left: 0,+ top: 0,+ backgroundSize: "contain",+ backgroundRepeat: "no-repeat",+ backgroundPosition: "center",+ backgroundImage: `url(${brokenImage})`,+ },+});++export const Image = ({ assetContainer, alt, width }: ImageProps) => {+ const { asset } = assetContainer;+ const optimize = assetContainer.status === "uploaded";+ const remoteLocation =+ assetContainer.status === "uploaded" &&+ assetContainer.asset.location === "REMOTE";++ // Avoid image flickering on switching from preview to asset (during upload)+ // Possible optimisation, we can set it to "sync" only if asset.path has changed or add isNew prop to UploadedAssetContainer+ const decoding = "sync";++ const loader = useMemo(() => {+ if (remoteLocation) {+ return loaders.cloudflareImageLoader({+ resizeOrigin: env.RESIZE_ORIGIN,+ });+ }++ return loaders.localImageLoader();+ }, [remoteLocation]);++ return (+ <StyledWebstudioImage+ key={asset.id}+ loader={loader}+ decoding={decoding}+ src={asset.path}+ width={width}+ optimize={optimize}+ alt={alt}+ />+ );+};diff --git a/apps/designer/app/designer/shared/image-manager/uploading-animation.tsx b/apps/designer/app/designer/shared/image-manager/uploading-animation.tsxindex c2c590c93f..2f597d31c9 100644--- a/apps/designer/app/designer/shared/image-manager/uploading-animation.tsx+++ b/apps/designer/app/designer/shared/image-manager/uploading-animation.tsx@@ -9,7 +9,7 @@ const useFakeProgress = () => {// @todo rewrite this fake indication to show real progressuseInterval(() => {setProgressBarPercentage((percentage) =>- percentage < 60 ? percentage + 1 : percentage+ percentage < 60 ? percentage + 1 : 0);}, 100);@@ -21,9 +21,11 @@ const AnimationContainer = styled("div", {top: 0,left: 0,height: "100%",+ width: "100%",display: "flex",flexDirection: "column",justifyContent: "center",+ alignItems: "center",});export const UploadingAnimation = () => {diff --git a/apps/designer/app/designer/shared/nano-states/index.ts b/apps/designer/app/designer/shared/nano-states/index.tsindex fc9d0e8540..81f0335f7e 100644--- a/apps/designer/app/designer/shared/nano-states/index.ts+++ b/apps/designer/app/designer/shared/nano-states/index.ts@@ -6,7 +6,7 @@ import {} from "@webstudio-is/project";import { type SyncStatus } from "~/shared/sync";import { type Pages, type Project } from "@webstudio-is/project";-import type { ClientAsset } from "../assets";+import type { AssetContainer, DeletingAssetContainer } from "../assets";const selectedInstanceDataContainer = createValueContainer<SelectedInstanceData | undefined@@ -45,8 +45,10 @@ export const useCanvasRect = () => useValue(canvasRectContainer);const syncStatusContainer = createValueContainer<SyncStatus>("idle");export const useSyncStatus = () => useValue(syncStatusContainer);-const clientAssetsContainer = createValueContainer<Array<ClientAsset>>([]);-export const useClientAssets = () => useValue(clientAssetsContainer);+const assetsContainer = createValueContainer<+ Array<AssetContainer | DeletingAssetContainer>+>([]);+export const useAssetsContainer = () => useValue(assetsContainer);const pagesContainer = createValueContainer<Pages | undefined>();export const usePages = () => useValue(pagesContainer);