Skip to content

refactor: decouple system store from variables #4888

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 6 additions & 39 deletions apps/builder/app/builder/features/address-bar.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,15 @@
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import type { Meta, StoryFn } from "@storybook/react";
import { Box, Text, theme } from "@webstudio-is/design-system";
import { AddressBarPopover } from "./address-bar";
import {
$dataSourceVariables,
$dataSources,
$pages,
} from "~/shared/nano-states";
import { $dataSources, $pages } from "~/shared/nano-states";
import { registerContainers } from "~/shared/sync";
import { $awareness, $selectedPage } from "~/shared/awareness";
import { $currentSystem } from "~/shared/system";

registerContainers();

$dataSources.set(
new Map([
[
"systemId",
{
id: "systemId",
scopeInstanceId: "rootInstanceId",
name: "system",
type: "parameter",
},
],
])
);
$dataSources.set(new Map());

$pages.set({
folders: [
Expand All @@ -43,7 +27,6 @@ $pages.set({
title: "",
meta: {},
rootInstanceId: "",
systemDataSourceId: "",
},
pages: [
{
Expand All @@ -53,40 +36,24 @@ $pages.set({
title: "",
meta: {},
rootInstanceId: "rootInstanceId",
systemDataSourceId: "systemId",
},
],
});

const $selectedPageSystem = computed(
[$selectedPage, $dataSourceVariables],
(selectedPage, dataSourceVariables) => {
if (selectedPage?.systemDataSourceId === undefined) {
return {};
}
return dataSourceVariables.get(selectedPage.systemDataSourceId);
}
);

const SystemInspect = () => {
const system = useStore($selectedPageSystem);
const system = useStore($currentSystem);
return (
<Text variant="mono" css={{ whiteSpace: "pre" }}>
{JSON.stringify(system, null, 2)}
</Text>
);
};

const $selectedPageHistory = computed(
$selectedPage,
(page) => page?.history ?? []
);

const HistoryInspect = () => {
const history = useStore($selectedPageHistory);
const page = useStore($selectedPage);
return (
<Text variant="mono" css={{ whiteSpace: "pre" }}>
{JSON.stringify(history, null, 2)}
{JSON.stringify(page?.history, null, 2)}
</Text>
);
};
Expand Down
46 changes: 6 additions & 40 deletions apps/builder/app/builder/features/address-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,16 @@ import {
findParentFolderByChildId,
ROOT_FOLDER_ID,
getPagePath,
type System,
} from "@webstudio-is/sdk";
import {
$dataSourceVariables,
$pages,
$publishedOrigin,
$selectedPageDefaultSystem,
updateSystem,
} from "~/shared/nano-states";
import { $pages, $publishedOrigin } from "~/shared/nano-states";
import {
compilePathnamePattern,
isPathnamePattern,
matchPathnamePattern,
tokenizePathnamePattern,
} from "~/builder/shared/url-pattern";
import { savePathInHistory } from "~/shared/pages";
import { $selectedPage } from "~/shared/awareness";
import { $currentSystem, updateCurrentSystem } from "~/shared/system";

const $selectedPagePath = computed([$selectedPage, $pages], (page, pages) => {
if (pages === undefined || page === undefined) {
Expand All @@ -62,19 +55,6 @@ const $selectedPagePath = computed([$selectedPage, $pages], (page, pages) => {
.replace(/\/+/g, "/");
});

const $selectedPagePathParams = computed(
[$selectedPageDefaultSystem, $selectedPage, $dataSourceVariables],
(defaultSystem, selectedPage, dataSourceVariables) => {
if (selectedPage?.systemDataSourceId === undefined) {
return defaultSystem.params;
}
const system = dataSourceVariables.get(selectedPage.systemDataSourceId) as
| undefined
| System;
return system?.params ?? defaultSystem.params;
}
);

const $selectedPageHistory = computed(
$selectedPage,
(page) => page?.history ?? []
Expand Down Expand Up @@ -278,7 +258,7 @@ const AddressBar = forwardRef<
return history.filter((item) => matchPathnamePattern(path, item));
}, [history, path]);
const [pathParams, setPathParams] = useState(
() => $selectedPagePathParams.get() ?? {}
() => $currentSystem.get().params
);
const tokens = tokenizePathnamePattern(path);
const compiledPath = compilePathnamePattern(tokens, pathParams);
Expand Down Expand Up @@ -307,26 +287,11 @@ const AddressBar = forwardRef<
return (
<form
ref={mergeRefs(ref, containerRef)}
style={{ position: "relative" }}
onSubmit={(event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const path = $selectedPagePath.get();
const tokens = tokenizePathnamePattern(path);
// delete stale fields
const newParams: Record<string, string> = {};
for (const token of tokens) {
if (token.type === "param") {
newParams[token.name] = String(formData.get(token.name) ?? "");
}
}
const page = $selectedPage.get();
if (page === undefined) {
return;
}
updateSystem(page, { params: newParams });
const compiledPath = compilePathnamePattern(tokens, newParams);
savePathInHistory(page.id, compiledPath);
const params = Object.fromEntries(formData) as Record<string, string>;
updateCurrentSystem({ params });
if (errors.size === 0) {
onSubmit();
}
Expand Down Expand Up @@ -357,6 +322,7 @@ const AddressBar = forwardRef<
key={index}
name={token.name}
fieldSizing="content"
autoComplete="off"
css={{ minWidth: theme.spacing[15] }}
color={errors.has(token.name) ? "error" : undefined}
placeholder={token.name}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,12 @@ $breakpoints.set(
)
);

const pages = createDefaultPages({
rootInstanceId: "",
systemDataSourceId: "",
});
const pages = createDefaultPages({ rootInstanceId: "" });
pages.pages.push({
id: "page2",
path: "",
name: "Second Page",
rootInstanceId: "",
systemDataSourceId: "",
title: "",
meta: {},
});
Expand All @@ -58,7 +54,6 @@ pages.pages.push({
path: "",
name: "Thrid Page",
rootInstanceId: "",
systemDataSourceId: "",
title: "",
meta: {},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ $assets.set(
])
);

const pages = createDefaultPages({
rootInstanceId: "root-instance-id",
systemDataSourceId: "systemDataSourceId",
});
const pages = createDefaultPages({ rootInstanceId: "root-instance-id" });
pages.meta = {
siteName: "Project name",
faviconAssetId: "imageId",
Expand All @@ -53,7 +50,6 @@ pages.pages.push({
name: "page-name",
meta: {},
rootInstanceId: "root-instance-id",
systemDataSourceId: "systemDataSourceId",
});
const rootFolder = pages.folders.find(isRootFolder);
rootFolder?.children.push("pageId");
Expand Down
8 changes: 4 additions & 4 deletions apps/builder/app/builder/features/pages/page-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
} from "~/shared/nano-states";
import { registerContainers } from "~/shared/sync";
import { $awareness } from "~/shared/awareness";
import { updateCurrentSystem } from "~/shared/system";

setEnv("*");
registerContainers();
Expand Down Expand Up @@ -525,10 +526,9 @@ test("page root scope should prefill default system variable value", () => {
],
]),
});

$dataSourceVariables.set(
new Map([["systemId", { params: { slug: "my-post" }, search: {} }]])
);
updateCurrentSystem({
params: { slug: "my-post" },
});
expect($pageRootScope.get()).toEqual({
aliases: new Map([["$ws$dataSource$systemId", "system"]]),
scope: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ export const Redirects = () => {
title: `"My Title"`,
meta: {},
rootInstanceId: "body",
systemDataSourceId: "",
},
pages: [],
folders: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ describe("getExistingRoutePaths", () => {
test("gets all the route paths that exists in the project", () => {
const pages = createDefaultPages({
rootInstanceId: "rootInstanceId",
systemDataSourceId: "systemDataSourceId",
homePageId: "homePageId",
});

Expand All @@ -16,7 +15,6 @@ describe("getExistingRoutePaths", () => {
name: "Page",
path: "/page",
rootInstanceId: "rootInstanceId",
systemDataSourceId: "systemDataSourceId",
title: `"Page"`,
});

Expand All @@ -26,7 +24,6 @@ describe("getExistingRoutePaths", () => {
name: "Blog",
path: "/blog/:id",
rootInstanceId: "rootInstanceId",
systemDataSourceId: "systemDataSourceId",
title: `"Blog"`,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,10 @@ const page = (name: string, path: string): Page => ({
path,
meta: {},
rootInstanceId: unique(),
systemDataSourceId: unique(),
});

$pages.set({
...createDefaultPages({
rootInstanceId: unique(),
systemDataSourceId: unique(),
}),

...createDefaultPages({ rootInstanceId: unique() }),
homePage: page("Home", "") as Page & { path: "" },
pages: [
page("About", "/about"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ $instances.set(
["box", { id: "box", type: "instance", component: "Box", children: [] }],
])
);
$pages.set(
createDefaultPages({ rootInstanceId: "box", systemDataSourceId: "system" })
);
$pages.set(createDefaultPages({ rootInstanceId: "box" }));
$awareness.set({ pageId: "home", instanceSelector: ["box"] });

export const VariablesSection: StoryObj = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ $pages.set(
createDefaultPages({
homePageId: "homePageId",
rootInstanceId: "box",
systemDataSourceId: "systemId",
})
);
$awareness.set({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ $pages.set(
createDefaultPages({
homePageId: "homePageId",
rootInstanceId: "box",
systemDataSourceId: "systemId",
})
);
$awareness.set({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ $pages.set(
createDefaultPages({
homePageId: "homePageId",
rootInstanceId: "box",
systemDataSourceId: "systemId",
})
);
$awareness.set({
Expand Down
2 changes: 1 addition & 1 deletion apps/builder/app/builder/shared/commands.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ registerContainers();

const metas = new Map(Object.entries(baseMetas));
$registeredComponentMetas.set(metas);
$pages.set(createDefaultPages({ rootInstanceId: "", systemDataSourceId: "" }));
$pages.set(createDefaultPages({ rootInstanceId: "" }));
$awareness.set({ pageId: "" });

describe("deleteInstance", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,6 @@ export const CursorPositioningUpDown: StoryFn<typeof TextEditor> = () => {
path: "",
title: "",
name: "",
systemDataSourceId: "",
},
pages: [
{
Expand All @@ -232,7 +231,6 @@ export const CursorPositioningUpDown: StoryFn<typeof TextEditor> = () => {
path: "",
title: "",
name: "",
systemDataSourceId: "",
meta: {},
},
],
Expand Down
8 changes: 3 additions & 5 deletions apps/builder/app/canvas/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import {
$isPreviewMode,
$pages,
$selectedPageHash,
updateSystem,
} from "~/shared/nano-states";
import { savePathInHistory } from "~/shared/pages";
import { updateCurrentSystem } from "~/shared/system";

const isAbsoluteUrl = (href: string) => {
try {
Expand Down Expand Up @@ -62,10 +61,9 @@ const switchPageAndUpdateSystem = (href: string, formData?: FormData) => {
const search = Object.fromEntries(pageHref.searchParams);
$selectedPageHash.set({ hash: pageHref.hash });
selectPage(page.id);
updateSystem(page, { params, search });
savePathInHistory(page.id, pageHref.pathname);
break;
updateCurrentSystem({ params, search });
}
break;
}
};

Expand Down
2 changes: 1 addition & 1 deletion apps/builder/app/shared/copy-paste.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ $project.set({ id: "current_project" } as Project);

const createStub = (element: JSX.Element) => {
const project = {
pages: createDefaultPages({ rootInstanceId: "", systemDataSourceId: "" }),
pages: createDefaultPages({ rootInstanceId: "" }),
...renderData(element),
};
// global root instance is never stored in data
Expand Down
1 change: 0 additions & 1 deletion apps/builder/app/shared/copy-paste/plugin-instance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ $pages.set(
createDefaultPages({
homePageId: "home-page",
rootInstanceId: "body0",
systemDataSourceId: "",
})
);
$awareness.set({ pageId: "home-page" });
Expand Down
Loading
Loading