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 shallowComputed nanostores utility (#827)
Bogdan Chadkin1da64faf4f1b
diff --git a/apps/designer/app/canvas/features/wrapper-component/selected-instance-connector.ts b/apps/designer/app/canvas/features/wrapper-component/selected-instance-connector.tsindex 8df9609a23..588f40f690 100644--- a/apps/designer/app/canvas/features/wrapper-component/selected-instance-connector.ts+++ b/apps/designer/app/canvas/features/wrapper-component/selected-instance-connector.ts@@ -1,5 +1,5 @@import { useEffect } from "react";-import type { Instance, UserProp } from "@webstudio-is/react-sdk";+import type { Instance, Styles, UserProp } from "@webstudio-is/react-sdk";import { getBrowserStyle } from "@webstudio-is/react-sdk";import { publish, subscribe, subscribeAll } from "~/shared/pubsub";import {@@ -47,12 +47,12 @@ const hideOutline = () => {export const SelectedInstanceConnector = ({instanceElementRef,instance,- instanceStylesKey,+ instanceStyles,instanceProps,}: {instanceElementRef: { current: undefined | HTMLElement };instance: Instance;- instanceStylesKey: unknown;+ instanceStyles: Styles;instanceProps: undefined | UserProp[];}) => {useEffect(() => {@@ -144,7 +144,7 @@ export const SelectedInstanceConnector = ({};// instance props may change dom element- }, [instanceElementRef, instance, instanceStylesKey, instanceProps]);+ }, [instanceElementRef, instance, instanceStyles, instanceProps]);return null;};diff --git a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsxindex b0a2d25e7a..2532650512 100644--- a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx+++ b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx@@ -1,6 +1,6 @@-import { type MouseEvent, type FormEvent, useMemo } from "react";-import { useRef } from "react";-import { Suspense, lazy, useCallback } from "react";+import type { MouseEvent, FormEvent } from "react";+import { Suspense, lazy, useCallback, useMemo, useRef } from "react";+import { useStore } from "@nanostores/react";import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";import {type Instance,@@ -11,7 +11,11 @@ import {idAttribute,useAllUserProps,} from "@webstudio-is/react-sdk";-import { useTextEditingInstanceId } from "~/shared/nano-states";+import { shallowComputed } from "~/shared/store-utils";+import {+ stylesIndexStore,+ useTextEditingInstanceId,+} from "~/shared/nano-states";import { useSelectedInstance } from "~/canvas/shared/nano-states";import { useCssRules } from "~/canvas/shared/styles";import { publish } from "~/shared/pubsub";@@ -53,7 +57,16 @@ export const WrapperComponentDev = ({children,onChangeChildren,}: WrapperComponentDevProps) => {- const instanceStylesKey = useCssRules({ instanceId: instance.id });+ const instanceId = instance.id;++ const instanceStylesStore = useMemo(() => {+ return shallowComputed(+ [stylesIndexStore],+ (stylesIndex) => stylesIndex.stylesByInstanceId.get(instanceId) ?? []+ );+ }, [instanceId]);+ const instanceStyles = useStore(instanceStylesStore);+ useCssRules({ instanceId: instance.id, instanceStyles });const [editingInstanceId, setTextEditingInstanceId] =useTextEditingInstanceId();@@ -110,7 +123,7 @@ export const WrapperComponentDev = ({<SelectedInstanceConnectorinstanceElementRef={instanceElementRef}instance={instance}- instanceStylesKey={instanceStylesKey}+ instanceStyles={instanceStyles}instanceProps={instanceProps}/>)}diff --git a/apps/designer/app/canvas/shared/styles.ts b/apps/designer/app/canvas/shared/styles.tsindex db41e418d1..12e9aa86fc 100644--- a/apps/designer/app/canvas/shared/styles.ts+++ b/apps/designer/app/canvas/shared/styles.ts@@ -1,14 +1,13 @@-import { useEffect, useMemo } from "react";+import { useEffect } from "react";import { useSubscribe } from "~/shared/pubsub";import { addGlobalRules, getPresetStyleRules } from "@webstudio-is/project";-import { useSelectedInstance } from "./nano-states";import {useBreakpoints,useDesignTokens,usePresetStyles,- useStyles,} from "~/shared/nano-states";import {+ type Styles,getComponentMeta,getComponentNames,idAttribute,@@ -30,6 +29,7 @@ import {import { useIsomorphicLayoutEffect } from "react-use";import type { Asset } from "@webstudio-is/asset-uploader";import { tokensToStyle } from "~/designer/shared/design-tokens-manager";+import { useSelectedInstance } from "./nano-states";const cssEngine = createCssEngine({ name: "user-styles" });@@ -175,18 +175,15 @@ const getRule = (id: string, breakpoint?: string) => {return wrappedRulesMap.get(key);};-export const useCssRules = ({ instanceId }: { instanceId: string }) => {- const [styles] = useStyles();+export const useCssRules = ({+ instanceId,+ instanceStyles,+}: {+ instanceId: string;+ instanceStyles: Styles;+}) => {const [breakpoints] = useBreakpoints();- const [instanceStylesKey, instanceStyles] = useMemo(() => {- const instanceStyles = styles.filter(- (item) => item.instanceId === instanceId- );- const key = JSON.stringify(instanceStyles);- return [key, instanceStyles];- }, [styles, instanceId]);-useIsomorphicLayoutEffect(() => {const stylePerBreakpoint = new Map<string, Style>();@@ -221,11 +218,7 @@ export const useCssRules = ({ instanceId }: { instanceId: string }) => {}}cssEngine.render();- // run effect only when serialized instanceStyles changed- // to avoid rerendering on other instances change- }, [instanceId, instanceStylesKey, breakpoints]);-- return instanceStylesKey;+ }, [instanceId, instanceStyles, breakpoints]);};const toVarNamespace = (id: string, property: string) => {diff --git a/apps/designer/app/shared/nano-states/nano-states.ts b/apps/designer/app/shared/nano-states/nano-states.tsindex d96098f929..b76b6c5d95 100644--- a/apps/designer/app/shared/nano-states/nano-states.ts+++ b/apps/designer/app/shared/nano-states/nano-states.ts@@ -1,6 +1,6 @@-import { atom, type WritableAtom } from "nanostores";+import { atom, computed, type WritableAtom } from "nanostores";import { useStore } from "@nanostores/react";-import type { Instance, PresetStyles, Styles } from "@webstudio-is/react-sdk";+import { Instance, PresetStyles, Styles } from "@webstudio-is/react-sdk";import type {DropTargetChangePayload,DragStartPayload,@@ -31,6 +31,31 @@ export const useSetPresetStyles = (presetStyles: PresetStyles) => {};export const stylesContainer = atom<Styles>([]);+/**+ * Indexed styles data is recomputed on every styles update+ * Compumer should use shallow-equal to check all items in the list+ * are the same to avoid unnecessary rerenders+ *+ * Potential optimization can be maintaining the index as separate state+ * though will require to move away from running immer patches on array+ * of styles+ */+export const stylesIndexStore = computed(stylesContainer, (styles) => {+ const stylesByInstanceId = new Map<Instance["id"], Styles>();+ for (const stylesItem of styles) {+ const { instanceId } = stylesItem;+ let instanceStyles = stylesByInstanceId.get(instanceId);+ if (instanceStyles === undefined) {+ instanceStyles = [];+ stylesByInstanceId.set(instanceId, instanceStyles);+ }+ instanceStyles.push(stylesItem);+ }+ return {+ stylesByInstanceId,+ };+});+export const useStyles = () => useValue(stylesContainer);export const useSetStyles = (styles: Styles) => {useSyncInitializeOnce(() => {diff --git a/apps/designer/app/shared/store-utils.test.ts b/apps/designer/app/shared/store-utils.test.tsnew file mode 100644index 0000000000..55d3435163--- /dev/null+++ b/apps/designer/app/shared/store-utils.test.ts@@ -0,0 +1,53 @@+import { test, expect } from "@jest/globals";+import { type ReadableAtom, atom } from "nanostores";+import { shallowComputed } from "./store-utils";++type StoreValue<Store extends ReadableAtom> = Readonly<+ ReturnType<Store["get"]>+>;++test("shallowComputed provides same reference when object/array values not changed", () => {+ const list = atom([+ { type: "a", value: 0 },+ { type: "b", value: 1 },+ { type: "a", value: 2 },+ ]);++ const filtered = shallowComputed([list], (list) => {+ return list.filter((item) => item.type === "a");+ });++ let prevList: StoreValue<typeof filtered> = filtered.get();+ let computedList: StoreValue<typeof filtered> = filtered.get();+ filtered.subscribe((list) => {+ computedList = list;+ });++ expect(prevList).toBe(computedList);++ // preserve the reference of array with same items+ list.set([...list.get(), { type: "b", value: 3 }]);+ expect(prevList).toBe(computedList);++ // update reference when items added+ list.set([...list.get(), { type: "a", value: 4 }]);+ expect(prevList).not.toBe(computedList);+ expect(computedList).toEqual([+ { type: "a", value: 0 },+ { type: "a", value: 2 },+ { type: "a", value: 4 },+ ]);+ prevList = computedList;++ list.set([...list.get(), { type: "b", value: 5 }]);+ expect(prevList).toBe(computedList);++ // update reference when items added+ list.set(list.get().filter((item) => item.value !== 2));+ expect(prevList).not.toBe(computedList);+ expect(computedList).toEqual([+ { type: "a", value: 0 },+ { type: "a", value: 4 },+ ]);+ prevList = computedList;+});diff --git a/apps/designer/app/shared/store-utils.ts b/apps/designer/app/shared/store-utils.tsnew file mode 100644index 0000000000..61af20f03c--- /dev/null+++ b/apps/designer/app/shared/store-utils.ts@@ -0,0 +1,50 @@+import { type AnyStore, type StoreValue, computed } from "nanostores";+// eslint-disable-next-line @typescript-eslint/ban-ts-comment+// @ts-ignore soon will have definitions+import { shallowEqualArrays, shallowEqualObjects } from "shallow-equal";++type Comparable<Item> = Record<string, Item> | Item[] | null | undefined;++type ValidArrayValue<Item> = Item[] | null | undefined;++type ValidObjectValue<Item> = Record<string, Item> | null | undefined;++const shallowEqual = <Item extends Comparable<Item>>(+ a: Item,+ b: Item+): boolean => {+ if (Array.isArray(a) || Array.isArray(b)) {+ return shallowEqualArrays(+ a as ValidArrayValue<Item>,+ b as ValidArrayValue<Item>+ );+ }++ return shallowEqualObjects(+ a as ValidObjectValue<Item>,+ b as ValidObjectValue<Item>+ );+};++// https://github.com/nanostores/nanostores/blob/0d27b0d18d0f471ca0ac5439137d3dac71d01f08/computed/index.d.ts++type StoreValues<Stores extends AnyStore[]> = {+ [Index in keyof Stores]: StoreValue<Stores[Index]>;+};++export const shallowComputed = <Value, OriginStores extends AnyStore[]>(+ stores: [...OriginStores],+ cb: (...values: StoreValues<OriginStores>) => Value+) => {+ let prevComputed: Value;+ return computed<Value, OriginStores>(stores, (...values) => {+ const nextComputed = cb(...values);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ if (shallowEqual<any>(prevComputed, nextComputed)) {+ return prevComputed;+ } else {+ prevComputed = nextComputed;+ return nextComputed;+ }+ });+};diff --git a/apps/designer/package.json b/apps/designer/package.jsonindex 96072b668a..379fd14553 100644--- a/apps/designer/package.json+++ b/apps/designer/package.json@@ -86,6 +86,7 @@"remix-auth-github": "^1.1.1","remix-auth-google": "^1.1.0","remix-utils": "^4.1.0",+ "shallow-equal": "^1.2.1","slugify": "^1.6.5","use-debounce": "^9.0.2","uuid": "^9.0.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7253bce86e..d4a336a1ff 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -144,6 +144,7 @@ importers:remix-auth-github: ^1.1.1remix-auth-google: ^1.1.0remix-utils: ^4.1.0+ shallow-equal: ^1.2.1slugify: ^1.6.5typescript: 4.7.4use-debounce: ^9.0.2@@ -220,6 +221,7 @@ importers:remix-auth-github: 1.1.1_xwzgzw5pppjvklzjkjpfcyhkreremix-auth-google: 1.1.0_vfjkmpgf2kafw3snxw2uyzxrmaremix-utils: 4.1.0_p7gsab2odbjrdioff2iqwg35mm+ shallow-equal: 1.2.1slugify: 1.6.5use-debounce: [email protected]uuid: 9.0.0@@ -19924,6 +19926,10 @@ packages:dependencies:kind-of: 6.0.3+ /shallow-equal/1.2.1:+ resolution: {integrity: sha512-S4vJDjHHMBaiZuT9NPb616CSmLf618jawtv3sufLl6ivK8WocjAo58cXwbRV1cgqxH0Qbv+iUt6m05eqEa2IRA==}+ dev: false+/sharp/0.30.7:resolution: {integrity: sha512-G+MY2YW33jgflKPTXXptVO28HvNOo9G3j0MybYAHeEmby+QuD2U98dT6ueht9cv/XDqZspSpIhoSW+BAKJ7Hig==}engines: {node: '>=12.13.0'}