Skip to content

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.

Use synchronized store for assets (#936)

Bogdan Chadkin2b404f28646c
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsx
index e9436b7828..2aedced6cf 100644
--- a/apps/designer/app/canvas/canvas.tsx
+++ b/apps/designer/app/canvas/canvas.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useMemo } from "react";
import { computed } from "nanostores";
import store from "immerhin";
import type { CanvasData } from "@webstudio-is/project";
@@ -11,7 +11,7 @@ import {
type OnChangeChildren,
setPropsByInstanceIdStore,
} from "@webstudio-is/react-sdk";
-import { publish, useSubscribe } from "~/shared/pubsub";
+import { publish } from "~/shared/pubsub";
import { registerContainers, useCanvasStore } from "~/shared/sync";
import { useShortcuts } from "./shared/use-shortcuts";
import {
@@ -36,12 +36,12 @@ import {
useSetStyleSourceSelections,
useSubscribeScrollState,
useIsPreviewMode,
+ useSetAssets,
} from "~/shared/nano-states";
import { usePublishScrollState } from "./shared/use-publish-scroll-state";
import { useDragAndDrop } from "./shared/use-drag-drop";
import { utils } from "@webstudio-is/project";
import { useSubscribeDesignerReady } from "./shared/use-designer-ready";
-import type { Asset } from "@webstudio-is/asset-uploader";
import { useCopyPasteInstance } from "~/shared/copy-paste";
import { customComponents } from "./custom-components";
import { useHoveredInstanceConnector } from "./hovered-instance-connector";
@@ -85,12 +85,6 @@ const useElementsTree = () => {
}, [rootInstance, onChangeChildren]);
};
-const useAssets = (initialAssets: Array<Asset>) => {
- const [assets, setAssets] = useState(initialAssets);
- useSubscribe("updateAssets", setAssets);
- return assets;
-};
-
const DesignMode = () => {
useManageDesignModeStyles();
useInsertInstance();
@@ -126,7 +120,7 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
throw new Error("Tree is null");
}
const isDesignerReady = useSubscribeDesignerReady();
- const assets = useAssets(data.assets);
+ useSetAssets(data.assets);
useSetBreakpoints(data.build.breakpoints);
useSetProps(data.tree.props);
// inject props store to sdk
@@ -155,7 +149,7 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
if (isPreviewMode || isDesignerReady === false) {
return (
<>
- <GlobalStyles assets={assets} />
+ <GlobalStyles />
{elements}
</>
);
@@ -163,7 +157,7 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
return (
<>
- <GlobalStyles assets={assets} />
+ <GlobalStyles />
<DesignMode />
{elements}
</>
diff --git a/apps/designer/app/canvas/shared/styles.ts b/apps/designer/app/canvas/shared/styles.ts
index 6a135394d8..60353e7b10 100644
--- a/apps/designer/app/canvas/shared/styles.ts
+++ b/apps/designer/app/canvas/shared/styles.ts
@@ -1,7 +1,12 @@
import { useEffect } from "react";
-import { useSubscribe } from "~/shared/pubsub";
+import { useIsomorphicLayoutEffect } from "react-use";
+import { useStore } from "@nanostores/react";
import { addGlobalRules } from "@webstudio-is/project";
-import { selectedInstanceIdStore, useBreakpoints } from "~/shared/nano-states";
+import {
+ assetsStore,
+ selectedInstanceIdStore,
+ useBreakpoints,
+} from "~/shared/nano-states";
import type { Styles } from "@webstudio-is/project-build";
import {
getComponentMeta,
@@ -22,8 +27,7 @@ import {
type StyleRule,
type PlaintextRule,
} from "@webstudio-is/css-engine";
-import { useIsomorphicLayoutEffect } from "react-use";
-import type { Asset } from "@webstudio-is/asset-uploader";
+import { useSubscribe } from "~/shared/pubsub";
const cssEngine = createCssEngine({ name: "user-styles" });
@@ -62,8 +66,9 @@ const fontsAndDefaultsCssEngine = createCssEngine({
});
const presetStylesEngine = createCssEngine({ name: "presetStyles" });
-export const GlobalStyles = ({ assets }: { assets: Array<Asset> }) => {
+export const GlobalStyles = () => {
const [breakpoints] = useBreakpoints();
+ const assets = useStore(assetsStore);
useIsomorphicLayoutEffect(() => {
for (const breakpoint of breakpoints) {
diff --git a/apps/designer/app/designer/designer.tsx b/apps/designer/app/designer/designer.tsx
index d51966ce40..6dadecdc3d 100644
--- a/apps/designer/app/designer/designer.tsx
+++ b/apps/designer/app/designer/designer.tsx
@@ -34,7 +34,7 @@ import { useClientSettings } from "./shared/client-settings";
import { Navigator } from "./features/sidebar-left";
import { getBuildUrl } from "~/shared/router-utils";
import { useCopyPasteInstance } from "~/shared/copy-paste";
-import { AssetsProvider, usePublishAssets } from "./shared/assets";
+import { AssetsProvider } from "./shared/assets";
registerContainers();
export const links = () => {
@@ -260,7 +260,6 @@ export const Designer = ({
const [publish, publishRef] = usePublish();
useDesignerStore(publish);
useSyncServer({ buildId, treeId, projectId: project.id, authToken });
- usePublishAssets(publish);
const [isPreviewMode] = useIsPreviewMode();
usePublishShortcuts(publish);
const onRefReadCanvasWidth = useUpdateCanvasWidth();
diff --git a/apps/designer/app/designer/shared/assets/use-assets.tsx b/apps/designer/app/designer/shared/assets/use-assets.tsx
index 21ab6fbee8..9bf40095a2 100644
--- a/apps/designer/app/designer/shared/assets/use-assets.tsx
+++ b/apps/designer/app/designer/shared/assets/use-assets.tsx
@@ -6,6 +6,9 @@ import {
type ReactNode,
useRef,
} from "react";
+import { useStore } from "@nanostores/react";
+import warnOnce from "warn-once";
+import { useFetcher } from "@remix-run/react";
import {
AssetType,
idsFormDataFieldName,
@@ -14,9 +17,10 @@ import {
type Asset,
} from "@webstudio-is/asset-uploader";
import { toast } from "@webstudio-is/design-system";
-import { restAssetsPath } from "~/shared/router-utils";
-import { useAssetsContainer, useProject } from "../nano-states";
import { sanitizeS3Key } from "@webstudio-is/asset-uploader";
+import { assetContainersStore } from "~/shared/nano-states";
+import { restAssetsPath } from "~/shared/router-utils";
+import { useProject } from "../nano-states";
import type {
AssetContainer,
DeletingAssetContainer,
@@ -30,38 +34,8 @@ import {
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-asset-containers";
-declare module "~/shared/pubsub" {
- export interface PubsubMap {
- updateAssets: Array<Asset>;
- }
-}
-
-export const usePublishAssets = (publish: Publish) => {
- const [assetContainers] = useAssetsContainer();
- useEffect(() => {
- publish({
- type: "updateAssets",
- payload: assetContainers
- .filter((assetContainer) => assetContainer.status === "uploaded")
- .map((assetContainer) => {
- // This check is only to fix that ts can't detect type based on the filter above
- if (assetContainer.status !== "uploaded") {
- throw new Error(
- `Impossible, asset must have status "uploaded" see filter above`
- );
- }
-
- return assetContainer.asset;
- }),
- });
- }, [assetContainers, publish]);
-};
-
export type UploadData = FetcherData<ActionData>;
const toUploadingAssetsAndFormData = (
@@ -116,7 +90,7 @@ const toUploadingAssetsAndFormData = (
const maxSize = toBytes(MAX_UPLOAD_SIZE);
-const getFilesFromInput = (type: AssetType, input: HTMLInputElement) => {
+const getFilesFromInput = (_type: AssetType, input: HTMLInputElement) => {
const files = Array.from(input?.files ?? []);
const exceedSizeFiles = files.filter((file) => file.size > maxSize);
@@ -140,7 +114,7 @@ const Context = createContext<AssetsContext | undefined>(undefined);
export const AssetsProvider = ({ children }: { children: ReactNode }) => {
const [project] = useProject();
- const [assetContainers, setAssetContainers] = useAssetsContainer();
+ const assetContainers = useStore(assetContainersStore);
const { submit: load, data: serverAssets } = useFetcher<Asset[]>();
const submit = usePersistentFetcher();
const assetContainersRef = useRef(assetContainers);
@@ -166,10 +140,10 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {
);
if (nextAssetContainers !== assetContainers) {
- setAssetContainers(nextAssetContainers);
+ assetContainersStore.set(nextAssetContainers);
}
}
- }, [serverAssets, assetContainers, setAssetContainers]);
+ }, [serverAssets, assetContainers]);
const handleDeleteAfterSubmit = (data: UploadData) => {
// We need to remove assets only at updateStateAssets.
@@ -194,7 +168,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {
return assetContainer;
});
- setAssetContainers(nextAssetContainers);
+ assetContainersStore.set(nextAssetContainers);
return toastUnknownFieldErrors(normalizeErrors(data.errors), []);
}
@@ -209,7 +183,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {
if (data.status === "error" || data.errors !== undefined) {
// We don't know what's wrong, remove uploading asset and wait for the load to fix it
- setAssetContainers(
+ assetContainersStore.set(
assetContainers.filter(
(assetContainer) =>
assetContainer.status !== "uploading" ||
@@ -235,7 +209,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {
toast.error("Could not upload an asset");
// remove uploading asset and wait for the load to fix it
- setAssetContainers(
+ assetContainersStore.set(
assetContainers.filter(
(assetContainer) =>
assetContainer.status !== "uploading" ||
@@ -245,7 +219,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {
return;
}
- setAssetContainers(
+ assetContainersStore.set(
assetContainers.map((assetContainer) => {
if (
assetContainer.status === "uploading" &&
@@ -289,7 +263,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {
}
}
- setAssetContainers(nextAssetContainers);
+ assetContainersStore.set(nextAssetContainers);
submit<UploadData>(
formData,
@@ -306,7 +280,7 @@ export const AssetsProvider = ({ children }: { children: ReactNode }) => {
);
const assets = assetContainersRef.current;
- setAssetContainers([
+ assetContainersStore.set([
...uploadingAssetsAndFormData.map(([previewAsset]) => previewAsset),
...assets,
]);
diff --git a/apps/designer/app/shared/nano-states/nano-states.ts b/apps/designer/app/shared/nano-states/nano-states.ts
index 8c2a69584a..73424b6df3 100644
--- a/apps/designer/app/shared/nano-states/nano-states.ts
+++ b/apps/designer/app/shared/nano-states/nano-states.ts
@@ -1,6 +1,7 @@
import { useMemo } from "react";
import { atom, computed, type WritableAtom } from "nanostores";
import { useStore } from "@nanostores/react";
+import type { Asset } from "@webstudio-is/asset-uploader";
import type {
Instance,
Props,
@@ -14,6 +15,10 @@ import type {
DropTargetChangePayload,
DragStartPayload,
} from "~/canvas/shared/use-drag-drop";
+import type {
+ AssetContainer,
+ DeletingAssetContainer,
+} from "~/designer/shared/assets";
import { useSyncInitializeOnce } from "../hook-utils";
import { shallowComputed } from "../store-utils";
@@ -204,6 +209,33 @@ export const useSetBreakpoints = (breakpoints: Breakpoint[]) => {
});
};
+export const assetContainersStore = atom<
+ Array<AssetContainer | DeletingAssetContainer>
+>([]);
+
+export const assetsStore = computed(assetContainersStore, (assetContainers) => {
+ const assets: Asset[] = [];
+ for (const assetContainer of assetContainers) {
+ if (assetContainer.status === "uploaded") {
+ assets.push(assetContainer.asset);
+ }
+ }
+ return assets;
+});
+
+export const useSetAssets = (assets: Asset[]) => {
+ useSyncInitializeOnce(() => {
+ assetContainersStore.set(
+ assets.map((asset) => {
+ return {
+ status: "uploaded",
+ asset,
+ };
+ })
+ );
+ });
+};
+
export const selectedInstanceIdStore = atom<undefined | Instance["id"]>(
undefined
);
diff --git a/apps/designer/app/shared/sync/sync-stores.ts b/apps/designer/app/shared/sync/sync-stores.ts
index 64859e3a12..c077ddef3d 100644
--- a/apps/designer/app/shared/sync/sync-stores.ts
+++ b/apps/designer/app/shared/sync/sync-stores.ts
@@ -9,6 +9,7 @@ import {
stylesStore,
styleSourcesStore,
styleSourceSelectionsStore,
+ assetContainersStore,
selectedInstanceIdStore,
selectedInstanceBrowserStyleStore,
hoveredInstanceIdStore,
@@ -49,6 +50,7 @@ export const registerContainers = () => {
store.register("styleSourceSelections", styleSourceSelectionsStore);
store.register("props", propsStore);
// synchronize whole states
+ clientStores.set("assetContainers", assetContainersStore);
clientStores.set("selectedInstanceId", selectedInstanceIdStore);
clientStores.set(
"selectedInstanceBrowserStyle",
diff --git a/packages/project/src/db/styles.ts b/packages/project/src/db/styles.ts
index 3510721119..3d056cdda6 100644
--- a/packages/project/src/db/styles.ts
+++ b/packages/project/src/db/styles.ts
@@ -136,7 +136,7 @@ export const patch = async (
await prisma.build.update({
data: {
- styles: JSON.stringify(patchedStyles),
+ styles: serializeStyles(patchedStyles),
},
where: {
id_projectId: { projectId, id: buildId },