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: Adds the ability to place images on the canvas immediately during upload (#3546)
Ivan Starkov863bb2a1bc17
diff --git a/apps/builder/app/builder/features/ai/ai-command-bar.tsx b/apps/builder/app/builder/features/ai/ai-command-bar.tsxindex 48e82eb196..7c32f5809f 100644--- a/apps/builder/app/builder/features/ai/ai-command-bar.tsx+++ b/apps/builder/app/builder/features/ai/ai-command-bar.tsx@@ -97,7 +97,7 @@ export const AiCommandBar = ({ isPreviewMode }: { isPreviewMode: boolean }) => {} = useMediaRecorder({onError: (error) => {if (error instanceof DOMException && error.name === "NotAllowedError") {- toast("Please enable your microphone.");+ toast.info("Please enable your microphone.");return;}if (error instanceof Error) {@@ -123,7 +123,7 @@ export const AiCommandBar = ({ isPreviewMode }: { isPreviewMode: boolean }) => {handleAiRequest(newValue);} catch (error) {if (error instanceof RateLimitException) {- toast(+ toast.info(`Temporary AI rate limit reached. Please wait ${formatDistance(Date.now(),new Date(error.meta.reset),@@ -231,7 +231,7 @@ export const AiCommandBar = ({ isPreviewMode }: { isPreviewMode: boolean }) => {}if (error instanceof RateLimitException) {- toast(+ toast.info(`Temporary AI rate limit reached. Please wait ${formatDistance(Date.now(),new Date(error.meta.reset),diff --git a/apps/builder/app/builder/features/project-settings/image-control.tsx b/apps/builder/app/builder/features/project-settings/image-control.tsxindex 350f5ee74b..b8df39c2c1 100644--- a/apps/builder/app/builder/features/project-settings/image-control.tsx+++ b/apps/builder/app/builder/features/project-settings/image-control.tsx@@ -12,8 +12,8 @@ export const ImageControl = (props: {title="Images"content={<ImageManager- onChange={(asset) => {- props.onAssetIdChange(asset.id);+ onChange={(assetId) => {+ props.onAssetIdChange(assetId);}}/>}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.tsxindex 51eaf3db32..1503ce4dae 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@@ -54,9 +54,7 @@ export const SelectAsset = ({ prop, onChange, onDelete, accept }: Props) => {title="Images"content={<ImageManager- onChange={(asset) =>- onChange({ type: "asset", value: asset.id }, asset)- }+ onChange={(assetId) => onChange({ type: "asset", value: assetId })}accept={accept}/>}diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsxindex ac79cfbdf4..3518ff4572 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx@@ -62,27 +62,17 @@ const renderProperty = (onDelete: () => {if (prop) {logic.handleDelete(prop);+ if (component === "Image" && propName === "src") {+ logic.handleDeleteByPropName("width");+ logic.handleDeleteByPropName("height");+ }}},- onChange: (propValue, asset) => {+ onChange: (propValue) => {logic.handleChange({ prop, propName }, propValue);-- // @todo: better way to do this?- if (- component === "Image" &&- propName === "src" &&- asset &&- "width" in asset.meta &&- "height" in asset.meta- ) {- logic.handleChangeByPropName("width", {- value: asset.meta.width,- type: "number",- });- logic.handleChangeByPropName("height", {- value: asset.meta.height,- type: "number",- });+ if (component === "Image" && propName === "src") {+ logic.handleChangeByPropName("width", propValue);+ logic.handleChangeByPropName("height", propValue);}},});diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.tsindex f3cc73c4c2..2af5f7467d 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts@@ -287,6 +287,14 @@ export const usePropsLogic = ({);};+ const handleDeleteByPropName = (propName: string) => {+ const prop = props.find((prop) => prop.name === propName);++ if (prop) {+ deleteProp(prop.id);+ }+ };+const handleDelete = (prop: Prop) => {deleteProp(prop.id);};@@ -296,6 +304,7 @@ export const usePropsLogic = ({handleChange,handleDelete,handleChangeByPropName,+ handleDeleteByPropName,meta,/** Similar to Initial, but displayed as a separate group in UI etc.* Currentrly used only for the ID prop. */diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsxindex 17b4185c43..22e7c98fe1 100644--- a/apps/builder/app/builder/features/settings-panel/shared.tsx+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx@@ -64,7 +64,7 @@ export type ControlProps<Control> = {propName: string;computedValue: unknown;deletable: boolean;- onChange: (value: PropValue, asset?: Asset) => void;+ onChange: (value: PropValue) => void;onDelete: () => void;autoFocus?: boolean;};diff --git a/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx b/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsxindex d3a895e283..89e6329bb1 100644--- a/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx+++ b/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx@@ -92,10 +92,10 @@ export const ImageControl = ({title="Images"content={<ImageManager- onChange={(asset) => {+ onChange={(assetId) => {setValue({type: "image",- value: { type: "asset", value: asset.id },+ value: { type: "asset", value: assetId },});}}/>diff --git a/apps/builder/app/builder/shared/assets/asset-upload.tsx b/apps/builder/app/builder/shared/assets/asset-upload.tsxindex 2f79285257..e2ab98e4ae 100644--- a/apps/builder/app/builder/shared/assets/asset-upload.tsx+++ b/apps/builder/app/builder/shared/assets/asset-upload.tsx@@ -10,7 +10,7 @@ import {import { FONT_MIME_TYPES } from "@webstudio-is/fonts";import { uploadAssets } from "./use-assets";import { $authPermit } from "~/shared/nano-states";-import { imageMimeTypes } from "./image-formats";+import { imageMimeTypes } from "./asset-utils";const maxSize = toBytes(MAX_UPLOAD_SIZE);diff --git a/apps/builder/app/builder/shared/assets/asset-utils.ts b/apps/builder/app/builder/shared/assets/asset-utils.tsnew file mode 100644index 0000000000..403450bfad--- /dev/null+++ b/apps/builder/app/builder/shared/assets/asset-utils.ts@@ -0,0 +1,93 @@+import { nanoid } from "nanoid";++const extensionToMime = new Map([+ [".gif", "image/gif"],+ [".ico", "image/x-icon"],+ [".jpeg", "image/jpeg"],+ [".jpg", "image/jpeg"],+ [".png", "image/png"],+ [".svg", "image/svg+xml"],+ [".webp", "image/webp"],+] as const);++const extensions = [...extensionToMime.keys()];++export const imageMimeTypes = [...extensionToMime.values()];++export const getImageNameAndType = (fileName: string) => {+ const extension = extensions.find((ext) => fileName.endsWith(ext));++ if (extension == null) {+ return;+ }++ return [extensionToMime.get(extension)!, fileName] as const;+};++const extractImageNameAndMimeTypeFromUrl = (url: URL) => {+ const nameFromPath = url.pathname+ .split("/")+ .map(getImageNameAndType)+ .filter(Boolean)[0];++ if (nameFromPath != null) {+ return nameFromPath;+ }++ const nameFromSearchParams = [...url.searchParams.values()]+ .map(getImageNameAndType)+ .filter(Boolean)[0];++ if (nameFromSearchParams != null) {+ return nameFromSearchParams;+ }++ // Any image format is suitable+ const FALLBACK_URL_TYPE = "image/png";++ return [FALLBACK_URL_TYPE, `${nanoid()}.png`] as const;+};++const bufferToHex = (buffer: ArrayBuffer) => {+ const byteArray = new Uint8Array(buffer);+ return Array.from(byteArray, (byte) =>+ byte.toString(16).padStart(2, "0")+ ).join("");+};++export const getSha256Hash = async (data: string) => {+ const encoder = new TextEncoder();+ const dataBuffer = encoder.encode(data);+ const hashBuffer = await crypto.subtle.digest("SHA-256", dataBuffer);+ return bufferToHex(hashBuffer);+};++const readFileAsArrayBuffer = (file: File): Promise<ArrayBuffer> =>+ new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as ArrayBuffer);+ reader.onerror = () => reject(reader.error);+ reader.readAsArrayBuffer(file);+ });++export const getSha256HashOfFile = async (file: File) => {+ const arrayBuffer = await readFileAsArrayBuffer(file);+ const hashBuffer = await crypto.subtle.digest("SHA-256", arrayBuffer);+ return bufferToHex(hashBuffer);+};++export const getMimeType = (file: File | URL) => {+ if (file instanceof File) {+ return file.type;+ }++ return extractImageNameAndMimeTypeFromUrl(file)[0];+};++export const getFileName = (file: File | URL) => {+ if (file instanceof File) {+ return file.name;+ }++ return extractImageNameAndMimeTypeFromUrl(file)[1];+};diff --git a/apps/builder/app/builder/shared/assets/image-formats.ts b/apps/builder/app/builder/shared/assets/image-formats.tsdeleted file mode 100644index 9c071bcc0d..0000000000--- a/apps/builder/app/builder/shared/assets/image-formats.ts+++ /dev/null@@ -1,49 +0,0 @@-import { nanoid } from "nanoid";--const extensionToMime = new Map([- [".gif", "image/gif"],- [".ico", "image/x-icon"],- [".jpeg", "image/jpeg"],- [".jpg", "image/jpeg"],- [".png", "image/png"],- [".svg", "image/svg+xml"],- [".webp", "image/webp"],-] as const);--const extensions = [...extensionToMime.keys()];--export const imageMimeTypes = [...extensionToMime.values()];--export const getImageNameAndType = (fileName: string) => {- const extension = extensions.find((ext) => fileName.endsWith(ext));-- if (extension == null) {- return;- }-- return [extensionToMime.get(extension)!, fileName] as const;-};--export const extractImageNameAndMimeTypeFromUrl = (url: URL) => {- const nameFromPath = url.pathname- .split("/")- .map(getImageNameAndType)- .filter(Boolean)[0];-- if (nameFromPath != null) {- return nameFromPath;- }-- const nameFromSearchParams = [...url.searchParams.values()]- .map(getImageNameAndType)- .filter(Boolean)[0];-- if (nameFromSearchParams != null) {- return nameFromSearchParams;- }-- // Any image format is suitable- const FALLBACK_URL_TYPE = "image/png";-- return [FALLBACK_URL_TYPE, `${nanoid()}.png`] as const;-};diff --git a/apps/builder/app/builder/shared/assets/use-assets.tsx b/apps/builder/app/builder/shared/assets/use-assets.tsxindex 48112977c3..db3adab91c 100644--- a/apps/builder/app/builder/shared/assets/use-assets.tsx+++ b/apps/builder/app/builder/shared/assets/use-assets.tsx@@ -3,7 +3,7 @@ import { useStore } from "@nanostores/react";import warnOnce from "warn-once";import type { Asset } from "@webstudio-is/sdk";import type { AssetType } from "@webstudio-is/asset-uploader";-import { toast } from "@webstudio-is/design-system";+import { Box, Grid, toast, Text } from "@webstudio-is/design-system";import { sanitizeS3Key } from "@webstudio-is/asset-uploader";import { restAssetsUploadPath, restAssetsPath } from "~/shared/router-utils";import type {@@ -12,11 +12,23 @@ import type {UploadingAssetContainer,} from "./types";import type { ActionData } from "~/builder/shared/assets";-import { $assets, $authToken, $project } from "~/shared/nano-states";-import { atom, computed } from "nanostores";+import {+ $assets,+ $authToken,+ $project,+ $uploadingFilesDataStore,+ type UploadingFileData,+} from "~/shared/nano-states";+import { computed } from "nanostores";import { serverSyncStore } from "~/shared/sync";-import type { Simplify } from "type-fest";-import { extractImageNameAndMimeTypeFromUrl } from "./image-formats";++import {+ getFileName,+ getMimeType,+ getSha256Hash,+ getSha256HashOfFile,+} from "./asset-utils";+import { Image } from "../image-manager/image";export const deleteAssets = (assetIds: Asset["id"][]) => {serverSyncStore.createTransaction([$assets], (assets) => {@@ -32,48 +44,36 @@ const setAsset = (asset: Asset) => {});};-type UploadingFileData = Simplify<- {- // common props- assetId: string;- type: AssetType;- objectURL: string;- } & (- | {- source: "file";- file: File;- }- | {- source: "url";- url: URL;- }- )->;--const getFilesData = (+const getFilesData = async (type: AssetType,files: File[],urls: URL[]-): UploadingFileData[] => {- return [- ...files.map((file) => ({+): Promise<UploadingFileData[]> => {+ const filesData: UploadingFileData[] = [];+ for (const file of files) {+ const assetId = await getSha256HashOfFile(file);+ filesData.push({source: "file" as const,- assetId: crypto.randomUUID(),+ assetId: assetId,type,file,objectURL: URL.createObjectURL(file),- })),- ...urls.map((url) => ({+ });+ }++ for (const url of urls) {+ const assetId = await getSha256Hash(url.href);+ filesData.push({source: "url" as const,- assetId: crypto.randomUUID(),+ assetId,type,- url,+ url: url.href,objectURL: url.href,- })),- ];-};+ });+ }-const $uploadingFilesDataStore = atom<UploadingFileData[]>([]);+ return filesData;+};const addUploadingFilesData = (filesData: UploadingFileData[]) => {const uploadingFilesData = $uploadingFilesDataStore.get();@@ -96,12 +96,13 @@ const $assetContainers = computed(const name =uploadingFile.source === "file"? uploadingFile.file.name- : uploadingFile.url.href;+ : uploadingFile.url;- const format =+ const format = getMimeType(uploadingFile.source === "file"- ? uploadingFile.file.type.split("/")[1]- : extractImageNameAndMimeTypeFromUrl(uploadingFile.url)[0];+ ? uploadingFile.file+ : new URL(uploadingFile.url)+ ).split("/")[1];uploadingContainers.push({status: "uploading",@@ -109,9 +110,7 @@ const $assetContainers = computed(asset: {id: uploadingFile.assetId,type: uploadingFile.type,-format,-name: name,description: name,},@@ -155,15 +154,8 @@ const uploadAsset = async ({onError: (error: string) => void;}) => {try {- const mimeType =- fileOrUrl instanceof File- ? fileOrUrl.type- : extractImageNameAndMimeTypeFromUrl(fileOrUrl)[0];-- const fileName =- fileOrUrl instanceof File- ? fileOrUrl.name- : extractImageNameAndMimeTypeFromUrl(fileOrUrl)[1];+ const mimeType = getMimeType(fileOrUrl);+ const fileName = getFileName(fileOrUrl);const metaFormData = new FormData();metaFormData.append("projectId", projectId);@@ -171,12 +163,15 @@ const uploadAsset = async ({// sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443// should be removed after fixmetaFormData.append("filename", sanitizeS3Key(fileName));+const metaResponse = await fetch(restAssetsPath({ authToken }), {method: "POST",body: metaFormData,});+const metaData: { name: string } | { errors: string } =await metaResponse.json();+if ("errors" in metaData) {throw Error(metaData.errors);}@@ -202,9 +197,11 @@ const uploadAsset = async ({);const uploadData: UploadData = await uploadResponse.json();+if ("errors" in uploadData) {throw Error(uploadData.errors);}+onCompleted(uploadData);} catch (error) {if (error instanceof Error) {@@ -232,6 +229,46 @@ const handleAfterSubmit = (assetId: string, data: UploadData) => {setAsset({ ...uploadedAsset, id: assetId });};+const ToastMessage = ({+ assetId,+ objectURL,+ children,+ title,+}: {+ assetId: string;+ objectURL: string;+ children: string;+ title: string;+}) => {+ return (+ <Grid+ css={{+ gridTemplateColumns: "20% 1fr",+ }}+ gap={2}+ >+ <Image+ alt={children}+ objectURL={objectURL}+ name={""}+ assetId={assetId}+ width={64}+ />+ <Grid>+ <Text variant={"titles"}>{title}</Text>+ <Box+ css={{+ whiteSpace: "pre-wrap",+ wordBreak: "break-word",+ }}+ >+ {children}+ </Box>+ </Grid>+ </Grid>+ );+};+export const uploadAssets = async (type: AssetType,files: File[],@@ -243,17 +280,33 @@ export const uploadAssets = async (return;}- const filesData = getFilesData(type, files, urls);+ const filesData = await getFilesData(type, files, urls);addUploadingFilesData(filesData);for (const fileData of filesData) {const assetId = fileData.assetId;+ if ($assets.get().has(assetId)) {+ toast.warn(+ <ToastMessage+ title="Info"+ assetId={assetId}+ objectURL={fileData.objectURL}+ >+ Asset is already exists+ </ToastMessage>+ );++ deleteUploadingFileData(assetId);+ continue;+ }+await uploadAsset({authToken,projectId,- fileOrUrl: fileData.source === "file" ? fileData.file : fileData.url,+ fileOrUrl:+ fileData.source === "file" ? fileData.file : new URL(fileData.url),onCompleted: (data) => {URL.revokeObjectURL(fileData.objectURL);deleteUploadingFileData(assetId);@@ -262,7 +315,15 @@ export const uploadAssets = async (onError: (error) => {deleteAssets([assetId]);deleteUploadingFileData(assetId);- toast.error(error);+ toast.error(+ <ToastMessage+ title="Error"+ assetId={assetId}+ objectURL={fileData.objectURL}+ >+ {error}+ </ToastMessage>+ );},});}diff --git a/apps/builder/app/builder/shared/image-manager/image-manager.tsx b/apps/builder/app/builder/shared/image-manager/image-manager.tsxindex 5cf3f4389c..fcbf1fd8b7 100644--- a/apps/builder/app/builder/shared/image-manager/image-manager.tsx+++ b/apps/builder/app/builder/shared/image-manager/image-manager.tsx@@ -23,7 +23,7 @@ const useLogic = ({onChange,accept,}: {- onChange?: (asset: ImageAsset) => void;+ onChange?: (assetId: ImageAsset["id"]) => void;accept?: string;}) => {const { assetContainers } = useAssets("image");@@ -39,7 +39,7 @@ const useLogic = ({assetContainer.status === "uploaded" &&assetContainer.asset.type === "image") {- onChange?.(assetContainer.asset);+ onChange?.(assetContainer.asset.id);}return;}@@ -85,7 +85,7 @@ const useLogic = ({};type ImageManagerProps = {- onChange?: (asset: ImageAsset) => void;+ onChange?: (assetId: ImageAsset["id"]) => void;/** acceptable file types in the `<imput accept>` attribute format */accept?: string;};@@ -114,12 +114,8 @@ export const ImageManager = ({ accept, onChange }: ImageManagerProps) => {onDelete={handleDelete}onSelect={handleSelect}onChange={(assetContainer) => {- // @todo we probably should not allow select uploading images too- if (- assetContainer.status === "uploaded" &&- assetContainer.asset.type === "image"- ) {- onChange?.(assetContainer.asset);+ if (assetContainer.asset.type === "image") {+ onChange?.(assetContainer.asset.id);}}}state={index === selectedIndex ? "selected" : undefined}diff --git a/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsx b/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsxindex 34f24b67d7..b1b6afc290 100644--- a/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsx+++ b/apps/builder/app/builder/shared/image-manager/image-thumbnail.tsx@@ -5,8 +5,35 @@ import { ImageInfoTrigger, imageInfoTriggerCssVars } from "./image-info-tigger";import type { AssetContainer } from "~/builder/shared/assets";import { Filename } from "./filename";import { Image } from "./image";+import brokenImage from "~/shared/images/broken-image-placeholder.svg";import { theme } from "@webstudio-is/design-system";+const StyledWebstudioImage = styled(Image, {+ 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})`,+ },+});+const ThumbnailContainer = styled(Box, {position: "relative",display: "flex",@@ -79,20 +106,24 @@ export const ImageThumbnail = ({}}}onKeyDown={(event: KeyboardEvent) => {- if (event.code === "Enter" && assetContainer.status === "uploaded") {+ if (event.code === "Enter") {onChange?.(assetContainer);}}}><ThumbnailonClick={() => {- if (assetContainer.status === "uploaded") {- onChange?.(assetContainer);- }+ onChange?.(assetContainer);}}>- <Image- assetContainer={assetContainer}+ <StyledWebstudioImage+ assetId={assetContainer.asset.id}+ name={assetContainer.asset.name}+ objectURL={+ assetContainer.status === "uploading"+ ? assetContainer.objectURL+ : undefined+ }alt={description ?? name}// width={64} used for Image optimizations it should be approximately equal to the width of the picture on the screen in pxwidth={64}diff --git a/apps/builder/app/builder/shared/image-manager/image.tsx b/apps/builder/app/builder/shared/image-manager/image.tsxindex 1b4a67a970..59f51c86b4 100644--- a/apps/builder/app/builder/shared/image-manager/image.tsx+++ b/apps/builder/app/builder/shared/image-manager/image.tsx@@ -1,58 +1,38 @@import { useStore } from "@nanostores/react";-import { styled } from "@webstudio-is/design-system";+import { Image as WebstudioImage } from "@webstudio-is/image";-import type { AssetContainer } from "../assets";-import brokenImage from "~/shared/images/broken-image-placeholder.svg";+import { $imageLoader } from "~/shared/nano-states";type ImageProps = {- assetContainer: AssetContainer;+ assetId: string;+ objectURL: string | undefined;+ name: string;alt: string;width: number;+ className?: string;};-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";+export const Image = ({+ className,+ objectURL,+ assetId,+ name,+ alt,+ width,+}: ImageProps) => {+ const optimize = objectURL === undefined;const imageLoader = useStore($imageLoader);// 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 UploadedAssetContainerconst decoding = "sync";- const src =- assetContainer.status === "uploading"- ? assetContainer.objectURL- : asset.name;+ const src = objectURL ?? name;return (- <StyledWebstudioImage+ <WebstudioImage+ className={className}style={{// Prevent native image drag in Image Manager to avoid issues with monitorForExternal// from @atlaskit/pragmatic-drag-and-drop, which incorrectly identifies it as an external drag operation@@ -60,8 +40,9 @@ export const Image = ({ assetContainer, alt, width }: ImageProps) => {// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignoreWebkitUserDrag: "none",+ maxWidth: "100%",}}- key={asset.id}+ key={assetId}loader={imageLoader}decoding={decoding}src={src}diff --git a/apps/builder/app/builder/shared/image-manager/uploading-animation.tsx b/apps/builder/app/builder/shared/image-manager/uploading-animation.tsxindex 7e4a0f3dfd..5a589303b0 100644--- a/apps/builder/app/builder/shared/image-manager/uploading-animation.tsx+++ b/apps/builder/app/builder/shared/image-manager/uploading-animation.tsx@@ -29,6 +29,7 @@ const AnimationContainer = styled("div", {flexDirection: "column",justifyContent: "center",alignItems: "center",+ pointerEvents: "none",});export const UploadingAnimation = () => {diff --git a/apps/builder/app/routes/cgi.image.$name.ts b/apps/builder/app/routes/cgi.image.$name.tsindex 7aac9d9dc2..5e195fb44f 100644--- a/apps/builder/app/routes/cgi.image.$name.ts+++ b/apps/builder/app/routes/cgi.image.$name.ts@@ -3,7 +3,41 @@ import { join } from "node:path";import { createReadableStreamFromReadable } from "@remix-run/node";import type { LoaderFunctionArgs } from "@remix-run/server-runtime";import env from "~/env/env.server";-import { getImageNameAndType } from "~/builder/shared/assets/image-formats";+import { getImageNameAndType } from "~/builder/shared/assets/asset-utils";+import { z } from "zod";++const ImageParams = z.object({+ width: z.string().transform((value) => Math.round(parseFloat(value))),+ height: z.optional(+ z.string().transform((value) => Math.round(parseFloat(value)))+ ),+ fit: z.optional(+ z.union([+ z.literal("scale-down"),+ z.literal("contain"),+ z.literal("cover"),+ z.literal("crop"),+ z.literal("pad"),+ ])+ ),++ quality: z.string().transform((value) => Math.round(parseFloat(value))),++ format: z.union([+ z.literal("auto"),+ z.literal("avif"),+ z.literal("webp"),+ z.literal("json"),+ z.literal("jpeg"),+ z.literal("png"),+ z.literal("raw"),+ ]),++ // For testing purposes+ sleep: z+ .optional(z.string())+ .transform((value) => (value ? Math.round(parseFloat(value)) : undefined)),+});// this route used as proxy for images to cloudflare endpoint// https://developers.cloudflare.com/fundamentals/get-started/reference/cdn-cgi-endpoint/@@ -15,12 +49,37 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {}const url = new URL(request.url);- const width = url.searchParams.get("width");- const quality = url.searchParams.get("quality");- const format = url.searchParams.get("format");- if (width === null || quality === null || format === null) {- throw Error("Options are invalid");+ // The code should be +- same as here https://github.com/webstudio-is/webstudio-saas/blob/6c9a3bfb67cf5a221c20666de34bd20dc14bd558/packages/assets-proxy/src/image-transform.ts#L68+ const rawParameters: Record<string, string> = {+ format: url.searchParams.get("format") ?? "auto",+ width: url.searchParams.get("width") ?? "0",+ quality: url.searchParams.get("quality") ?? "80",+ };++ const height = url.searchParams.get("height");++ if (height != null) {+ rawParameters.height = height;+ }++ const fit = url.searchParams.get("fit");++ if (fit != null) {+ rawParameters.fit = fit;+ }++ const sleep = url.searchParams.get("sleep");++ if (sleep != null) {+ rawParameters.sleep = sleep;+ }++ const imageParameters = ImageParams.parse(rawParameters);++ // For testing purposes+ if (imageParameters.sleep !== undefined) {+ await new Promise((resolve) => setTimeout(resolve, imageParameters.sleep));}// Allow direct image access, and from the same origindiff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.tsindex 4d390d65d9..99d756383c 100644--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts@@ -219,7 +219,7 @@ const parse = (clipboardData: string, options?: Options) => {return data;};-export const onPaste = (clipboardData: string) => {+export const onPaste = async (clipboardData: string) => {const data = parse(clipboardData);const selectedPage = $selectedPage.get();if (data === undefined || selectedPage === undefined) {diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.tsindex 9e572c53c4..9af6b7f402 100644--- a/apps/builder/app/shared/nano-states/nano-states.ts+++ b/apps/builder/app/shared/nano-states/nano-states.ts@@ -29,6 +29,8 @@ import type { htmlTags as HtmlTags } from "html-tags";import { $instances, $selectedInstanceSelector } from "./instances";import { $selectedPage } from "./pages";import type { UnitSizes } from "~/builder/features/style-panel/shared/css-value-input/convert-units";+import type { Simplify } from "type-fest";+import type { AssetType } from "@webstudio-is/asset-uploader";export const $project = atom<Project | undefined>();@@ -154,6 +156,26 @@ export const $stylesIndex = computed(export const $assets = atom<Assets>(new Map());+export type UploadingFileData = Simplify<+ {+ // common props+ assetId: string;+ type: AssetType;+ objectURL: string;+ } & (+ | {+ source: "file";+ file: File;+ }+ | {+ source: "url";+ url: string;+ }+ )+>;++export const $uploadingFilesDataStore = atom<UploadingFileData[]>([]);+export const $selectedInstanceBrowserStyle = atom<undefined | Style>();// Init with some defaults to avoid undefineddiff --git a/apps/builder/app/shared/nano-states/props.test.ts b/apps/builder/app/shared/nano-states/props.test.tsindex f06ff3f54a..432404040c 100644--- a/apps/builder/app/shared/nano-states/props.test.ts+++ b/apps/builder/app/shared/nano-states/props.test.ts@@ -247,7 +247,12 @@ test("resolve asset prop values when params is provided", () => {});expect($propValuesByInstanceSelector.get().get(JSON.stringify(["box"]))- ).toEqual(new Map<string, unknown>([["myAsset", "/asset/my-file.jpg"]]));+ ).toEqual(+ new Map<string, unknown>([+ ["$webstudio$canvasOnly$assetId", "assetId"],+ ["myAsset", "/asset/my-file.jpg"],+ ])+ );cleanStores($propValuesByInstanceSelector);});diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.tsindex 182a1c3b73..d6ee16b5c9 100644--- a/apps/builder/app/shared/nano-states/props.ts+++ b/apps/builder/app/shared/nano-states/props.ts@@ -6,6 +6,7 @@ import type {Prop,ResourceRequest,System,+ ImageAsset,} from "@webstudio-is/sdk";import {decodeDataSourceVariable,@@ -21,7 +22,13 @@ import {import { isFeatureEnabled } from "@webstudio-is/feature-flags";import { mapGroupBy } from "~/shared/shim";import { $instances } from "./instances";-import { $dataSources, $props, $assets, $resources } from "./nano-states";+import {+ $dataSources,+ $props,+ $assets,+ $resources,+ $uploadingFilesDataStore,+} from "./nano-states";import { $selectedPage, $pages } from "./pages";import type { InstanceSelector } from "../tree-utils";import { $params } from "~/canvas/stores";@@ -32,6 +39,7 @@ import {$selectedPageDefaultSystem,mergeSystem,} from "./variables";+import { getMimeType } from "~/builder/shared/assets/asset-utils";export const getIndexedInstanceId = (instanceId: Instance["id"],@@ -235,20 +243,58 @@ export const $propValuesByInstanceSelector = computed($params,$pages,$assets,+ $uploadingFilesDataStore,],- (instances, props, page, unscopedVariableValues, params, pages, assets) => {+ (+ instances,+ props,+ page,+ unscopedVariableValues,+ params,+ pages,+ assets,+ uploadingFilesDataStore+ ) => {const variableValues = new Map<string, unknown>(unscopedVariableValues);let propsList = Array.from(props.values());// ignore asset and page props when params is not providedif (params && pages) {+ const uploadingImageAssets = uploadingFilesDataStore+ .map((fileData) => {+ const format = getMimeType(+ fileData.source === "file" ? fileData.file : new URL(fileData.url)+ ).split("/")[1];++ const uploadingAsset: ImageAsset = {+ id: fileData.assetId,+ name: fileData.objectURL,+ format,+ type: "image",+ description: "",+ createdAt: "",+ projectId: "",+ size: 0,++ meta: {+ width: Number.NaN,+ height: Number.NaN,+ },+ };++ return uploadingAsset;+ })+ .filter(<T>(value: T): value is NonNullable<T> => value !== undefined);+// use whole props list to let access hash props from other pages and instancespropsList = normalizeProps({props: propsList,assetBaseUrl: params.assetBaseUrl,assets,+ uploadingImageAssets,pages,+ source: "canvas",});}// collect props and group by instances@@ -272,8 +318,23 @@ export const $propValuesByInstanceSelector = computed(const propValues = new Map<Prop["name"], unknown>();const props = propsByInstanceId.get(instanceId);const parameters = new Map<Prop["name"], DataSource["id"]>();+if (props) {for (const prop of props) {+ if (prop.type === "asset" && prop.name === "width") {+ const asset = assets.get(prop.value);+ if (asset?.type === "image") {+ propValues.set("width", asset.meta.width);+ }+ }++ if (prop.type === "asset" && prop.name === "height") {+ const asset = assets.get(prop.value);+ if (asset?.type === "image") {+ propValues.set("height", asset.meta.height);+ }+ }+// at this point asset and page either already converted to string// or can be ignoredif (prop.type === "asset" || prop.type === "page") {diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 9d0f08e2f1..1a7070d244 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -39,6 +39,7 @@ import {$resourceValues,$marketplaceProduct,$canvasIframeState,+ $uploadingFilesDataStore,} from "~/shared/nano-states";import { $ephemeralStyles } from "~/canvas/stores";@@ -120,6 +121,7 @@ export const registerContainers = () => {clientStores.set("ephemeralStyles", $ephemeralStyles);clientStores.set("selectedInstanceStates", $selectedInstanceStates);clientStores.set("canvasIframeState", $canvasIframeState);+ clientStores.set("uploadingFilesDataStore", $uploadingFilesDataStore);for (const [name, store] of $synchronizedBreakpoints) {clientStores.set(name, store);diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.tsindex ec11a32fcd..1502d3f0a5 100644--- a/packages/asset-uploader/src/upload.ts+++ b/packages/asset-uploader/src/upload.ts@@ -78,6 +78,7 @@ export const createUploadName = async (* "SELECT id FROM "Project" where id=? FOR UPDATE;" is shareable between sqlite and postgres.**/const name = getUniqueFilename(sanitizeS3Key(filename));+await prisma.file.create({data: {name,diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex 68fb3b5d35..4f6fd4c00c 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -328,7 +328,9 @@ export const prebuild = async (options: {props: siteData.build.props.map(([_id, prop]) => prop),assetBaseUrl,assets: new Map(siteData.assets.map((asset) => [asset.id, asset])),+ uploadingImageAssets: [],pages: siteData.build.pages,+ source: "prebuild",});const props: [Prop["id"], Prop][] = [];diff --git a/packages/design-system/src/components/toast.tsx b/packages/design-system/src/components/toast.tsxindex fcc733e056..e9c9e234b2 100644--- a/packages/design-system/src/components/toast.tsx+++ b/packages/design-system/src/components/toast.tsx@@ -1,5 +1,5 @@import * as ToastPrimitive from "@radix-ui/react-toast";-import toast, { resolveValue, useToaster } from "react-hot-toast/headless";+import hotToast, { resolveValue, useToaster } from "react-hot-toast/headless";import { keyframes, styled } from "../stitches.config";import { InfoCircleIcon } from "@webstudio-is/icons";import { Box } from "./box";@@ -91,13 +91,10 @@ const StyledToast = styled(ToastPrimitive.Root, {},});-const StyledTitle = styled(ToastPrimitive.Title, {- marginBottom: theme.spacing[3],-});-export const Toaster = () => {const { toasts, handlers } = useToaster();const { startPause, endPause } = handlers;+return (<ToastPrimitive.ToastProvider>{toasts.map((toastData) => (@@ -109,23 +106,25 @@ export const Toaster = () => {onClick={() => {// To give a way to dismiss the infinite toastif (toastData.duration === Number.POSITIVE_INFINITY) {- toast.dismiss(toastData.id);+ hotToast.dismiss(toastData.id);}}}>- <Box- css={{- svg: {- width: theme.spacing[11],- height: theme.spacing[11],- },- }}- >- {toastData.type === "blank" && <InfoCircleIcon />}- </Box>- <StyledTitle>+ {toastData.type === "blank" && (+ <Box+ css={{+ svg: {+ width: theme.spacing[11],+ height: theme.spacing[11],+ },+ }}+ >+ <InfoCircleIcon />+ </Box>+ )}+ <ToastPrimitive.Title>{resolveValue(toastData.message, toastData)}- </StyledTitle>+ </ToastPrimitive.Title></StyledToast>))}<StyledViewport />@@ -133,4 +132,9 @@ export const Toaster = () => {);};-export { toast };+export const toast = {+ info: hotToast,+ error: hotToast.error,+ success: hotToast.success,+ warn: hotToast.custom,+};diff --git a/packages/image/src/image-optimize.ts b/packages/image/src/image-optimize.tsindex c52dbfe251..f8f31f4407 100644--- a/packages/image/src/image-optimize.ts+++ b/packages/image/src/image-optimize.ts@@ -248,6 +248,7 @@ export const getImageAttributes = (props: {}| undefined => {const width = getInt(props.width);+const quality = Math.max(Math.min(getInt(props.quality) ?? DEFAULT_QUALITY, 100),0diff --git a/packages/react-sdk/src/props.test.ts b/packages/react-sdk/src/props.test.tsindex ffeb4a0cf3..2b4bb50d29 100644--- a/packages/react-sdk/src/props.test.ts+++ b/packages/react-sdk/src/props.test.ts@@ -35,6 +35,94 @@ test("normalize asset prop into string", () => {type: "asset",value: "asset1",},+ {+ id: "prop-w",+ instanceId: "instance1",+ name: "width",+ type: "asset",+ value: "asset1",+ },+ {+ id: "prop-h",+ instanceId: "instance1",+ name: "height",+ type: "asset",+ value: "asset1",+ },+ ],+ assetBaseUrl: "/assets/",+ assets: new Map([+ [+ "asset1",+ {+ id: "asset1",+ type: "image",+ name: "my-asset.jpg",+ format: "jpg",+ meta: { width: 101, height: 303 },+ projectId: "",+ size: 0,+ description: "",+ createdAt: "",+ },+ ],+ ]),+ uploadingImageAssets: [],+ pages: pagesBase,+ source: "prebuild",+ })+ ).toEqual([+ {+ id: "prop1",+ instanceId: "instance1",+ name: "src",+ type: "string",+ value: "/assets/my-asset.jpg",+ },+ {+ id: "prop-w",+ instanceId: "instance1",+ name: "width",+ required: undefined,+ type: "number",+ value: 101,+ },+ {+ id: "prop-h",+ instanceId: "instance1",+ name: "height",+ required: undefined,+ type: "number",+ value: 303,+ },+ ]);+});++test("normalize asset prop into string and pass assetId on the canvas", () => {+ expect(+ normalizeProps({+ props: [+ {+ id: "prop1",+ instanceId: "instance1",+ name: "src",+ type: "asset",+ value: "asset1",+ },+ {+ id: "prop-w",+ instanceId: "instance1",+ name: "width",+ type: "asset",+ value: "asset1",+ },+ {+ id: "prop-h",+ instanceId: "instance1",+ name: "height",+ type: "asset",+ value: "asset1",+ },],assetBaseUrl: "/assets/",assets: new Map([@@ -45,7 +133,7 @@ test("normalize asset prop into string", () => {type: "image",name: "my-asset.jpg",format: "jpg",- meta: { width: 0, height: 0 },+ meta: { width: 101, height: 303 },projectId: "",size: 0,description: "",@@ -53,7 +141,9 @@ test("normalize asset prop into string", () => {},],]),+ uploadingImageAssets: [],pages: pagesBase,+ source: "canvas",})).toEqual([{@@ -63,6 +153,30 @@ test("normalize asset prop into string", () => {type: "string",value: "/assets/my-asset.jpg",},+ {+ id: "instance1-asset1-assetId",+ instanceId: "instance1",+ name: "$webstudio$canvasOnly$assetId",+ required: false,+ type: "string",+ value: "asset1",+ },+ {+ id: "prop-w",+ instanceId: "instance1",+ name: "width",+ required: undefined,+ type: "number",+ value: 101,+ },+ {+ id: "prop-h",+ instanceId: "instance1",+ name: "height",+ required: undefined,+ type: "number",+ value: 303,+ },]);});@@ -80,6 +194,7 @@ test("normalize page prop with path into string", () => {],assetBaseUrl: "",assets: new Map(),+ uploadingImageAssets: [],pages: {...pagesBase,pages: [@@ -95,6 +210,7 @@ test("normalize page prop with path into string", () => {],folders: [],},+ source: "prebuild",})).toEqual([{@@ -131,6 +247,7 @@ test("normalize page prop with path and hash into string", () => {],assetBaseUrl: "",assets: new Map(),+ uploadingImageAssets: [],pages: {...pagesBase,pages: [@@ -159,6 +276,7 @@ test("normalize page prop with path and hash into string", () => {},],},+ source: "prebuild",});expect(result).toEqual([{diff --git a/packages/react-sdk/src/props.ts b/packages/react-sdk/src/props.tsindex 2ceffcee6f..b9e4c0379f 100644--- a/packages/react-sdk/src/props.ts+++ b/packages/react-sdk/src/props.ts@@ -2,6 +2,7 @@ import {type Prop,type Assets,type Pages,+ type ImageAsset,getPagePath,findPageByIdOrPath,} from "@webstudio-is/sdk";@@ -10,29 +11,74 @@ export const normalizeProps = ({props,assetBaseUrl,assets,+ uploadingImageAssets,pages,+ source,}: {props: Prop[];assetBaseUrl: string;assets: Assets;+ uploadingImageAssets: ImageAsset[];pages: Pages;+ source: "canvas" | "prebuild";}) => {const newProps: Prop[] = [];for (const prop of props) {if (prop.type === "asset") {const assetId = prop.value;- const asset = assets.get(assetId);+ const asset =+ assets.get(assetId) ??+ uploadingImageAssets.find((asset) => asset.id === assetId);+if (asset === undefined) {continue;}- newProps.push({++ const propBase = {id: prop.id,name: prop.name,required: prop.required,instanceId: prop.instanceId,+ };++ if (prop.name === "width" && asset.type === "image") {+ newProps.push({+ ...propBase,+ type: "number",+ value: asset.meta.width,+ });++ continue;+ }++ if (prop.name === "height" && asset.type === "image") {+ newProps.push({+ ...propBase,+ type: "number",+ value: asset.meta.height,+ });+ continue;+ }++ newProps.push({+ ...propBase,type: "string",value: `${assetBaseUrl}${asset.name}`,});++ if (source === "canvas") {+ // use assetId as key to not recreate the image if it's switched from uploading to uploaded asset state (we don't know asset src during uploading)+ // see Image component in sdk-components-react+ newProps.push({+ id: `${prop.instanceId}-${asset.id}-assetId`,+ name: "$webstudio$canvasOnly$assetId",+ required: false,+ instanceId: prop.instanceId,+ type: "string",+ value: asset.id,+ });+ }+continue;}diff --git a/packages/sdk-components-react/src/image.tsx b/packages/sdk-components-react/src/image.tsxindex e0875df796..d4fc10a293 100644--- a/packages/sdk-components-react/src/image.tsx+++ b/packages/sdk-components-react/src/image.tsx@@ -35,22 +35,63 @@ const imagePlaceholderSvg = `data:image/svg+xml;base64,${btoa(`<svgtype Props = Omit<ComponentPropsWithoutRef<typeof WebstudioImage>, "loader">;-export const Image = forwardRef<ElementRef<typeof defaultTag>, Props>(- ({ loading = "lazy", ...props }, ref) => {+export const Image = forwardRef<+ ElementRef<typeof defaultTag>,+ Props & { $webstudio$canvasOnly$assetId?: string | undefined }+>(+ (+ {+ loading = "lazy",+ width: widthProp,+ height: heightProp,+ optimize: optimizeProp,+ decoding: decodingProp,+ $webstudio$canvasOnly$assetId,+ ...props+ },+ ref+ ) => {// cast to string when invalid value type is provided with bindingconst src = String(props.src ?? "");const { imageLoader, renderer, assetBaseUrl } = useContext(ReactSdkContext);+ let decoding = decodingProp;++ let key = src;++ let optimize = optimizeProp;++ let width = widthProp;+ let height = heightProp;+if (renderer === "canvas") {// With disabled cache and loading lazy, chrome may not render the image at allloading = "eager";++ // Avoid image flickering on switching from preview to asset (during upload)+ decoding = "sync";++ // use assetId as key to not recreate the image if it's switched from uploading to uploaded asset state (we don't know asset src during uploading)+ key = $webstudio$canvasOnly$assetId ?? src;++ // NaN width and height means that the image is not yet uploaded, and should not be optimized on canvas+ if (+ widthProp !== undefined &&+ heightProp !== undefined &&+ Number.isNaN(widthProp) &&+ Number.isNaN(heightProp)+ ) {+ optimize = optimizeProp ?? false;+ width = undefined;+ height = undefined;+ }}if (src.startsWith(assetBaseUrl) === false) {return (<img- key={src}+ key={key}loading={loading}{...props}src={src || imagePlaceholderSvg}@@ -68,14 +109,16 @@ export const Image = forwardRef<ElementRef<typeof defaultTag>, Props>(/*** `key` is needed to recreate the image in case of asset change in builder,* this gives immediate feedback when an asset is changed.- * Also, it visually fixes image distortion when another asset has a seriously different aspectRatio- * (we change aspectRatio CSS prop on asset change)** In non-builder mode, key on images are usually also a good idea,* prevents showing outdated images on route change.**/- key={assetName}+ key={key}loading={loading}+ decoding={decoding}+ optimize={optimize}+ width={width}+ height={height}{...props}loader={imageLoader}src={assetName}