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
Add assets store (#1361)
Bogdan Chadkin362cced07194
diff --git a/apps/builder/app/builder/shared/assets/types.ts b/apps/builder/app/builder/shared/assets/types.tsindex fef6d3bf02..b205b6aee9 100644--- a/apps/builder/app/builder/shared/assets/types.ts+++ b/apps/builder/app/builder/shared/assets/types.ts@@ -1,6 +1,6 @@import type { Asset } from "@webstudio-is/asset-uploader";-type PreviewAsset = Pick<+export type PreviewAsset = Pick<Asset,"path" | "name" | "id" | "format" | "description" | "type">;@@ -15,14 +15,6 @@ export type UploadingAssetContainer = {asset: Asset | PreviewAsset;};-/**- * Used for optimistic UI only- **/-export type DeletingAssetContainer = {- status: "deleting";- asset: Asset;-};-/*** Assets that can be shown in the UI*/diff --git a/apps/builder/app/builder/shared/assets/use-assets.tsx b/apps/builder/app/builder/shared/assets/use-assets.tsxindex 4d66bb8a1c..254cc370dd 100644--- a/apps/builder/app/builder/shared/assets/use-assets.tsx+++ b/apps/builder/app/builder/shared/assets/use-assets.tsx@@ -1,5 +1,10 @@-import { useMemo, createContext, useContext, type ReactNode } from "react";-import { useStore } from "@nanostores/react";+import {+ useMemo,+ createContext,+ useContext,+ type ReactNode,+ useState,+} from "react";import warnOnce from "warn-once";import type { Project } from "@webstudio-is/project";import {@@ -7,20 +12,44 @@ import {idsFormDataFieldName,MAX_UPLOAD_SIZE,toBytes,+ Asset,} from "@webstudio-is/asset-uploader";import { toast } from "@webstudio-is/design-system";import { sanitizeS3Key } from "@webstudio-is/asset-uploader";-import { assetContainersStore } from "~/shared/nano-states";import { restAssetsPath } from "~/shared/router-utils";import type {AssetContainer,- DeletingAssetContainer,- UploadedAssetContainer,+ PreviewAsset,UploadingAssetContainer,} from "./types";import { usePersistentFetcher } from "~/shared/fetcher";import type { ActionData } from "~/builder/shared/assets";import { normalizeErrors, toastUnknownFieldErrors } from "~/shared/form-utils";+import { assetsStore } from "~/shared/nano-states";+import { useStore } from "@nanostores/react";++// stubbed asset is necessary to preserve position of asset+// while uploading and after it is uploaded+// undefined is not stored in db and only persisted in current session+const stubAssets = (ids: Asset["id"][]) => {+ const assets = new Map(assetsStore.get());+ for (const assetId of ids) {+ assets.set(assetId, undefined);+ }+ assetsStore.set(assets);+};++const setAsset = (asset: Asset) => {+ const assets = new Map(assetsStore.get());+ assets.set(asset.id, asset);+ assetsStore.set(assets);+};++const cleanAsset = (assetId: Asset["id"]) => {+ const assets = new Map(assetsStore.get());+ assets.delete(assetId);+ assetsStore.set(assets);+};export type UploadData = ActionData;@@ -92,7 +121,7 @@ const getFilesFromInput = (_type: AssetType, input: HTMLInputElement) => {type AssetsContext = {handleSubmit: (type: AssetType, files: File[]) => Promise<void>;- assetContainers: Array<AssetContainer | DeletingAssetContainer>;+ assetContainers: AssetContainer[];handleDelete: (ids: Array<string>) => void;};@@ -107,52 +136,41 @@ export const AssetsProvider = ({authToken: string | undefined;children: ReactNode;}) => {- const assetContainers = useStore(assetContainersStore);+ const [deletingAssetIds, setDeletingAssetIds] = useState<Asset["id"][]>([]);+ const [uploadingAssets, setUploadingAssets] = useState<+ Array<Asset | PreviewAsset>+ >([]);const submit = usePersistentFetcher();const action = restAssetsPath({ projectId: projectId, authToken });- const handleDeleteAfterSubmit = (data: UploadData) => {+ const handleDeleteAfterSubmit = (ids: Asset["id"][], data: UploadData) => {+ setDeletingAssetIds((prev) =>+ prev.filter((assetId) => ids.includes(assetId) === false)+ );+const { errors, deletedAssets } = data;- const assetContainers = assetContainersStore.get();if (errors !== undefined) {- const nextAssetContainers = assetContainers.map((assetContainer) => {- if (assetContainer.status === "deleting") {- const uploadedAssetContainer: UploadedAssetContainer = {- ...assetContainer,- status: "uploaded",- };- return uploadedAssetContainer;- }-- return assetContainer;- });- assetContainersStore.set(nextAssetContainers);return toastUnknownFieldErrors(normalizeErrors(errors), []);}- if (deletedAssets) {- const deletedIds = new Set(deletedAssets.map((asset) => asset.id));- assetContainersStore.set(- assetContainers.filter(- (assetContainer) => deletedIds.has(assetContainer.asset.id) === false- )- );+ if (deletedAssets === undefined) {+ warnOnce(true, "Deleted assets is undefined");+ toast.error("Could not delete assets");+ return;+ }++ for (const deletedId of ids) {+ cleanAsset(deletedId);}};const handleAfterSubmit = (assetId: string, data: UploadData) => {- const assetContainers = assetContainersStore.get();+ // remove uploaded or failed asset+ setUploadingAssets((prev) => prev.filter((asset) => asset.id !== assetId));if (data.errors !== undefined) {- assetContainersStore.set(- assetContainers.filter(- (assetContainer) =>- assetContainer.status !== "uploading" ||- assetContainer.asset.id !== assetId- )- );-+ cleanAsset(assetId);return toastUnknownFieldErrors(normalizeErrors(data.errors ?? "Could not upload an asset"),[]@@ -169,68 +187,24 @@ export const AssetsProvider = ({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- assetContainersStore.set(- assetContainers.filter(- (assetContainer) =>- assetContainer.status !== "uploading" ||- assetContainer.asset.id !== assetId- )- );+ cleanAsset(assetId);return;}- assetContainersStore.set(- assetContainers.map((assetContainer) => {- if (- assetContainer.status === "uploading" &&- assetContainer.asset.id === assetId- ) {- // We can start using the uploaded asset for image previews etc- return { status: "uploaded", asset: uploadedAsset };- }- return assetContainer;- })- );+ // update store with new asset+ setAsset(uploadedAsset);};const handleDelete = (ids: Array<string>) => {- const formData = new FormData();- const assetContainer = assetContainersStore.get();-- const nextAssetContainers = [...assetContainer];+ setDeletingAssetIds((prev) => [...prev, ...ids]);+ const formData = new FormData();for (const id of ids) {formData.append("assetId", id);- // Mark assets as deleting- const index = nextAssetContainers.findIndex(- (nextAssetContainer) => nextAssetContainer.asset.id === id- );-- if (index !== -1) {- const asset = nextAssetContainers[index];-- if (asset.status === "uploaded") {- const newAsset: DeletingAssetContainer = {- ...asset,- status: "deleting",- };-- nextAssetContainers[index] = newAsset;- continue;- }-- warnOnce(true, "Trying to delete an asset that is not uploaded");- }}- assetContainersStore.set(nextAssetContainers);-- submit<UploadData>(- formData,- { method: "delete", action },- handleDeleteAfterSubmit+ submit<UploadData>(formData, { method: "delete", action }, (data) =>+ handleDeleteAfterSubmit(ids, data));};@@ -240,11 +214,13 @@ export const AssetsProvider = ({type,files);+ const uploadingAssets = uploadingAssetsAndFormData.map(+ ([previewAsset]) => previewAsset.asset+ );++ setUploadingAssets((prev) => [...uploadingAssets, ...prev]);- assetContainersStore.set([- ...uploadingAssetsAndFormData.map(([previewAsset]) => previewAsset),- ...assetContainersStore.get(),- ]);+ stubAssets(uploadingAssets.map((asset) => asset.id));for (const [uploadingAssetContainer,@@ -267,6 +243,32 @@ export const AssetsProvider = ({}};+ const uploadingAssetsMap = new Map();+ for (const asset of uploadingAssets) {+ uploadingAssetsMap.set(asset.id, asset);+ }+ const assetContainers: Array<AssetContainer> = [];+ const assets = useStore(assetsStore);+ for (const [assetId, asset] of assets) {+ if (deletingAssetIds.includes(assetId)) {+ continue;+ }+ const uploadingAsset = uploadingAssetsMap.get(assetId);+ if (uploadingAsset) {+ assetContainers.push({+ status: "uploading",+ asset: uploadingAsset,+ });+ continue;+ }+ if (asset) {+ assetContainers.push({+ status: "uploaded",+ asset,+ });+ }+ }+return (<Context.Provider value={{ assetContainers, handleSubmit, handleDelete }}>{children}@@ -287,16 +289,7 @@ export const useAssets = (type: AssetType) => {}const assetsByType = useMemo(() => {- // In no case we need to have access to deleting assets- // But we need them for optiistic updates, filter out here- const assetContainers: AssetContainer[] = [];-- for (const asset of assetContainersContext.assetContainers) {- if (asset.status !== "deleting") {- assetContainers.push(asset);- }- }-+ const assetContainers = assetContainersContext.assetContainers;return filterByType(assetContainers, type);}, [assetContainersContext.assetContainers, type]);diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.tsindex e197280c53..6342a79e1e 100644--- a/apps/builder/app/shared/nano-states/nano-states.ts+++ b/apps/builder/app/shared/nano-states/nano-states.ts@@ -3,7 +3,7 @@ import { atom, computed, type WritableAtom } from "nanostores";import { useStore } from "@nanostores/react";import { nanoid } from "nanoid";import type { AuthPermit } from "@webstudio-is/trpc-interface";-import type { Asset } from "@webstudio-is/asset-uploader";+import type { Asset, Assets } from "@webstudio-is/asset-uploader";import type { ItemDropTarget, Placement } from "@webstudio-is/design-system";import type {Breakpoint,@@ -25,10 +25,6 @@ import type {} from "@webstudio-is/project-build";import type { Style } from "@webstudio-is/css-data";import type { DragStartPayload } from "~/canvas/shared/use-drag-drop";-import type {- AssetContainer,- DeletingAssetContainer,-} from "~/builder/shared/assets";import { useSyncInitializeOnce } from "../hook-utils";import { shallowComputed } from "../store-utils";import { createInstancesIndex, type InstanceSelector } from "../tree-utils";@@ -290,31 +286,10 @@ export const useSetBreakpoints = (});};-export const assetContainersStore = atom<- Array<AssetContainer | DeletingAssetContainer>->([]);--export const assetsStore = computed(assetContainersStore, (assetContainers) => {- const assets = new Map<Asset["id"], Asset>();- for (const assetContainer of assetContainers) {- if (assetContainer.status === "uploaded") {- assets.set(assetContainer.asset.id, assetContainer.asset);- }- }- return assets;-});-export const assetsIndex = computed;-+export const assetsStore = atom<Assets>(new Map());export const useSetAssets = (assets: Asset[]) => {useSyncInitializeOnce(() => {- assetContainersStore.set(- assets.map((asset) => {- return {- status: "uploaded",- asset,- };- })- );+ assetsStore.set(new Map(assets.map((asset) => [asset.id, asset])));});};diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex d39c96568b..309702c074 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -11,8 +11,8 @@ import {stylesStore,styleSourcesStore,styleSourceSelectionsStore,+ assetsStore,selectedPageIdStore,- assetContainersStore,selectedInstanceSelectorStore,selectedInstanceBrowserStyleStore,selectedInstanceIntanceToTagStore,@@ -60,8 +60,8 @@ export const registerContainers = () => {store.register("styleSourceSelections", styleSourceSelectionsStore);store.register("props", propsStore);// synchronize whole states+ clientStores.set("assets", assetsStore);clientStores.set("selectedPageId", selectedPageIdStore);- clientStores.set("assetContainers", assetContainersStore);clientStores.set("selectedInstanceSelector", selectedInstanceSelectorStore);clientStores.set("selectedInstanceBrowserStyle",diff --git a/packages/asset-uploader/src/schema.ts b/packages/asset-uploader/src/schema.tsindex 7afef4bd63..a11860f2f7 100644--- a/packages/asset-uploader/src/schema.ts+++ b/packages/asset-uploader/src/schema.ts@@ -38,8 +38,10 @@ export const FsEnv = z.object({export const Location = z.union([z.literal("FS"), z.literal("REMOTE")]);export type Location = z.infer<typeof Location>;+const AssetId = z.string();+const BaseAsset = z.object({- id: z.string(),+ id: AssetId,projectId: z.string(),format: z.string(),size: z.number(),@@ -67,3 +69,8 @@ export const Asset = z.union([FontAsset, ImageAsset]);export type Asset = z.infer<typeof Asset>;export const idsFormDataFieldName = "ids";++// undefined is necessary to represent uploading state+// to be able to upload data while preserving order+export const Assets = z.map(AssetId, z.union([z.undefined(), Asset]));+export type Assets = z.infer<typeof Assets>;diff --git a/packages/react-sdk/src/context.tsx b/packages/react-sdk/src/context.tsxindex b4c43fc9ad..29af41684e 100644--- a/packages/react-sdk/src/context.tsx+++ b/packages/react-sdk/src/context.tsx@@ -1,6 +1,7 @@import { type ReadableAtom, atom } from "nanostores";import { createContext } from "react";-import type { Assets, Pages, PropsByInstanceId } from "./props";+import type { Assets } from "@webstudio-is/asset-uploader";+import type { Pages, PropsByInstanceId } from "./props";export const ReactSdkContext = createContext<{propsByInstanceIdStore: ReadableAtom<PropsByInstanceId>;diff --git a/packages/react-sdk/src/css/global-rules.ts b/packages/react-sdk/src/css/global-rules.tsindex 0082e5c300..26bc86212e 100644--- a/packages/react-sdk/src/css/global-rules.ts+++ b/packages/react-sdk/src/css/global-rules.ts@@ -1,5 +1,5 @@import type { CssEngine } from "@webstudio-is/css-engine";-import type { Asset, FontAsset } from "@webstudio-is/asset-uploader";+import type { Assets, FontAsset } from "@webstudio-is/asset-uploader";import {type FontFormat,FONT_FORMATS,@@ -8,7 +8,7 @@ import {export const addGlobalRules = (engine: CssEngine,- { assets }: { assets: Map<Asset["id"], Asset> }+ { assets }: { assets: Assets }) => {// @todo we need to figure out all global resets while keeping// the engine aware of all of them.@@ -17,7 +17,7 @@ export const addGlobalRules = (const fontAssets: Array<FontAsset> = [];for (const asset of assets.values()) {- if (FONT_FORMATS.has(asset.format as FontFormat)) {+ if (asset && FONT_FORMATS.has(asset.format as FontFormat)) {fontAssets.push(asset as FontAsset);}}diff --git a/packages/react-sdk/src/props.ts b/packages/react-sdk/src/props.tsindex 9b82bdf137..3c8ed58908 100644--- a/packages/react-sdk/src/props.ts+++ b/packages/react-sdk/src/props.ts@@ -2,13 +2,11 @@ import { useContext, useMemo } from "react";import { computed } from "nanostores";import { useStore } from "@nanostores/react";import type { Instance, Page, Prop, Props } from "@webstudio-is/project-build";-import type { Asset } from "@webstudio-is/asset-uploader";import { ReactSdkContext } from "./context";import { idAttribute } from "./tree/webstudio-component";export type PropsByInstanceId = Map<Instance["id"], Prop[]>;-export type Assets = Map<Asset["id"], Asset>;export type Pages = Map<Page["id"], Page>;export const getPropsByInstanceId = (props: Props) => {diff --git a/packages/react-sdk/src/tree/create-elements-tree.tsx b/packages/react-sdk/src/tree/create-elements-tree.tsxindex 52254ca0ef..88162e2e9e 100644--- a/packages/react-sdk/src/tree/create-elements-tree.tsx+++ b/packages/react-sdk/src/tree/create-elements-tree.tsx@@ -1,10 +1,11 @@import { type ComponentProps, Fragment } from "react";import type { ReadableAtom } from "nanostores";import { Scripts, ScrollRestoration } from "@remix-run/react";+import type { Assets } from "@webstudio-is/asset-uploader";import type { Instance } from "@webstudio-is/project-build";import type { GetComponent } from "../components/components-utils";import { ReactSdkContext } from "../context";-import type { Assets, Pages, PropsByInstanceId } from "../props";+import type { Pages, PropsByInstanceId } from "../props";import type { WebstudioComponent } from "./webstudio-component";import { SessionStoragePolyfill } from "./session-storage-polyfill";