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 useFetcher
Oleg Isonen3a4b2dc8156e
diff --git a/apps/designer/app/designer/shared/assets/asset-upload.tsx b/apps/designer/app/designer/shared/assets/asset-upload.tsxindex 165d7c72d1..c04cf4589f 100644--- a/apps/designer/app/designer/shared/assets/asset-upload.tsx+++ b/apps/designer/app/designer/shared/assets/asset-upload.tsx@@ -1,99 +1,23 @@-import { Form, FormEncType, FormMethod, useActionData } from "@remix-run/react";-import ObjectID from "bson-objectid";-import { ChangeEvent, useEffect, useRef } from "react";-import { Button, Flex, Text, toast } from "@webstudio-is/design-system";+import { ChangeEvent, useRef } from "react";+import { Button, Flex, Text } from "@webstudio-is/design-system";import { UploadIcon } from "@webstudio-is/icons";-import {- MAX_UPLOAD_SIZE,- toBytes,- type AssetType,-} from "@webstudio-is/asset-uploader";-import type { ActionData, PreviewAsset } from "./types";+import { type AssetType } from "@webstudio-is/asset-uploader";import { FONT_MIME_TYPES } from "@webstudio-is/fonts";-import { useSerialSubmit } from "./use-serial-submit";+import { useAssets } from "./use-assets";-const toPreviewAssets = (formData: FormData): Promise<PreviewAsset[]> => {- const assets: Array<Promise<PreviewAsset>> = [];-- for (const entry of formData) {- const file = entry[1] as File;- 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 useUpload = ({- onSubmit,- onActionData,- type,-}: {- onActionData: (data: ActionData) => void;- onSubmit: (assets: Array<PreviewAsset>) => void;- type: AssetType;-}) => {- const submit = useSerialSubmit();+const useUpload = (type: AssetType) => {+ const { handleSubmit, Form } = useAssets(type);const inputRef = useRef<HTMLInputElement | null>(null);- const actionData: ActionData | undefined = useActionData();const onChange = (event: ChangeEvent<HTMLFormElement>) => {- const files = Array.from(inputRef?.current?.files ?? []);- if (files.length !== 0) {- const form = event.currentTarget;- const formData = new FormData();- for (const file of files) {- if (file.size > maxSize) {- toast.error(- `Asset "${file.name}" cannot be bigger than ${MAX_UPLOAD_SIZE}MB`- );- continue;- }- formData.append(type, file, file.name);- }- const options = {- method: form.method as FormMethod,- action: form.action,- encType: form.enctype as FormEncType,- };- submit(formData, options);- toPreviewAssets(formData)- .then(onSubmit)- .catch((error: unknown) => {- if (error instanceof Error) {- toast.error(error.message);- }- });- form.reset();- }+ const form = event.currentTarget;+ const input = inputRef.current;+ if (input === null) return;+ handleSubmit({ form, input });+ form.reset();};- useEffect(() => {- if (actionData !== undefined) {- onActionData(actionData);- }- }, [actionData, onActionData]);-- return { inputRef, onChange };+ return { inputRef, onChange, Form };};const acceptMap = {@@ -102,17 +26,11 @@ const acceptMap = {};type AssetUploadProps = {- onActionData: (data: ActionData) => void;- onSubmit: (assets: Array<PreviewAsset>) => void;type: AssetType;};-export const AssetUpload = ({- onSubmit,- onActionData,- type,-}: AssetUploadProps) => {- const { inputRef, onChange } = useUpload({ onSubmit, onActionData, type });+export const AssetUpload = ({ type }: AssetUploadProps) => {+ const { inputRef, onChange, Form } = useUpload(type);return (<Flexas={Form}diff --git a/apps/designer/app/designer/shared/assets/use-assets.ts b/apps/designer/app/designer/shared/assets/use-assets.tsindex b0b739054c..71752bcdf5 100644--- a/apps/designer/app/designer/shared/assets/use-assets.ts+++ b/apps/designer/app/designer/shared/assets/use-assets.ts@@ -1,65 +1,66 @@-import { useMemo, useState } from "react";-import type { PreviewAsset, ActionData } from "./types";+import { FormEncType, FormMethod, useFetcher } from "@remix-run/react";import {- type AssetType,- type Asset,+ AssetType,filterByType,+ MAX_UPLOAD_SIZE,+ toBytes,} from "@webstudio-is/asset-uploader";-import { useAssets as useAllAssets } from "../nano-states";-import { useSubmit } from "@remix-run/react";+import { toast } from "@webstudio-is/design-system";+import ObjectID from "bson-objectid";+import { useMemo } from "react";+import { useAssets as useAssetsState } from "../nano-states";+import { PreviewAsset } from "./types";-type UseAssetsApi = {- assets: Array<Asset | PreviewAsset>;- onSubmitAssets: (assets: Array<PreviewAsset>) => void;- onActionData: (data: ActionData) => void;- onDelete: (ids: Array<string>) => void;-};+const toPreviewAssets = (formData: FormData): Promise<PreviewAsset[]> => {+ const assets: Array<Promise<PreviewAsset>> = [];-export const useAssets = (type: AssetType): UseAssetsApi => {- const submit = useSubmit();- const [allAssets] = useAllAssets();- const [actionData, setActionData] = useState<ActionData>({});- const [uploadingAssets, setUploadingAssets] = useState<Array<PreviewAsset>>(- []- );+ for (const entry of formData) {+ const file = entry[1] as File;+ 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}"`));+ }- const assets = useMemo(() => {- const {- errors,- uploadedAssets = [],- deletedAssets = [],- } = actionData ?? {};- let assets: Array<Asset | PreviewAsset> = [];+ resolve({+ format: file.type.split("/")[1],+ path: String(dataUri),+ name: file.name,+ id: ObjectID().toString(),+ status: "uploading",+ });+ });+ reader.readAsDataURL(file);+ });+ assets.push(promise);+ }- // Once we have uploaded or deleted assets in action data, current upload was finished.- if (- uploadedAssets.length === 0 &&- deletedAssets.length === 0 &&- errors === undefined- ) {- assets = [...uploadingAssets];- }+ return Promise.all(assets);+};- for (const uploadedAsset of uploadedAssets) {- const isInAllAssets = allAssets.some(- (asset) => asset.id === uploadedAsset.id- );- if (isInAllAssets === false) {- assets.unshift(uploadedAsset);- }- }+const maxSize = toBytes(MAX_UPLOAD_SIZE);- for (const asset of allAssets) {- const isDeleted = deletedAssets.some(- (deletedAsset) => deletedAsset.id === asset.id+const toFormData = (type: AssetType, input: HTMLInputElement) => {+ const files = Array.from(input?.files ?? []);+ const formData = new FormData();+ if (files.length === 0) return formData;+ for (const file of files) {+ if (file.size > maxSize) {+ toast.error(+ `Asset "${file.name}" cannot be bigger than ${MAX_UPLOAD_SIZE}MB`);- if (isDeleted === false) {- assets.push(asset);- }+ continue;}+ formData.append(type, file, file.name);+ }+ return formData;+};- return filterByType(assets, type);- }, [actionData, uploadingAssets, type, allAssets]);+export const useAssets = (type: AssetType) => {+ const { submit, Form } = useFetcher();+ const [assets, setAssets] = useAssetsState();const handleDelete = (ids: Array<string>) => {const formData = new FormData();@@ -69,10 +70,34 @@ export const useAssets = (type: AssetType): UseAssetsApi => {submit(formData, { method: "delete" });};- return {- assets,- onSubmitAssets: setUploadingAssets,- onActionData: setActionData,- onDelete: handleDelete,+ const handleSubmit = ({+ form,+ input,+ }: {+ form: HTMLFormElement;+ input: HTMLInputElement;+ }) => {+ const formData = toFormData(type, input);+ submit(formData, {+ method: form.method as FormMethod,+ action: form.action,+ encType: form.enctype as FormEncType,+ });+ toPreviewAssets(formData)+ .then((previewAssets) => {+ setAssets([...previewAssets, ...assets]);+ })+ .catch((error) => {+ if (error instanceof Error) {+ toast.error(error.message);+ }+ });};++ const assetsByType = useMemo(+ () => filterByType(assets, type),+ [assets, type]+ );++ return { handleSubmit, Form, assets: assetsByType, handleDelete };};diff --git a/apps/designer/app/designer/shared/assets/use-serial-submit.ts b/apps/designer/app/designer/shared/assets/use-serial-submit.tsdeleted file mode 100644index c74cf5a602..0000000000--- a/apps/designer/app/designer/shared/assets/use-serial-submit.ts+++ /dev/null@@ -1,41 +0,0 @@-import { useActionData, useSubmit, type SubmitOptions } from "@remix-run/react";-import { useCallback, useEffect, useRef, useState } from "react";--const initialSubmission: {- data: Array<[string, FormDataEntryValue]>;- options: SubmitOptions;-} = {- data: [],- options: {},-};--/**- * Wrapps useSubmit hook to submit form data serially.- * This is useful when you want to submit multiple files, but send them one after another.- * Specifically Vercel has a single upload limit of 4.5MB, so we need to send them one by one so that this limit is per file, not per total upload- */-export const useSerialSubmit = () => {- const submit = useSubmit();- const actionData = useActionData();- const [submission, setSubmission] =- useState<typeof initialSubmission>(initialSubmission);- const submittedRef = useRef(new Map());-- useEffect(() => {- const submitted = submittedRef.current;- for (const entry of submission.data) {- if (submitted.has(entry) === false) {- const data = new FormData();- data.append(entry[0], entry[1]);- submit(data, submission.options);- submitted.set(entry, true);- break;- }- }- }, [actionData, submission, submit]);-- return useCallback((formData: FormData, options: SubmitOptions) => {- const data = Array.from(formData.entries());- setSubmission({ data, options });- }, []);-};diff --git a/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx b/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsxindex ccdb63d485..2161be9a49 100644--- a/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx+++ b/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx@@ -63,9 +63,9 @@ type FontsManagerProps = {};export const FontsManager = ({ value, onChange }: FontsManagerProps) => {- const { assets, onSubmitAssets, onActionData, onDelete } = useAssets("font");+ const { assets, handleDelete } = useAssets("font");- const handleDelete = (family: string) => {+ const handleDeleteByLabel = (family: string) => {// One family may have multiple assets for different formats, so we need to delete them all.const ids = assets.filter(@@ -76,7 +76,7 @@ export const FontsManager = ({ value, onChange }: FontsManagerProps) => {asset.meta.family === family).map((asset) => asset.id);- onDelete(ids);+ handleDelete(ids);};const fontItems = useMemo(() => getItems(assets), [assets]);@@ -104,11 +104,7 @@ export const FontsManager = ({ value, onChange }: FontsManagerProps) => {css={{ padding: "$1", paddingTop: "$2", height: 460, overflow: "hidden" }}><Box css={{ padding: "$2" }}>- <AssetUpload- onSubmit={onSubmitAssets}- onActionData={onActionData}- type="font"- />+ <AssetUpload type="font" /></Box><Flex@@ -132,7 +128,7 @@ export const FontsManager = ({ value, onChange }: FontsManagerProps) => {{item.label}<ItemMenuonDelete={() => {- handleDelete(item.label);+ handleDeleteByLabel(item.label);}}/></ComboboxListboxItem>diff --git a/apps/designer/app/designer/shared/image-manager/image-manager.tsx b/apps/designer/app/designer/shared/image-manager/image-manager.tsxindex f46c15bec4..860b56ccdd 100644--- a/apps/designer/app/designer/shared/image-manager/image-manager.tsx+++ b/apps/designer/app/designer/shared/image-manager/image-manager.tsx@@ -1,30 +1,25 @@import { Box, Flex, Grid } from "@webstudio-is/design-system";import type { Asset } from "@webstudio-is/asset-uploader";import { ImageThumbnail } from "./image-thumbnail";-import { AssetUpload } from "../assets/asset-upload";-import { useAssets } from "../assets/use-assets";+import { AssetUpload, useAssets } from "../assets";type ImageManagerProps = {onSelect?: (asset: Asset) => void;};export const ImageManager = ({ onSelect }: ImageManagerProps) => {- const { assets, onSubmitAssets, onActionData, onDelete } = useAssets("image");+ const { assets, handleDelete } = useAssets("image");return (<Flex gap="3" direction="column" css={{ padding: "$1", paddingTop: "$2" }}><Box css={{ padding: "$2" }}>- <AssetUpload- onSubmit={onSubmitAssets}- onActionData={onActionData}- type="image"- />+ <AssetUpload type="image" /></Box><Grid columns={2} gap={2}>{assets.map((asset) => (<ImageThumbnailkey={asset.id}asset={asset}- onDelete={onDelete}+ onDelete={handleDelete}onSelect={onSelect}/>))}diff --git a/apps/designer/app/designer/shared/nano-states/index.ts b/apps/designer/app/designer/shared/nano-states/index.tsindex f0e0e9a4b2..9c2b78fd13 100644--- a/apps/designer/app/designer/shared/nano-states/index.ts+++ b/apps/designer/app/designer/shared/nano-states/index.ts@@ -7,6 +7,7 @@ import {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";const selectedInstanceDataContainer = createValueContainer<SelectedInstanceData | undefined@@ -48,7 +49,7 @@ export const useSyncStatus = () => useValue(syncStatusContainer);const selectionRectContainer = createValueContainer<DOMRect | undefined>();export const useSelectionRect = () => useValue(selectionRectContainer);-const assetsContainer = createValueContainer<Array<Asset>>([]);+const assetsContainer = createValueContainer<Array<Asset | PreviewAsset>>([]);export const useAssets = () => useValue(assetsContainer);const pagesContainer = createValueContainer<Pages | undefined>();