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
refactor: split instances slice into separate utility (#2521)
Bogdan Chadkin78d9ea912d1c
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 97e6ad1b35..47b3f5aa81 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -2,7 +2,6 @@ import { shallowEqual } from "shallow-equal";import { nanoid } from "nanoid";import { z } from "zod";import { toast } from "@webstudio-is/design-system";-import { findTreeInstanceIds } from "@webstudio-is/sdk";import {Asset,Breakpoint,@@ -12,13 +11,11 @@ import {StyleDecl,StyleSource,StyleSourceSelection,- StyleSourceSelections,} from "@webstudio-is/sdk";import {encodeDataSourceVariable,validateExpression,decodeDataSourceVariable,- computeExpressionsDependencies,} from "@webstudio-is/react-sdk";import {propsStore,@@ -33,7 +30,6 @@ import {projectStore,registeredComponentMetasStore,dataSourcesStore,- dataSourcesLogicStore,} from "../nano-states";import {type InstanceSelector,@@ -50,9 +46,9 @@ import {computeInstancesConstraints,deleteInstance,findClosestDroppableTarget,+ getInstancesSlice,isInstanceDetachable,} from "../instance-utils";-import { getMapValuesBy, getMapValuesByKeysSet } from "../array-utils";import { serverSyncStore } from "../sync";const version = "@webstudio/instance/v0.1";@@ -71,114 +67,6 @@ const InstanceData = z.object({type InstanceData = z.infer<typeof InstanceData>;-const findTreeStyleSourceIds = (- styleSourceSelections: StyleSourceSelections,- treeInstanceIds: Set<Instance["id"]>-) => {- const treeStyleSourceIds = new Set<StyleSource["id"]>();- for (const { instanceId, values } of styleSourceSelections.values()) {- // skip selections outside of tree- if (treeInstanceIds.has(instanceId) === false) {- continue;- }- for (const styleSourceId of values) {- treeStyleSourceIds.add(styleSourceId);- }- }- return treeStyleSourceIds;-};--const getAssetsUsedInStyle = (- style: StyleDecl[],- foundAssetsIds = new Set<Asset["id"]>()-) => {- const fontFamilies = new Set<string>();-- const processValues = (values: StyleDecl["value"][]) => {- for (const value of values) {- if (value.type === "fontFamily") {- for (const fontFamily of value.value) {- fontFamilies.add(fontFamily);- }- continue;- }- if (value.type === "image") {- if (value.value.type === "asset") {- foundAssetsIds.add(value.value.value);- }- continue;- }- if (value.type === "var") {- processValues(value.fallbacks);- continue;- }- if (value.type === "tuple" || value.type === "layers") {- processValues(value.value);- continue;- }- if (- value.type === "unit" ||- value.type === "keyword" ||- value.type === "unparsed" ||- value.type === "invalid" ||- value.type === "unset" ||- value.type === "rgb"- ) {- continue;- }- value satisfies never;- }- };-- processValues(style.map(({ value }) => value));-- for (const asset of assetsStore.get().values()) {- if (asset?.type === "font" && fontFamilies.has(asset.meta.family)) {- foundAssetsIds.add(asset.id);- }- }-- return foundAssetsIds;-};--const getAssetsUsedInProps = (props: Prop[], foundAssetsIds = new Set()) => {- for (const prop of props) {- if (prop.type === "asset") {- foundAssetsIds.add(prop.value);- continue;- }- if (- prop.type === "number" ||- prop.type === "string" ||- prop.type === "boolean" ||- prop.type === "page" ||- prop.type === "string[]" ||- prop.type === "dataSource" ||- prop.type === "action"- ) {- continue;- }- prop satisfies never;- }- return foundAssetsIds;-};--const getPropTypeAndValue = (value: unknown) => {- if (typeof value === "boolean") {- return { type: "boolean", value } as const;- }- if (typeof value === "number") {- return { type: "number", value } as const;- }- if (typeof value === "string") {- return { type: "string", value } as const;- }- if (Array.isArray(value)) {- return { type: "string[]", value } as const;- }- throw Error(`Unexpected prop value ${value}`);-};-const getTreeData = (targetInstanceSelector: InstanceSelector) => {if (isInstanceDetachable(targetInstanceSelector) === false) {toast.error(@@ -193,165 +81,10 @@ const getTreeData = (targetInstanceSelector: InstanceSelector) => {}const [targetInstanceId] = targetInstanceSelector;- const instances = instancesStore.get();- const treeInstanceIds = findTreeInstanceIds(instances, targetInstanceId);- const styleSourceSelections = styleSourceSelectionsStore.get();- const treeStyleSourceIds = findTreeStyleSourceIds(- styleSourceSelections,- treeInstanceIds- );-- // first item is guaranteed root of copied tree- const treeInstances = getMapValuesByKeysSet(instances, treeInstanceIds);-- const dataSources = dataSourcesStore.get();- const expressions = new Map<string, string>();- for (const dataSource of dataSources.values()) {- if (dataSource.type === "expression") {- expressions.set(encodeDataSourceVariable(dataSource.id), dataSource.code);- }- }- const dependencies = computeExpressionsDependencies(expressions);-- const treeDataSources = getMapValuesBy(dataSources, (dataSource) => {- if (dataSource.type === "expression") {- const expressionDeps = dependencies.get(- encodeDataSourceVariable(dataSource.id)- );- if (expressionDeps) {- for (const dependency of expressionDeps) {- const dataSourceId = decodeDataSourceVariable(dependency);- if (dataSourceId === undefined) {- continue;- }- const dataSource = dataSources.get(dataSourceId);- if (dataSource === undefined) {- continue;- }- if (- dataSource.scopeInstanceId === undefined ||- treeInstanceIds.has(dataSource.scopeInstanceId) === false- ) {- return false;- }- }- }- }- return (- dataSource.scopeInstanceId !== undefined &&- treeInstanceIds.has(dataSource.scopeInstanceId)- );- });- const treeDataSourceIds = new Set(- treeDataSources.map((dataSource) => dataSource.id)- );-- const dataSourcesLogic = dataSourcesLogicStore.get();- const treeProps = getMapValuesBy(propsStore.get(), (prop) =>- treeInstanceIds.has(prop.instanceId)- ).map((prop) => {- if (prop.type === "dataSource") {- const dataSourceId = prop.value;- // copy data source if scoped to one of copied instances- if (treeDataSourceIds.has(dataSourceId)) {- return prop;- }- // convert data source prop to typed prop- // when data source is not scoped to one of copied instances- const value = dataSourcesLogic.get(dataSourceId);- return {- id: prop.id,- instanceId: prop.instanceId,- name: prop.name,- ...getPropTypeAndValue(value),- } satisfies Prop;- }- if (prop.type === "action") {- return {- ...prop,- value: prop.value.flatMap((value) => {- if (value.type !== "execute") {- return [value];- }- let shouldKeepAction = true;- validateExpression(value.code, {- effectful: true,- transformIdentifier: (identifier) => {- if (value.args.includes(identifier)) {- return identifier;- }- const id = decodeDataSourceVariable(identifier);- if (id === undefined) {- return identifier;- }- if (treeDataSourceIds.has(id) === false) {- shouldKeepAction = false;- return identifier;- }- const identifierDeps = dependencies.get(id);- if (identifierDeps) {- for (const dependency of identifierDeps) {- const id = decodeDataSourceVariable(dependency);- if (id === undefined) {- continue;- }- if (treeDataSourceIds.has(id) === false) {- shouldKeepAction = false;- return identifier;- }- }- }- return identifier;- },- });- if (shouldKeepAction) {- return [value];- }- return [];- }),- };- }- return prop;- });-- const treeStyleSourceSelections = getMapValuesByKeysSet(- styleSourceSelections,- treeInstanceIds- );-- const treeStyleSources = getMapValuesByKeysSet(- styleSourcesStore.get(),- treeStyleSourceIds- );-- const treeStyles = getMapValuesBy(stylesStore.get(), (styleDecl) =>- treeStyleSourceIds.has(styleDecl.styleSourceId)- );-- const treeBreapointIds = new Set<Breakpoint["id"]>();- for (const styleDecl of treeStyles) {- treeBreapointIds.add(styleDecl.breakpointId);- }- const treeBreapoints = getMapValuesByKeysSet(- breakpointsStore.get(),- treeBreapointIds- );-- const treeAssets = getMapValuesByKeysSet(- assetsStore.get(),- getAssetsUsedInProps(treeProps, getAssetsUsedInStyle(treeStyles))- );return {instanceSelector: targetInstanceSelector,- breakpoints: treeBreapoints,- instances: treeInstances,- styleSources: treeStyleSources,- dataSources: treeDataSources,- props: treeProps,- styleSourceSelections: treeStyleSourceSelections,- styles: treeStyles,- assets: treeAssets,+ ...getInstancesSlice(targetInstanceId),};};diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.tsindex 4bc024006e..cb9f0f76aa 100644--- a/apps/builder/app/shared/instance-utils.test.ts+++ b/apps/builder/app/shared/instance-utils.test.ts@@ -2,7 +2,15 @@ import { enableMapSet } from "immer";import { describe, test, expect } from "@jest/globals";import type { WsComponentMeta } from "@webstudio-is/react-sdk";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";-import type { Instance, Instances } from "@webstudio-is/sdk";+import type {+ Asset,+ Instance,+ Instances,+ Prop,+ StyleDecl,+ StyleDeclKey,+} from "@webstudio-is/sdk";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";import {computeInstancesConstraints,findClosestDroppableComponentIndex,@@ -11,9 +19,14 @@ import {insertTemplateData,type InsertConstraints,deleteInstance,+ getInstancesSlice,} from "./instance-utils";import {+ assetsStore,+ breakpointsStore,+ dataSourcesStore,instancesStore,+ propsStore,registeredComponentMetasStore,styleSourceSelectionsStore,styleSourcesStore,@@ -47,6 +60,20 @@ const createFakeComponentMetas = (return new Map(Object.entries(configs)) as Map<string, WsComponentMeta>;};+const getIdValuePair = <T extends { id: string }>(item: T) =>+ [item.id, item] as const;++const toMap = <T extends { id: string }>(list: T[]) =>+ new Map(list.map(getIdValuePair));++const createInstance = (+ id: Instance["id"],+ component: string,+ children: Instance["children"]+): Instance => {+ return { type: "instance", id, component, children };+};+const createInstancePair = (id: Instance["id"],component: string,@@ -55,6 +82,64 @@ const createInstancePair = (return [id, { type: "instance", id, component, children }];};+const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue | string+): StyleDecl => ({+ styleSourceId,+ breakpointId,+ property,+ value: typeof value === "string" ? { type: "unparsed", value } : value,+});++const createStyleDeclPair = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue | string+): [StyleDeclKey, StyleDecl] => [+ `${styleSourceId}:${breakpointId}:${property}:`,+ createStyleDecl(styleSourceId, breakpointId, property, value),+];++const createProp = (instanceId: string, id: string, name: string): Prop => ({+ id,+ instanceId,+ name,+ type: "string",+ value: id,+});++const createImageAsset = (id: string): Asset => {+ return {+ id,+ type: "image",+ format: "",+ name: "",+ description: "",+ projectId: "",+ createdAt: "",+ size: 0,+ meta: { width: 0, height: 0 },+ };+};++const createFontAsset = (id: string, family: string): Asset => {+ return {+ id,+ type: "font",+ format: "woff",+ name: "",+ description: "",+ projectId: "",+ createdAt: "",+ size: 0,+ meta: { style: "normal", family, variationAxes: {} },+ };+};+const emptyInsertConstraints: InsertConstraints = {requiredAncestors: new Set(),invalidAncestors: new Set(),@@ -464,3 +549,388 @@ test("prevent deleting root instance", () => {]));});++describe("get instances slice", () => {+ test("collect the instance by id and all its descendants including portal instances", () => {+ // body+ // bodyChild1+ // slot+ // slotChild+ // bodyChild2+ instancesStore.set(+ toMap([+ createInstance("body", "Body", [+ { type: "id", value: "bodyChild1" },+ { type: "id", value: "bodyChild2" },+ ]),+ createInstance("bodyChild1", "Box", [{ type: "id", value: "slot" }]),+ createInstance("slot", "Slot", [{ type: "id", value: "slotChild" }]),+ createInstance("slotChild", "Box", []),+ createInstance("bodyChild2", "Box", []),+ ])+ );+ const { instances } = getInstancesSlice("bodyChild1");++ expect(instances).toEqual([+ createInstance("bodyChild1", "Box", [{ type: "id", value: "slot" }]),+ createInstance("slot", "Slot", [{ type: "id", value: "slotChild" }]),+ createInstance("slotChild", "Box", []),+ ]);+ });++ test("collect all styles and breakpoints bound to instances slice", () => {+ // body+ // box1+ // box2+ instancesStore.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ])+ );+ styleSourceSelectionsStore.set(+ new Map([+ ["body", { instanceId: "box1", values: ["localBody", "token1"] }],+ ["box1", { instanceId: "box1", values: ["localBox1", "token2"] }],+ ["box2", { instanceId: "box2", values: ["localBox2", "token2"] }],+ ])+ );+ styleSourcesStore.set(+ new Map([+ ["localBody", { id: "localBody", type: "local" }],+ ["localBox1", { id: "localBox1", type: "local" }],+ ["localBox2", { id: "localBox2", type: "local" }],+ ["token1", { id: "token1", type: "token", name: "token1" }],+ ["token2", { id: "token2", type: "token", name: "token2" }],+ ])+ );+ stylesStore.set(+ new Map([+ createStyleDeclPair("localBody1", "base", "color", "red"),+ createStyleDeclPair("localBox1", "base", "color", "green"),+ createStyleDeclPair("localBox2", "base", "color", "blue"),+ createStyleDeclPair("token1", "base", "color", "yellow"),+ createStyleDeclPair("token2", "base", "color", "orange"),+ ])+ );+ breakpointsStore.set(+ new Map([+ ["base", { id: "base", label: "base" }],+ ["big", { id: "big", label: "big", minWidth: 768 }],+ ])+ );+ const { styleSources, styleSourceSelections, styles, breakpoints } =+ getInstancesSlice("box1");++ // exclude localBody and token1 bound to body+ expect(styleSources).toEqual([+ { id: "localBox1", type: "local" },+ { id: "token2", type: "token", name: "token2" },+ { id: "localBox2", type: "local" },+ ]);+ expect(styleSourceSelections).toEqual([+ { instanceId: "box1", values: ["localBox1", "token2"] },+ { instanceId: "box2", values: ["localBox2", "token2"] },+ ]);+ expect(styles).toEqual([+ createStyleDecl("localBox1", "base", "color", "green"),+ createStyleDecl("localBox2", "base", "color", "blue"),+ createStyleDecl("token2", "base", "color", "orange"),+ ]);+ expect(breakpoints).toEqual([{ id: "base", label: "base" }]);+ });++ test("collect all props bound to instances slice", () => {+ // body+ // box1+ // box2+ instancesStore.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ])+ );+ propsStore.set(+ toMap([+ createProp("body", "bodyProp", "data-body"),+ createProp("box1", "box1Prop", "data-box1"),+ createProp("box2", "box2Prop", "data-box2"),+ ])+ );+ const { props } = getInstancesSlice("box1");++ expect(props).toEqual([+ createProp("box1", "box1Prop", "data-box1"),+ createProp("box2", "box2Prop", "data-box2"),+ ]);+ });++ test("collect assets from props and styles withiin instances slice", () => {+ // body+ // box1+ // box2+ instancesStore.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ])+ );+ propsStore.set(+ new Map([+ [+ "bodyProp",+ {+ id: "bodyProp",+ instanceId: "body",+ name: "data-body",+ type: "asset",+ value: "asset1",+ },+ ],+ [+ "box1Prop",+ {+ id: "box1Prop",+ instanceId: "box1",+ name: "data-box1",+ type: "asset",+ value: "asset2",+ },+ ],+ ])+ );+ styleSourceSelectionsStore.set(+ new Map([+ ["body", { instanceId: "box1", values: ["localBody"] }],+ ["box1", { instanceId: "box1", values: ["localBox1"] }],+ ])+ );+ styleSourcesStore.set(+ new Map([+ ["localBody", { id: "localBody", type: "local" }],+ ["localBox1", { id: "localBox1", type: "local" }],+ ])+ );+ stylesStore.set(+ new Map([+ createStyleDeclPair("localBody1", "base", "fontFamily", {+ type: "fontFamily",+ value: ["font1"],+ }),+ createStyleDeclPair("localBody1", "base", "backgroundImage", {+ type: "image",+ value: { type: "asset", value: "asset3" },+ }),+ createStyleDeclPair("localBox1", "base", "fontFamily", {+ type: "fontFamily",+ value: ["font2"],+ }),+ createStyleDeclPair("localBox1", "base", "color", {+ type: "image",+ value: { type: "asset", value: "asset4" },+ }),+ ])+ );+ breakpointsStore.set(new Map([["base", { id: "base", label: "base" }]]));+ assetsStore.set(+ toMap([+ createImageAsset("asset1"),+ createImageAsset("asset2"),+ createImageAsset("asset3"),+ createImageAsset("asset4"),+ createFontAsset("asset5", "font1"),+ createFontAsset("asset6", "font2"),+ ])+ );+ const { assets } = getInstancesSlice("box1");++ expect(assets).toEqual([+ createImageAsset("asset2"),+ createImageAsset("asset4"),+ createFontAsset("asset6", "font2"),+ ]);+ });++ test("collect data sources within instances slice and convert others to value prop", () => {+ // body+ // box1+ // box2+ instancesStore.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ])+ );+ dataSourcesStore.set(+ toMap([+ {+ id: "box1$state",+ scopeInstanceId: "box1",+ type: "variable",+ name: "state",+ value: { type: "string", value: "initial" },+ },+ {+ id: "box2$stateInitial",+ scopeInstanceId: "box2",+ type: "expression",+ name: "stateInitial",+ code: `$ws$dataSource$box1$state === 'initial'`,+ },+ {+ id: "box2$true",+ scopeInstanceId: "box2",+ type: "expression",+ name: "trueValue",+ code: `true`,+ },+ ])+ );+ propsStore.set(+ toMap([+ {+ id: "box1$state",+ instanceId: "box1",+ type: "dataSource",+ name: "state",+ value: "box1$state",+ },+ {+ id: "box2$state",+ instanceId: "box2",+ type: "dataSource",+ name: "state",+ value: "box1$state",+ },+ {+ id: "box2$show",+ instanceId: "box2",+ type: "dataSource",+ name: "show",+ value: "box2$stateInitial",+ },+ {+ id: "box2$true",+ instanceId: "box2",+ type: "dataSource",+ name: "bool-prop",+ value: "box2$true",+ },+ ])+ );+ const { props } = getInstancesSlice("box2");++ expect(props).toEqual([+ {+ id: "box2$state",+ instanceId: "box2",+ type: "string",+ name: "state",+ value: "initial",+ },+ {+ id: "box2$show",+ instanceId: "box2",+ type: "boolean",+ name: "show",+ value: true,+ },+ {+ id: "box2$true",+ instanceId: "box2",+ type: "dataSource",+ name: "bool-prop",+ value: "box2$true",+ },+ ]);+ });++ test("clear actions which depend on data sources outside of instances slice", () => {+ // body+ // box1+ // box2+ instancesStore.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ])+ );+ dataSourcesStore.set(+ toMap([+ {+ id: "box1$state",+ scopeInstanceId: "box1",+ type: "variable",+ name: "state",+ value: { type: "string", value: "initial" },+ },+ {+ id: "box2$state",+ scopeInstanceId: "box2",+ type: "variable",+ name: "state",+ value: { type: "string", value: "initial" },+ },+ ])+ );+ propsStore.set(+ toMap([+ {+ id: "box2$onChange1",+ instanceId: "box2",+ type: "action",+ name: "onChange",+ value: [+ {+ type: "execute",+ args: ["value"],+ code: `$ws$dataSource$box1$state = value`,+ },+ ],+ },+ {+ id: "box2$onChange2",+ instanceId: "box2",+ type: "action",+ name: "onChange",+ value: [+ {+ type: "execute",+ args: ["value"],+ code: `$ws$dataSource$box2$state = value`,+ },+ ],+ },+ ])+ );+ const { props } = getInstancesSlice("box2");++ expect(props).toEqual([+ {+ id: "box2$onChange1",+ instanceId: "box2",+ type: "action",+ name: "onChange",+ value: [],+ },+ {+ id: "box2$onChange2",+ instanceId: "box2",+ type: "action",+ name: "onChange",+ value: [+ {+ type: "execute",+ args: ["value"],+ code: `$ws$dataSource$box2$state = value`,+ },+ ],+ },+ ]);+ });+});diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex d490eceef0..bb550af84b 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -4,12 +4,24 @@ import {type Instances,type StyleSource,getStyleDeclKey,+ findTreeInstanceIds,+ StyleSourceSelection,+ StyleDecl,+ Asset,+ StyleSources,+ Breakpoints,+ DataSources,+ Props,} from "@webstudio-is/sdk";import { findTreeInstanceIdsExcludingSlotDescendants } from "@webstudio-is/sdk";import {type WsComponentMeta,generateDataFromEmbedTemplate,type EmbedTemplateData,+ encodeDataSourceVariable,+ computeExpressionsDependencies,+ decodeDataSourceVariable,+ validateExpression,} from "@webstudio-is/react-sdk";import {propsStore,@@ -22,6 +34,8 @@ import {breakpointsStore,registeredComponentMetasStore,dataSourcesStore,+ assetsStore,+ dataSourcesLogicStore,} from "./nano-states";import {type DroppableTarget,@@ -36,6 +50,7 @@ import { removeByMutable } from "./array-utils";import { isBaseBreakpoint } from "./breakpoints";import { humanizeString } from "./string-utils";import { serverSyncStore } from "./sync";+import type { StyleValue } from "@webstudio-is/css-engine";const getLabelFromComponentName = (component: Instance["component"]) => {if (component.includes(":")) {@@ -487,3 +502,285 @@ export const deleteInstance = (instanceSelector: InstanceSelector) => {);return true;};++const traverseStyleValue = (+ value: StyleValue,+ callback: (value: StyleValue) => void+) => {+ if (+ value.type === "fontFamily" ||+ value.type === "image" ||+ value.type === "unit" ||+ value.type === "keyword" ||+ value.type === "unparsed" ||+ value.type === "invalid" ||+ value.type === "unset" ||+ value.type === "rgb"+ ) {+ callback(value);+ return;+ }+ if (value.type === "var") {+ for (const item of value.fallbacks) {+ traverseStyleValue(item, callback);+ }+ return;+ }+ if (value.type === "tuple" || value.type === "layers") {+ for (const item of value.value) {+ traverseStyleValue(item, callback);+ }+ return;+ }+ value satisfies never;+};++const getPropTypeAndValue = (name: string, value: unknown) => {+ if (typeof value === "boolean") {+ return { type: "boolean", value } as const;+ }+ if (typeof value === "number") {+ return { type: "number", value } as const;+ }+ if (typeof value === "string") {+ return { type: "string", value } as const;+ }+ if (Array.isArray(value)) {+ return { type: "string[]", value } as const;+ }+ throw Error(`Unexpected "${name}" prop value ${value}`);+};++export const getInstancesSlice = (rootInstanceId: string) => {+ const assets = assetsStore.get();+ const instances = instancesStore.get();+ const dataSources = dataSourcesStore.get();+ const props = propsStore.get();+ const styleSourceSelections = styleSourceSelectionsStore.get();+ const styleSources = styleSourcesStore.get();+ const breakpoints = breakpointsStore.get();+ const styles = stylesStore.get();++ const dataSourcesLogic = dataSourcesLogicStore.get();++ // collect the instance by id and all its descendants including portal instances+ const slicedInstanceIds = findTreeInstanceIds(instances, rootInstanceId);+ const slicedInstances: Instance[] = [];+ const slicedStyleSourceSelections: StyleSourceSelection[] = [];+ const slicedStyleSources: StyleSources = new Map();+ for (const instanceId of slicedInstanceIds) {+ const instance = instances.get(instanceId);+ if (instance) {+ slicedInstances.push(instance);+ }++ // collect all style sources bound to these instances+ const styleSourceSelection = styleSourceSelections.get(instanceId);+ if (styleSourceSelection) {+ slicedStyleSourceSelections.push(styleSourceSelection);+ for (const styleSourceId of styleSourceSelection.values) {+ if (slicedStyleSources.has(styleSourceId)) {+ continue;+ }+ const styleSource = styleSources.get(styleSourceId);+ if (styleSource === undefined) {+ continue;+ }+ slicedStyleSources.set(styleSourceId, styleSource);+ }+ }+ }++ const slicedAssetIds = new Set<Asset["id"]>();+ const slicedFontFamilies = new Set<string>();++ // collect styles bound to these style sources+ const slicedStyles: StyleDecl[] = [];+ const slicedBreapoints: Breakpoints = new Map();+ for (const styleDecl of styles.values()) {+ if (slicedStyleSources.has(styleDecl.styleSourceId) === false) {+ continue;+ }+ slicedStyles.push(styleDecl);++ // collect breakpoints+ if (slicedBreapoints.has(styleDecl.breakpointId) === false) {+ const breakpoint = breakpoints.get(styleDecl.breakpointId);+ if (breakpoint) {+ slicedBreapoints.set(styleDecl.breakpointId, breakpoint);+ }+ }++ // collect assets including fonts+ traverseStyleValue(styleDecl.value, (value) => {+ if (value.type === "fontFamily") {+ for (const fontFamily of value.value) {+ slicedFontFamilies.add(fontFamily);+ }+ }+ if (value.type === "image") {+ if (value.value.type === "asset") {+ slicedAssetIds.add(value.value.value);+ }+ }+ });+ }++ // compute dependencies of expressions to make sure all data sources+ // are inside of instances slice and can be copied+ const expressions = new Map<string, string>();+ for (const dataSource of dataSources.values()) {+ if (dataSource.type === "expression") {+ expressions.set(encodeDataSourceVariable(dataSource.id), dataSource.code);+ }+ }+ const dependencies = computeExpressionsDependencies(expressions);++ // collect data sources scoped to instances slice+ //+ // @todo copy data sources outside of slice tree and bind to copied root+ // to preserve bindings and let users easily rebind variables+ // blocked by lack of UI to manage data sources+ const slicedDataSources: DataSources = new Map();+ for (const dataSource of dataSources.values()) {+ let canBeCopied = true;+ if (dataSource.type === "expression") {+ const expressionDeps = dependencies.get(+ encodeDataSourceVariable(dataSource.id)+ );+ // check if all expression dependencies can be copied+ if (expressionDeps) {+ for (const dependency of expressionDeps) {+ const dataSourceId = decodeDataSourceVariable(dependency);+ if (dataSourceId === undefined) {+ continue;+ }+ const dataSource = dataSources.get(dataSourceId);+ if (dataSource === undefined) {+ continue;+ }+ if (+ dataSource.scopeInstanceId === undefined ||+ slicedInstanceIds.has(dataSource.scopeInstanceId) === false+ ) {+ canBeCopied = false;+ }+ }+ }+ }+ if (+ canBeCopied &&+ // check if data source itself can be copied+ dataSource.scopeInstanceId !== undefined &&+ slicedInstanceIds.has(dataSource.scopeInstanceId)+ ) {+ slicedDataSources.set(dataSource.id, dataSource);+ }+ }++ // @todo convert to value props+ // when variables are outside of slice and cannot be copied++ // collect props bound to these instances+ const slicedProps: Props = new Map();+ for (const prop of props.values()) {+ if (slicedInstanceIds.has(prop.instanceId) === false) {+ continue;+ }++ slicedProps.set(prop.id, prop);++ // convert data source prop to value prop+ // when not scoped to sliced instances+ //+ // @todo stop converting to value props once UI is ready+ if (prop.type === "dataSource") {+ const dataSourceId = prop.value;+ if (slicedDataSources.has(dataSourceId) === false) {+ const value = dataSourcesLogic.get(dataSourceId);+ slicedProps.set(prop.id, {+ id: prop.id,+ instanceId: prop.instanceId,+ name: prop.name,+ ...getPropTypeAndValue(prop.name, value),+ });+ }+ }++ // clear effectful expressions when depend on data sources+ // outside of instances slice+ //+ // @todo should not be necessary once bindings UI is available+ if (prop.type === "action") {+ slicedProps.set(prop.id, {+ ...prop,+ value: prop.value.flatMap((value) => {+ if (value.type !== "execute") {+ return [value];+ }+ let shouldKeepAction = true;+ validateExpression(value.code, {+ effectful: true,+ transformIdentifier: (identifier) => {+ if (value.args.includes(identifier)) {+ return identifier;+ }+ const id = decodeDataSourceVariable(identifier);+ if (id === undefined) {+ return identifier;+ }+ if (slicedDataSources.has(id) === false) {+ shouldKeepAction = false;+ return identifier;+ }+ const identifierDeps = dependencies.get(id);+ if (identifierDeps) {+ for (const dependency of identifierDeps) {+ const id = decodeDataSourceVariable(dependency);+ if (id === undefined) {+ continue;+ }+ if (slicedDataSources.has(id) === false) {+ shouldKeepAction = false;+ return identifier;+ }+ }+ }+ return identifier;+ },+ });+ if (shouldKeepAction) {+ return [value];+ }+ return [];+ }),+ });+ }++ // collect assets+ if (prop.type === "asset") {+ slicedAssetIds.add(prop.value);+ }+ }++ const slicedAssets: Asset[] = [];+ for (const asset of assets.values()) {+ if (+ slicedAssetIds.has(asset.id) ||+ (asset.type === "font" && slicedFontFamilies.has(asset.meta.family))+ ) {+ slicedAssets.push(asset);+ }+ }++ return {+ instances: slicedInstances,+ styleSourceSelections: slicedStyleSourceSelections,+ styleSources: Array.from(slicedStyleSources.values()),+ breakpoints: Array.from(slicedBreapoints.values()),+ styles: slicedStyles,+ dataSources: Array.from(slicedDataSources.values()),+ props: Array.from(slicedProps.values()),+ assets: slicedAssets,+ };+};