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
Fix images appears disappears during upload/delete. (#623)
Ivan Starkov124f96ebe9f8
diff --git a/apps/designer/app/designer/designer.tsx b/apps/designer/app/designer/designer.tsxindex 829e08b82f..ae52ba215b 100644--- a/apps/designer/app/designer/designer.tsx+++ b/apps/designer/app/designer/designer.tsx@@ -41,7 +41,7 @@ import { Navigator } from "./features/sidebar-left";import { getBuildUrl } from "~/shared/router-utils";import { useSubscribeDesignTokens } from "./shared/design-tokens-manager";import { useInstanceCopyPaste } from "~/shared/copy-paste";-import { usePublishAssets } from "./shared/assets";+import { AssetsProvider, usePublishAssets } from "./shared/assets";export const links = () => {return [@@ -335,47 +335,50 @@ export const Designer = ({});return (- <ChromeWrapper isPreviewMode={isPreviewMode}>- <Topbar- css={{ gridArea: "header" }}- project={project}- publish={publish}- previewUrl={previewUrl}- />- <Main>- <Workspace onTransitionEnd={onTransitionEnd} publish={publish}>- <CanvasIframe- ref={iframeRefCallback}- src={canvasUrl}- pointerEvents={- dragAndDropState.isDragging && dragAndDropState.origin === "panel"- ? "none"- : "all"- }- title={project.title}- css={{- height: "100%",- width: "100%",- }}- />- </Workspace>- </Main>- <SidePanel gridArea="sidebar" isPreviewMode={isPreviewMode}>- <SidebarLeft publish={publish} />- </SidePanel>- <NavigatorPanel publish={publish} isPreviewMode={isPreviewMode} />- <SidePanel- gridArea="inspector"- isPreviewMode={isPreviewMode}- css={{ overflow: "hidden" }}- >- {dragAndDropState.isDragging ? (- <TreePrevew />- ) : (- <Inspector publish={publish} />- )}- </SidePanel>- <Footer publish={publish} />- </ChromeWrapper>+ <AssetsProvider>+ <ChromeWrapper isPreviewMode={isPreviewMode}>+ <Topbar+ css={{ gridArea: "header" }}+ project={project}+ publish={publish}+ previewUrl={previewUrl}+ />+ <Main>+ <Workspace onTransitionEnd={onTransitionEnd} publish={publish}>+ <CanvasIframe+ ref={iframeRefCallback}+ src={canvasUrl}+ pointerEvents={+ dragAndDropState.isDragging &&+ dragAndDropState.origin === "panel"+ ? "none"+ : "all"+ }+ title={project.title}+ css={{+ height: "100%",+ width: "100%",+ }}+ />+ </Workspace>+ </Main>+ <SidePanel gridArea="sidebar" isPreviewMode={isPreviewMode}>+ <SidebarLeft publish={publish} />+ </SidePanel>+ <NavigatorPanel publish={publish} isPreviewMode={isPreviewMode} />+ <SidePanel+ gridArea="inspector"+ isPreviewMode={isPreviewMode}+ css={{ overflow: "hidden" }}+ >+ {dragAndDropState.isDragging ? (+ <TreePrevew />+ ) : (+ <Inspector publish={publish} />+ )}+ </SidePanel>+ <Footer publish={publish} />+ </ChromeWrapper>+ </AssetsProvider>);};diff --git a/apps/designer/app/designer/features/props-panel/control.tsx b/apps/designer/app/designer/features/props-panel/control.tsxindex 94aea842cf..0386d7f49a 100644--- a/apps/designer/app/designer/features/props-panel/control.tsx+++ b/apps/designer/app/designer/features/props-panel/control.tsx@@ -155,7 +155,15 @@ const ImageControl = ({ asset, onChange }: ImageControlProps) => {return (<ValuePickerPopovertitle="Images"- content={<ImageManager onChange={onChange} />}+ content={+ <ImageManager+ onChange={(clientAsset) => {+ if (clientAsset.status === "uploaded") {+ onChange(clientAsset.asset);+ }+ }}+ />+ }><TextField defaultValue={asset?.name ?? " - "} /></ValuePickerPopover>diff --git a/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts b/apps/designer/app/designer/features/props-panel/use-props-logic.test.tsindex 42c70bcc8a..cf46a91875 100644--- a/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts+++ b/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts@@ -406,7 +406,6 @@ describe("usePropsLogic", () => {createdAt: new Date("1995-12-17T03:24:00Z").toISOString(),meta: { width: 101, height: 202 },path: "string",- status: "uploaded",},});});@@ -432,7 +431,6 @@ describe("usePropsLogic", () => {"path": "string","projectId": "string","size": 1111,- "status": "uploaded",},},]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 6d1c81c7aa..b26d60678d 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@@ -27,7 +27,13 @@ const useAvailableFontWeights = (// Find all font weights that are available for the current font family.return useMemo(() => {const found = allFontWeights.filter((option) => {- return assets.find((asset) => {+ return assets.find((clientAsset) => {+ if (clientAsset.status !== "uploaded") {+ return false;+ }++ const { asset } = clientAsset;+return ("meta" in asset &&"family" in asset.meta &&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 899987140d..1b7773e3a8 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@@ -26,20 +26,26 @@ export const ImageControl = ({const setValue = setProperty(styleConfig.property);- const selectedAsset = assets.find((asset) => asset.id === toValue(value));+ const selectedAsset = assets.find(+ (clientAsset) =>+ (clientAsset.asset?.id ?? clientAsset.preview?.id) === toValue(value)+ );return (<ValuePickerPopovertitle="Images"content={<ImageManager- onChange={(asset) => {- setValue(asset.id);+ onChange={(clientAsset) => {+ if (clientAsset.status === "uploaded") {+ // @todo looks like a bug fix next PRs+ setValue(clientAsset.asset.id);+ }}}/>}>- <TextField defaultValue={selectedAsset?.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 621a2fdaf6..be204555b1 100644--- a/apps/designer/app/designer/shared/assets/types.ts+++ b/apps/designer/app/designer/shared/assets/types.ts@@ -1,9 +1,36 @@import { Asset } from "@webstudio-is/asset-uploader";-export type PreviewAsset = Pick<Asset, "path" | "name" | "id" | "format"> & {+type PreviewAsset = Pick<+ Asset,+ "path" | "name" | "id" | "format" | "description"+>;++export type UploadedClientAsset = {+ status: "uploaded";+ asset: Asset;+ preview: PreviewAsset | undefined;+};++export type UploadingClientAsset = {status: "uploading";+ asset: Asset | undefined;+ preview: PreviewAsset;};+export type DeletingClientAsset = {+ status: "deleting";+ asset: Asset;+ preview: PreviewAsset | undefined;+};++/**+ * Client side we need more information about the asset than the server provides.+ */+export type ClientAsset =+ | UploadedClientAsset+ | UploadingClientAsset+ | DeletingClientAsset;+export type ActionData = {uploadedAssets?: Array<Asset>;deletedAssets?: Array<Asset>;diff --git a/apps/designer/app/designer/shared/assets/update-state-assets.test.ts b/apps/designer/app/designer/shared/assets/update-state-assets.test.tsnew file mode 100644index 0000000000..bb59ce909e--- /dev/null+++ b/apps/designer/app/designer/shared/assets/update-state-assets.test.ts@@ -0,0 +1,161 @@+import type { Asset } from "@webstudio-is/asset-uploader";+import {+ UploadedClientAsset,+ UploadingClientAsset,+ DeletingClientAsset,+ ClientAsset,+} from "./types";+import { updateStateAssets } from "./update-state-assets";++const getAssetId = (clientAsset: ClientAsset): string =>+ clientAsset.status === "uploading"+ ? clientAsset.preview.id+ : clientAsset.asset.id;++const createServerAsset = (id: string, name?: string): Asset => ({+ id,++ name: name ?? "test",+ location: "FS",+ projectId: "id",+ size: 2135,+ format: "png",+ createdAt: "",+ description: "",+ meta: { width: 200, height: 200 },+ path: "",+});++const createAsset = (id: string, name?: string): UploadedClientAsset => ({+ status: "uploaded",+ asset: createServerAsset(id, name),+ preview: undefined,+});++const createPreviewAsset = (id: string): UploadingClientAsset => {+ return {+ status: "uploading",+ asset: undefined,+ preview: createAsset(id).asset,+ };+};++const createPreviewAndAsset = (+ id: string,+ name?: string+): UploadedClientAsset => {+ return {+ status: "uploaded",+ asset: createAsset(id, name).asset,+ preview: createAsset(id).asset,+ };+};++const createDeletingAsset = (id: string): DeletingClientAsset => {+ return {+ ...createAsset(id),+ status: "deleting",+ };+};++describe("updateStateAssets", () => {+ const stateAssets = [+ createPreviewAsset("1"),+ createAsset("2"),+ createDeletingAsset("3"),+ createAsset("4"),+ createDeletingAsset("5"),+ createDeletingAsset("6"),+ createPreviewAsset("7"),+ ];++ test("Deleting assets should not update", () => {+ const serverAssets = [+ createServerAsset("2"),+ createServerAsset("3"),+ createServerAsset("4"),+ createServerAsset("5"),+ createServerAsset("6"),+ ];++ const nextAssets = updateStateAssets(stateAssets, serverAssets);++ expect(nextAssets).toEqual(stateAssets);++ // Check referential equality+ expect(updateStateAssets(nextAssets, serverAssets)).toBe(nextAssets);+ });++ test("Deleting asset should gone if not exists in server data", () => {+ const serverAssets = [+ createServerAsset("2"),+ createServerAsset("4"),+ createServerAsset("6"),+ ];++ const nextAssets = updateStateAssets(stateAssets, serverAssets);++ expect(nextAssets).toEqual(+ stateAssets.filter((a) => getAssetId(a) !== "3" && getAssetId(a) !== "5")+ );++ // Check referential equality+ expect(updateStateAssets(nextAssets, serverAssets)).toBe(nextAssets);+ });++ test("Preview assets preserves in state", () => {+ const serverAssets: Asset[] = [];++ const nextAssets = updateStateAssets(stateAssets, serverAssets);++ expect(nextAssets).toEqual(+ stateAssets.filter((a) => a.status === "uploading")+ );++ // Check referential equality+ expect(updateStateAssets(nextAssets, serverAssets)).toBe(nextAssets);+ });++ test("Preview assets updated on same id asset at server state", () => {+ const serverAssets = [createServerAsset("1")];++ const nextAssets = updateStateAssets(stateAssets, serverAssets);++ expect(nextAssets).toEqual([+ createPreviewAndAsset("1"),+ createPreviewAsset("7"),+ ]);++ // Check referential equality+ expect(updateStateAssets(nextAssets, serverAssets)).toBe(nextAssets);+ });++ test("Updated asset updated", () => {+ const serverAssets = [createServerAsset("1", "new name")];++ const nextAssets = updateStateAssets(stateAssets, serverAssets);++ expect(nextAssets).toEqual([+ createPreviewAndAsset("1", "new name"),+ createPreviewAsset("7"),+ ]);++ // Check referential equality+ expect(updateStateAssets(nextAssets, serverAssets)).toBe(nextAssets);+ });++ test("Add asset not existing in stateAssets", () => {+ const serverAssets = [createServerAsset("8")];++ const nextAssets = updateStateAssets(stateAssets, serverAssets);++ expect(nextAssets).toEqual([+ createPreviewAsset("1"),+ createPreviewAsset("7"),+ createAsset("8"),+ ]);++ // Check referential equality+ expect(updateStateAssets(nextAssets, serverAssets)).toBe(nextAssets);+ });+});diff --git a/apps/designer/app/designer/shared/assets/update-state-assets.ts b/apps/designer/app/designer/shared/assets/update-state-assets.tsnew file mode 100644index 0000000000..ae32ab649d--- /dev/null+++ b/apps/designer/app/designer/shared/assets/update-state-assets.ts@@ -0,0 +1,65 @@+import deepEqual from "fast-deep-equal";+import type { Asset } from "@webstudio-is/asset-uploader";+import { ClientAsset } from "./types";++/**+ * Update local assets (containing optimistic data) with data from the server+ * - We need to preserve the order of local assets.+ * - We need to not remove optimistic assets until we are 100% sure all is fine.+ * - We need to keep in mind that "serverAssets" can be outdated, or contain information we don't have in local (optimistic) assets+ * - updateAssets(assets, data) must be referentially equal to updateAssets(updateAssets(assets, data), data)+ */+export const updateStateAssets = <T>(+ clientAssets: ClientAsset[],+ serverAssets: Asset[]+) => {+ let nextAssets: ClientAsset[] = [...clientAssets];+ // Merging data with existing assets, trying to preserve sorting+ for (const serverAsset of serverAssets) {+ // The same asset is already in the assets+ const sameIndex = nextAssets.findIndex(+ (nextAsset) =>+ (nextAsset.asset?.id ?? nextAsset.preview?.id) === serverAsset.id+ );++ if (sameIndex !== -1) {+ if (nextAssets[sameIndex].status !== "deleting") {+ nextAssets[sameIndex] = {+ status: "uploaded",+ asset: serverAsset,+ // preserve preview to avoid image flickering+ preview: nextAssets[sameIndex].preview,+ };+ }+ continue;+ }++ // Assets array were empty or somebody loaded in parallel+ nextAssets.push({+ status: "uploaded",+ asset: serverAsset,+ preview: undefined,+ });+ }++ // Remove non-preview assets that are not in the data+ nextAssets = nextAssets.filter((nextAsset) => {+ if (nextAsset.status !== "uploading") {+ if (+ serverAssets.find(+ (serverAsset) => serverAsset.id === nextAsset.asset.id+ ) === undefined+ ) {+ return false;+ }+ }++ return true;+ });++ if (deepEqual(nextAssets, clientAssets)) {+ return clientAssets;+ }++ return nextAssets;+};diff --git a/apps/designer/app/designer/shared/assets/use-assets.ts b/apps/designer/app/designer/shared/assets/use-assets.tsdeleted file mode 100644index 06cc1f44a7..0000000000--- a/apps/designer/app/designer/shared/assets/use-assets.ts+++ /dev/null@@ -1,180 +0,0 @@-import { useEffect, useMemo } from "react";-import {- AssetType,- filterByType,- MAX_UPLOAD_SIZE,- toBytes,- type Asset,-} from "@webstudio-is/asset-uploader";-import { toast } from "@webstudio-is/design-system";-import ObjectID from "bson-objectid";-import { restAssetsPath } from "~/shared/router-utils";-import { useAssets as useAssetsState, useProject } from "../nano-states";-import { sanitizeS3Key } from "@webstudio-is/asset-uploader";-import { PreviewAsset } from "./types";-import { usePersistentFetcher } from "~/shared/fetcher";-import type { ActionData } from "~/designer/shared/assets";-import {- FetcherData,- normalizeErrors,- toastUnknownFieldErrors,-} from "~/shared/form-utils";-import { Publish } from "~/shared/pubsub";-import { useFetcher } from "@remix-run/react";--declare module "~/shared/pubsub" {- export interface PubsubMap {- updateAssets: Array<Asset>;- }-}--export const usePublishAssets = (publish: Publish) => {- const [assets] = useAssetsState();- useEffect(() => {- publish({- type: "updateAssets",- payload: assets.filter(- (asset) => asset.status === undefined || asset.status === "uploaded"- ) as Array<Asset>, // TS doesn't understand we filtered out PrevewAssets- });- }, [assets, publish]);-};--export type UploadData = FetcherData<ActionData>;--const toPreviewAssets = (- formsData: Array<FormData>-): Promise<PreviewAsset[]> => {- const assets: Array<Promise<PreviewAsset>> = [];- for (const formData of formsData) {- for (const entry of formData) {- const file = entry[1];- if (!(file instanceof File)) {- continue;- }- const promise: Promise<PreviewAsset> = new Promise((resolve, reject) => {- const reader = new FileReader();- reader.addEventListener("load", (event) => {- const dataUri = event?.target?.result;- if (dataUri === undefined) {- return reject(new Error(`Could not read file "${file.name}"`));- }-- resolve({- format: file.type.split("/")[1],- path: String(dataUri),- name: file.name,- id: ObjectID().toString(),- status: "uploading",- });- });- reader.readAsDataURL(file);- });- assets.push(promise);- }- }-- return Promise.all(assets);-};--const maxSize = toBytes(MAX_UPLOAD_SIZE);--const toFormsData = (type: AssetType, input: HTMLInputElement) => {- const files = Array.from(input?.files ?? []);- const formsData: Array<FormData> = [];- if (files.length === 0) {- return formsData;- }- for (const file of files) {- const formData = new FormData();- if (file.size > maxSize) {- toast.error(- `Asset "${file.name}" cannot be bigger than ${MAX_UPLOAD_SIZE}MB`- );- continue;- }-- // sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443- // should be removed after fix- formData.append(type, file, sanitizeS3Key(file.name));- formsData.push(formData);- }- return formsData;-};--export const useAssets = (type: AssetType) => {- const [project] = useProject();- const [assets, setAssets] = useAssetsState();- const { load, data } = useFetcher();- const submit = usePersistentFetcher();-- const action = project && restAssetsPath({ projectId: project.id });-- useEffect(() => {- if (action && assets.length === 0) {- load(action);- }- }, [action, assets.length, load]);-- useEffect(() => {- if (data !== undefined) {- setAssets(data);- }- }, [data, setAssets]);-- const handleAfterSubmit = (data: UploadData) => {- if (data.status === "error") {- return toastUnknownFieldErrors(normalizeErrors(data.errors), []);- }-- // @todo currently waiting until all of them are fetched- // should update each individually when its loaded- if (action) {- load(action);- }- };-- const handleDelete = (ids: Array<string>) => {- const formData = new FormData();- for (const id of ids) {- formData.append("assetId", id);- }- submit<UploadData>(- formData,- { method: "delete", action },- handleAfterSubmit- );- };-- const handleSubmit = (input: HTMLInputElement) => {- const formsData = toFormsData(type, input);- toPreviewAssets(formsData)- .then((previewAssets) => {- setAssets([...previewAssets, ...assets]);- })- .catch((error) => {- if (error instanceof Error) {- toast.error(error.message);- }- });-- for (const formData of formsData) {- submit<UploadData>(- formData,- {- method: "post",- action,- encType: "multipart/form-data",- },- handleAfterSubmit- );- }- };-- const assetsByType = useMemo(- () => filterByType(assets, type),- [assets, type]- );-- return { handleSubmit, assets: assetsByType, handleDelete };-};diff --git a/apps/designer/app/designer/shared/assets/use-assets.tsx b/apps/designer/app/designer/shared/assets/use-assets.tsxnew file mode 100644index 0000000000..4640b35f1c--- /dev/null+++ b/apps/designer/app/designer/shared/assets/use-assets.tsx@@ -0,0 +1,345 @@+import {+ useEffect,+ useMemo,+ createContext,+ useContext,+ type ReactNode,+ useRef,+} from "react";+import {+ AssetType,+ idsFormDataFieldName,+ MAX_UPLOAD_SIZE,+ toBytes,+ type Asset,+} from "@webstudio-is/asset-uploader";+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 { sanitizeS3Key } from "@webstudio-is/asset-uploader";+import { ClientAsset, UploadingClientAsset } from "./types";+import { usePersistentFetcher } from "~/shared/fetcher";+import type { ActionData } from "~/designer/shared/assets";+import {+ FetcherData,+ normalizeErrors,+ toastUnknownFieldErrors,+} from "~/shared/form-utils";+import { Publish } from "~/shared/pubsub";+import { useFetcher } from "@remix-run/react";+import warnOnce from "warn-once";+import { updateStateAssets } from "./update-state-assets";++declare module "~/shared/pubsub" {+ export interface PubsubMap {+ updateAssets: Array<Asset>;+ }+}++export const usePublishAssets = (publish: Publish) => {+ const [clientAssets] = useClientAssets();+ 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!),+ });+ }, [clientAssets, publish]);+};++export type UploadData = FetcherData<ActionData>;++const toUploadingAssetsAndFormData = (+ type: AssetType,+ files: File[]+): Promise<[UploadingClientAsset, FormData][]> => {+ const assets: Array<Promise<[UploadingClientAsset, FormData]>> = [];++ for (const file of files) {+ const promise = new Promise<[UploadingClientAsset, FormData]>(+ (resolve, reject) => {+ const reader = new FileReader();+ reader.addEventListener("load", (event) => {+ const dataUri = event?.target?.result;+ if (dataUri === undefined) {+ return reject(new Error(`Could not read file "${file.name}"`));+ }++ const id = crypto.randomUUID();++ // sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443+ // should be removed after fix+ const formData = new FormData();+ formData.append(type, file, sanitizeS3Key(file.name));+ formData.append(idsFormDataFieldName, crypto.randomUUID());++ resolve([+ {+ status: "uploading",+ asset: undefined,+ preview: {+ format: file.type.split("/")[1],+ path: String(dataUri),+ name: file.name,+ description: file.name,+ id,+ },+ },+ formData,+ ]);+ });++ reader.readAsDataURL(file);+ }+ );++ assets.push(promise);+ }++ return Promise.all(assets);+};++const maxSize = toBytes(MAX_UPLOAD_SIZE);++const getFilesFromInput = (type: AssetType, input: HTMLInputElement) => {+ const files = Array.from(input?.files ?? []);++ const exceedSizeFiles = files.filter((file) => file.size > maxSize);++ for (const file of exceedSizeFiles) {+ toast.error(+ `Asset "${file.name}" cannot be bigger than ${MAX_UPLOAD_SIZE}MB`+ );+ }++ return files.filter((file) => file.size <= maxSize);+};++type AssetsContext = {+ handleSubmit: (type: AssetType, files: File[]) => Promise<void>;+ assets: Array<ClientAsset>;+ handleDelete: (ids: Array<string>) => void;+};++const Context = createContext<AssetsContext | undefined>(undefined);++export const AssetsProvider = ({ children }: { children: ReactNode }) => {+ const [project] = useProject();+ const [clientAssets, setClientAssets] = useClientAssets();+ const { load, data: serverAssets } = useFetcher<Asset[]>();+ const submit = usePersistentFetcher();+ const assetsRef = useRef(clientAssets);++ const action = project && restAssetsPath({ projectId: project.id });+ assetsRef.current = clientAssets;++ useEffect(() => {+ if (action && clientAssets.length === 0) {+ load(action);+ }+ }, [action, clientAssets.length, load]);++ useEffect(() => {+ if (serverAssets !== undefined) {+ const nextAssets = updateStateAssets(clientAssets, serverAssets);++ if (nextAssets !== clientAssets) {+ setClientAssets(nextAssets);+ }+ }+ }, [serverAssets, clientAssets, setClientAssets]);++ const handleDeleteAfterSubmit = (data: UploadData) => {+ // We need to remove assets only at updateStateAssets.+ // We can't remove it here optimistically because the previous load+ // can return it as "updated" because of the async operation nature+ if (action) {+ load(action);+ }++ 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;+ }++ return asset;+ });++ setClientAssets(nextAssets);++ return toastUnknownFieldErrors(normalizeErrors(data.errors), []);+ }+ };++ const handleAfterSubmit = (assetId: string) => (data: UploadData) => {+ const assets = assetsRef.current;++ if (action) {+ load(action);+ }++ 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+ )+ );++ return toastUnknownFieldErrors(normalizeErrors(data.errors), []);+ }++ warnOnce(+ data.uploadedAssets?.length !== 1,+ "Expected exactly 1 uploaded asset"+ );++ const uploadedAsset = data.uploadedAssets?.[0];++ if (uploadedAsset === undefined) {+ warnOnce(true, "An uploaded asset is undefined");+ 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+ )+ );+ return;+ }++ setClientAssets(+ assets.map((asset) => {+ if (asset.status === "uploading" && asset.preview.id === assetId) {+ // We can start using the uploaded asset for image previews etc+ return { ...asset, asset: uploadedAsset };+ }+ return asset;+ })+ );+ };++ const handleDelete = (ids: Array<string>) => {+ const formData = new FormData();+ const assets = assetsRef.current;++ const nextAssets = [...assets];++ for (const id of ids) {+ formData.append("assetId", id);+ // Mark assets as deleting+ const index = nextAssets.findIndex(+ (nextAsset) => nextAsset.asset?.id === id+ );++ if (index !== -1) {+ const asset = nextAssets[index];++ if (asset.status === "uploaded") {+ const newAsset: ClientAsset = {+ ...asset,+ status: "deleting",+ };++ nextAssets[index] = newAsset;+ continue;+ }++ warnOnce(true, "Trying to delete an asset that is not uploaded");+ }+ }++ setClientAssets(nextAssets);++ submit<UploadData>(+ formData,+ { method: "delete", action },+ handleDeleteAfterSubmit+ );+ };++ const handleSubmit = async (type: AssetType, files: File[]) => {+ try {+ const uploadingAssetsAndFormData = await toUploadingAssetsAndFormData(+ type,+ files+ );++ const assets = assetsRef.current;+ setClientAssets([+ ...uploadingAssetsAndFormData.map(([previewAsset]) => previewAsset),+ ...assets,+ ]);++ for (const [uploadingAsset, formData] of uploadingAssetsAndFormData) {+ submit<UploadData>(+ formData,+ {+ method: "post",+ action,+ encType: "multipart/form-data",+ },+ handleAfterSubmit(uploadingAsset.preview.id)+ );+ }+ } catch (error) {+ if (error instanceof Error) {+ toast.error(error.message);+ }+ }+ };++ return (+ <Context.Provider+ value={{ handleSubmit, assets: clientAssets, handleDelete }}+ >+ {children}+ </Context.Provider>+ );+};++const filterByType = (clientAssets: Array<ClientAsset>, type: AssetType) => {+ return clientAssets.filter((clientAsset) => {+ const format = clientAsset.asset?.format ?? clientAsset.preview?.format;++ const isFont = FONT_FORMATS.has(format as FontFormat);+ if (type === "font") {+ return isFont;+ }++ return isFont === false;+ });+};++export const useAssets = (type: AssetType) => {+ const assetsContext = useContext(Context);+ if (!assetsContext) {+ throw new Error("useAssets is used without AssetsProvider");+ }++ const assetsByType = useMemo(+ () => filterByType(assetsContext.assets, type),+ [assetsContext.assets, type]+ );++ const handleSubmit = (input: HTMLInputElement) => {+ const formsData = getFilesFromInput(type, input);+ assetsContext.handleSubmit(type, formsData);+ };++ return {+ handleSubmit,+ assets: assetsByType,+ handleDelete: assetsContext.handleDelete,+ };+};diff --git a/apps/designer/app/designer/shared/fonts-manager/item-utils.ts b/apps/designer/app/designer/shared/fonts-manager/item-utils.tsindex 75e12dafd4..b0f0283c0a 100644--- a/apps/designer/app/designer/shared/fonts-manager/item-utils.ts+++ b/apps/designer/app/designer/shared/fonts-manager/item-utils.ts@@ -1,21 +1,25 @@-import { Asset } from "@webstudio-is/asset-uploader";import { SYSTEM_FONTS } from "@webstudio-is/fonts";import { matchSorter } from "match-sorter";-import { PreviewAsset } from "../assets";+import { ClientAsset } from "../assets";export type Item = {label: string;type: "uploaded" | "system";};-export const toItems = (assets: Array<Asset | PreviewAsset>): Array<Item> => {+export const toItems = (clientAssets: Array<ClientAsset>): 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 asset of assets) {+ for (const clientAsset of clientAssets) {+ if (clientAsset.status !== "uploaded") {+ continue;+ }++ const { asset } = clientAsset;// @todo need to teach ts the right type from useAssetsif ("meta" in asset && "family" in asset.meta) {uploaded.set(asset.meta.family, {@@ -29,18 +33,26 @@ export const toItems = (assets: Array<Asset | PreviewAsset>): Array<Item> => {export const filterIdsByFamily = (family: string,- assets: Array<Asset | PreviewAsset>+ clientAssets: Array<ClientAsset>) => {// One family may have multiple assets for different formats, so we need to find them all.- return assets- .filter(- (asset) =>+ return (+ clientAssets+ .filter((clientAsset) => {+ if (clientAsset.status !== "uploaded") {+ return false;+ }+ const { asset } = clientAsset;// @todo need to teach TS the right type from useAssets- "meta" in asset &&- "family" in asset.meta &&- asset.meta.family === family- )- .map((asset) => asset.id);+ return (+ "meta" in asset &&+ "family" in asset.meta &&+ asset.meta.family === family+ );+ })+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- we filtered out non uploaded items+ .map((clientAssets) => clientAssets.asset!.id)+ );};export const groupItemsByType = (items: Array<Item>) => {diff --git a/apps/designer/app/designer/shared/image-manager/image-manager.tsx b/apps/designer/app/designer/shared/image-manager/image-manager.tsxindex 637d43eb55..03ae2d95d3 100644--- a/apps/designer/app/designer/shared/image-manager/image-manager.tsx+++ b/apps/designer/app/designer/shared/image-manager/image-manager.tsx@@ -1,20 +1,29 @@import { useState } from "react";import { findNextListIndex, Grid } from "@webstudio-is/design-system";-import type { Asset } from "@webstudio-is/asset-uploader";-import { AssetsShell, PreviewAsset, useAssets, useSearch } from "../assets";+import { AssetsShell, type ClientAsset, useAssets, useSearch } from "../assets";import { useFilter } from "../assets/use-filter";import { ImageThumbnail } from "./image-thumbnail";import { matchSorter } from "match-sorter";-const filterItems = (search: string, items: Array<Asset | PreviewAsset>) => {+const filterItems = (search: string, items: Array<ClientAsset>) => {return matchSorter(items, search, {- keys: [(item) => item.name],+ keys: [+ (item) =>+ item.status === "uploading" ? item.preview.name : item.asset.name,+ ],});};-const useLogic = ({ onChange }: { onChange?: (asset: Asset) => void }) => {+const useLogic = ({+ onChange,+}: {+ onChange?: (asset: ClientAsset) => void;+}) => {const { assets, handleDelete } = useAssets("image");+const [selectedIndex, setSelectedIndex] = useState(-1);++ // @todo filter out deleting assetsconst { filteredItems, resetFilteredItems, setFilteredItems } = useFilter({items: assets,onReset() {@@ -49,9 +58,11 @@ const useLogic = ({ onChange }: { onChange?: (asset: Asset) => void }) => {},});- const handleSelect = (asset?: Asset | PreviewAsset) => {+ const handleSelect = (clientAsset?: ClientAsset) => {const selectedIndex = filteredItems.findIndex(- (item) => item.id === asset?.id+ (item) =>+ (item.asset?.id ?? item.preview?.id) ===+ (clientAsset?.asset?.id ?? clientAsset?.preview?.id));setSelectedIndex(selectedIndex);};@@ -66,7 +77,7 @@ const useLogic = ({ onChange }: { onChange?: (asset: Asset) => void }) => {};type ImageManagerProps = {- onChange?: (asset: Asset) => void;+ onChange?: (asset: ClientAsset) => void;};export const ImageManager = ({ onChange }: ImageManagerProps) => {@@ -85,10 +96,10 @@ export const ImageManager = ({ onChange }: ImageManagerProps) => {type="image"><Grid columns={3} gap={2}>- {filteredItems.map((asset, index) => (+ {filteredItems.map((clientAsset, index) => (<ImageThumbnail- key={asset.id}- asset={asset}+ key={clientAsset.asset?.id ?? clientAsset.preview?.id}+ asset={clientAsset}onDelete={handleDelete}onSelect={handleSelect}onChange={onChange}diff --git a/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsx b/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsxindex 587fd01a2f..7ee43bfcab 100644--- a/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsx+++ b/apps/designer/app/designer/shared/image-manager/image-thumbnail.tsx@@ -9,8 +9,7 @@ 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 { PreviewAsset } from "~/designer/shared/assets";-import type { Asset } from "@webstudio-is/asset-uploader";+import type { ClientAsset } from "~/designer/shared/assets";import { Filename } from "./filename";const useImageWithFallback = ({@@ -36,6 +35,7 @@ const ThumbnailContainer = styled(Box, {justifyContent: "center",alignItems: "center",flexDirection: "column",+ margin: "$spacing$2",border: "2px solid transparent",borderRadius: "$borderRadius$4",outline: 0,@@ -47,6 +47,7 @@ const ThumbnailContainer = styled(Box, {status: {uploading: {},uploaded: {},+ deleting: {},},state: {selected: {@@ -67,26 +68,37 @@ const Thumbnail = styled(Box, {});type ImageThumbnailProps = {- asset: Asset | PreviewAsset;+ asset: ClientAsset;onDelete: (ids: Array<string>) => void;- onSelect: (asset?: Asset | PreviewAsset) => void;- onChange?: (asset: Asset) => void;+ onSelect: (asset?: ClientAsset) => void;+ onChange?: (asset: ClientAsset) => void;state?: "selected";};export const ImageThumbnail = ({- asset,+ asset: clientAsset,onDelete,onSelect,onChange,state,}: ImageThumbnailProps) => {- const { path, status, name } = asset;+ const asset =+ clientAsset.status === "uploading"+ ? clientAsset.preview+ : clientAsset.asset;++ const { status } = clientAsset;++ const { path, name } = asset;+const description =- "description" in asset && asset.description ? asset.description : name;+ "description" in asset && asset.description+ ? (asset.description as string)+ : name;+const isUploading = status === "uploading";- const isUploadedAsset = isUploading === false && "size" in asset;- const [isDeleting, setIsDeleting] = useState(false);+ const isDeleting = status === "deleting";+const src = useImageWithFallback({ path });return (@@ -95,7 +107,11 @@ export const ImageThumbnail = ({tabIndex={0}status={status}state={state}- onFocus={() => onSelect?.(asset)}+ onFocus={() => {+ if (clientAsset.status !== "deleting") {+ onSelect?.(clientAsset);+ }+ }}onBlur={(event: FocusEvent) => {const isFocusWithin = event.currentTarget.contains(event.relatedTarget);if (isFocusWithin === false) {@@ -103,16 +119,16 @@ export const ImageThumbnail = ({}}}onKeyDown={(event: KeyboardEvent) => {- if (event.code === "Enter" && asset.status === "uploaded") {- onChange?.(asset);+ if (event.code === "Enter" && clientAsset.status === "uploaded") {+ onChange?.(clientAsset);}}}><Thumbnailcss={{ backgroundImage: `url("${src}")` }}onClick={() => {- if (isUploadedAsset) {- onChange?.(asset);+ if (clientAsset.status === "uploaded") {+ onChange?.(clientAsset);}}}/>@@ -125,11 +141,10 @@ export const ImageThumbnail = ({><Filename variant={"tiny"}>{name}</Filename></Box>- {isUploadedAsset && (+ {clientAsset.status === "uploaded" && (<ImageInfoTrigger- asset={asset}+ asset={clientAsset.asset}onDelete={(ids) => {- setIsDeleting(true);onDelete(ids);}}/>diff --git a/apps/designer/app/designer/shared/nano-states/index.ts b/apps/designer/app/designer/shared/nano-states/index.tsindex 8f3d746055..fc9d0e8540 100644--- a/apps/designer/app/designer/shared/nano-states/index.ts+++ b/apps/designer/app/designer/shared/nano-states/index.ts@@ -5,9 +5,8 @@ import {type HoveredInstanceData,} from "@webstudio-is/project";import { type SyncStatus } from "~/shared/sync";-import { Asset } from "@webstudio-is/asset-uploader";import { type Pages, type Project } from "@webstudio-is/project";-import type { PreviewAsset } from "../assets";+import type { ClientAsset } from "../assets";const selectedInstanceDataContainer = createValueContainer<SelectedInstanceData | undefined@@ -46,8 +45,8 @@ export const useCanvasRect = () => useValue(canvasRectContainer);const syncStatusContainer = createValueContainer<SyncStatus>("idle");export const useSyncStatus = () => useValue(syncStatusContainer);-const assetsContainer = createValueContainer<Array<Asset | PreviewAsset>>([]);-export const useAssets = () => useValue(assetsContainer);+const clientAssetsContainer = createValueContainer<Array<ClientAsset>>([]);+export const useClientAssets = () => useValue(clientAssetsContainer);const pagesContainer = createValueContainer<Pages | undefined>();export const usePages = () => useValue(pagesContainer);diff --git a/packages/asset-uploader/src/db/create.ts b/packages/asset-uploader/src/db/create.tsindex f8e8502348..eef883ebf1 100644--- a/packages/asset-uploader/src/db/create.ts+++ b/packages/asset-uploader/src/db/create.ts@@ -8,6 +8,7 @@ import { type ImageMeta } from "../schema";import { formatAsset } from "../utils/format-asset";type BaseOptions = {+ id: string;name: string;size: number;location: Location;@@ -23,9 +24,10 @@ type Options =const create = (projectId: Project["id"], options: Options) => {const size = options.size || 0;- const { meta, format, name, location } = options;+ const { id, meta, format, name, location } = options;return prisma.asset.create({data: {+ id,location,name,size,diff --git a/packages/asset-uploader/src/index.ts b/packages/asset-uploader/src/index.tsindex 699250178c..feff34e0af 100644--- a/packages/asset-uploader/src/index.ts+++ b/packages/asset-uploader/src/index.ts@@ -1,6 +1,5 @@export * from "./types";export * from "./schema";export * from "./constants";-export * from "./utils/filter-by-type";export * from "./utils/to-bytes";export * from "./utils/sanitize-s3-key";diff --git a/packages/asset-uploader/src/schema.ts b/packages/asset-uploader/src/schema.tsindex 65a49d5572..a981d16171 100644--- a/packages/asset-uploader/src/schema.ts+++ b/packages/asset-uploader/src/schema.ts@@ -43,7 +43,6 @@ const BaseAsset = z.object({location: Location,createdAt: z.string(),path: z.string(),- status: z.literal("uploaded").optional(),});export const FontAsset = BaseAsset.omit({ format: true }).extend({@@ -59,3 +58,5 @@ export type ImageAsset = z.infer<typeof ImageAsset>;export const Asset = z.union([FontAsset, ImageAsset]);export type Asset = z.infer<typeof Asset>;++export const idsFormDataFieldName = "ids";diff --git a/packages/asset-uploader/src/targets/fs/upload.ts b/packages/asset-uploader/src/targets/fs/upload.tsindex 985536c560..a77e5ab352 100644--- a/packages/asset-uploader/src/targets/fs/upload.ts+++ b/packages/asset-uploader/src/targets/fs/upload.ts@@ -2,17 +2,20 @@ import { z } from "zod";import {unstable_parseMultipartFormData as unstableParseMultipartFormData,unstable_createFileUploadHandler as unstableCreateFileUploadHandler,+ unstable_composeUploadHandlers as unstableComposeUploadHandlers,NodeOnDiskFile,} from "@remix-run/node";import { Location } from "@webstudio-is/prisma-client";import { getAssetData } from "../../utils/get-asset-data";import { createMany } from "../../db";import { FILE_DIRECTORY } from "./file-path";-import { Asset } from "../../schema";+import { Asset, idsFormDataFieldName } from "../../schema";import { getUniqueFilename } from "../../utils/get-unique-filename";import { sanitizeS3Key } from "../../utils/sanitize-s3-key";+import { uuidHandler } from "../../utils/uuid-handler";const AssetsFromFs = z.array(z.instanceof(NodeOnDiskFile));+const Ids = z.array(z.string().uuid());export const uploadToFs = async ({request,@@ -29,13 +32,19 @@ export const uploadToFs = async ({file: ({ filename }) => getUniqueFilename(sanitizeS3Key(filename)),});- const formData = await unstableParseMultipartFormData(request, uploadHandler);+ const formData = await unstableParseMultipartFormData(+ request,+ unstableComposeUploadHandlers(uploadHandler, uuidHandler)+ );+const formDataImages = AssetsFromFs.parse(formData.getAll("image"));const formDataFonts = AssetsFromFs.parse(formData.getAll("font"));const formDataAll = [...formDataImages, ...formDataFonts];+ const ids = Ids.parse(formData.getAll(idsFormDataFieldName));- const assets = formDataAll.map(async (asset) =>+ const assets = formDataAll.map(async (asset, index) =>getAssetData({+ id: ids[index],type: formDataFonts.includes(asset) ? "font" : "image",name: asset.name,size: asset.size,diff --git a/packages/asset-uploader/src/targets/s3/upload.ts b/packages/asset-uploader/src/targets/s3/upload.tsindex 5a870ce3c2..a46e091ad1 100644--- a/packages/asset-uploader/src/targets/s3/upload.ts+++ b/packages/asset-uploader/src/targets/s3/upload.ts@@ -2,6 +2,7 @@ import { z } from "zod";import {type UploadHandlerPart,unstable_parseMultipartFormData as unstableCreateFileUploadHandler,+ unstable_composeUploadHandlers as unstableComposeUploadHandlers,MaxPartSizeExceededError,} from "@remix-run/node";import { PutObjectCommandInput } from "@aws-sdk/client-s3";@@ -11,15 +12,18 @@ import { S3Env } from "../../schema";import { toUint8Array } from "../../utils/to-uint8-array";import { getAssetData } from "../../utils/get-asset-data";import { createMany } from "../../db";-import type { Asset } from "../../schema";+import { idsFormDataFieldName, type Asset } from "../../schema";import { getUniqueFilename } from "../../utils/get-unique-filename";import { getS3Client } from "./client";import { sanitizeS3Key } from "../../utils/sanitize-s3-key";+import { uuidHandler } from "../../utils/uuid-handler";const AssetsUploadedSuccess = z.object({Location: z.string(),});+const Ids = z.array(z.string().uuid());+export const uploadToS3 = async ({request,projectId,@@ -31,19 +35,26 @@ export const uploadToS3 = async ({}): Promise<Array<Asset>> => {const formData = await unstableCreateFileUploadHandler(request,- (file: UploadHandlerPart) =>- uploadHandler({- file,- maxSize,- })+ unstableComposeUploadHandlers(+ (file: UploadHandlerPart) =>+ uploadHandler({+ file,+ maxSize,+ }),+ uuidHandler+ ));const imagesFormData = formData.getAll("image") as Array<string>;const fontsFormData = formData.getAll("font") as Array<string>;- const assetsData = [...imagesFormData, ...fontsFormData].map((dataString) => {- // @todo validate with zod- return JSON.parse(dataString);- });+ const ids = Ids.parse(formData.getAll(idsFormDataFieldName));++ const assetsData = [...imagesFormData, ...fontsFormData].map(+ (dataString, i) => {+ // @todo validate with zod+ return { ...JSON.parse(dataString), id: ids[i] };+ }+ );return await createMany(projectId, assetsData);};@@ -54,7 +65,12 @@ const uploadHandler = async ({}: {file: UploadHandlerPart;maxSize: number;-}): Promise<string> => {+}): Promise<string | undefined> => {+ if (file.filename === undefined) {+ // Do not parse if it's not a file+ return;+ }+if (!file.data) {throw new Error("Your asset seems to be empty");}@@ -69,10 +85,6 @@ const uploadHandler = async ({throw new MaxPartSizeExceededError(file.name, maxSize);}- if (file.filename === undefined) {- throw new Error("Filename is required");- }-const fileName = sanitizeS3Key(file.filename);const uniqueFilename = getUniqueFilename(fileName);@@ -112,11 +124,15 @@ const uploadHandler = async ({if (type === "image") {assetOptions = {+ // Id will be set later+ id: "",type,...baseAssetOptions,};} else if (type === "font") {assetOptions = {+ // Id will be set later+ id: "",type,...baseAssetOptions,};diff --git a/packages/asset-uploader/src/utils/filter-by-type.ts b/packages/asset-uploader/src/utils/filter-by-type.tsdeleted file mode 100644index e32af2d3fe..0000000000--- a/packages/asset-uploader/src/utils/filter-by-type.ts+++ /dev/null@@ -1,16 +0,0 @@-import { type FontFormat, FONT_FORMATS } from "@webstudio-is/fonts";-import type { AssetType } from "../types";--export const filterByType = <PartialAsset extends { format: string }>(- assets: Array<PartialAsset>,- type: AssetType-) => {- return assets.filter(({ format }: PartialAsset) => {- const isFont = FONT_FORMATS.has(format as FontFormat);- if (type === "font") {- return isFont;- }-- return isFont === false;- });-};diff --git a/packages/asset-uploader/src/utils/get-asset-data.ts b/packages/asset-uploader/src/utils/get-asset-data.tsindex 9c4fc77b56..444fe32399 100644--- a/packages/asset-uploader/src/utils/get-asset-data.ts+++ b/packages/asset-uploader/src/utils/get-asset-data.ts@@ -5,6 +5,7 @@ import { type FontMeta } from "@webstudio-is/fonts";import { getFontData } from "@webstudio-is/fonts/server";type BaseData = {+ id: string;name: string;size: number;location: Location;@@ -24,6 +25,7 @@ type FontData = BaseData & {export type AssetData = ImageData | FontData;type BaseAssetOptions = {+ id: string;name: string;size: number;data: Uint8Array;@@ -56,6 +58,7 @@ export const getAssetData = async (return {...baseData,+ id: options.id,type: options.type,format,meta: { width, height },@@ -65,6 +68,7 @@ export const getAssetData = async (const { format, ...meta } = getFontData(options.data);return {+ id: options.id,type: options.type,...baseData,format,diff --git a/packages/asset-uploader/src/utils/to-uint8-array.ts b/packages/asset-uploader/src/utils/to-uint8-array.tsindex 7dfcdde457..39ca572d9c 100644--- a/packages/asset-uploader/src/utils/to-uint8-array.ts+++ b/packages/asset-uploader/src/utils/to-uint8-array.ts@@ -1,10 +1,8 @@export const toUint8Array = async (data: AsyncIterable<Uint8Array>) => {const result = [];for await (const chunk of data) {- for (const byte of chunk) {- result.push(byte);- }+ result.push(Buffer.from(chunk));}- return Uint8Array.from(result);+ return new Uint8Array(Buffer.concat(result));};diff --git a/packages/asset-uploader/src/utils/uuid-handler.ts b/packages/asset-uploader/src/utils/uuid-handler.tsnew file mode 100644index 0000000000..eaa6771ed5--- /dev/null+++ b/packages/asset-uploader/src/utils/uuid-handler.ts@@ -0,0 +1,9 @@+import { type UploadHandler as UnstableUploadHandler } from "@remix-run/node";+import { idsFormDataFieldName } from "../schema";+import { toUint8Array } from "./to-uint8-array";++export const uuidHandler: UnstableUploadHandler = async (part) => {+ if (part.name === idsFormDataFieldName) {+ return Buffer.from(await toUint8Array(part.data)).toString();+ }+};