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.

Expose form state change with action (#2295)

Bogdan Chadkinf67b0bd9b02d
diff --git a/packages/prisma-client/prisma/migrations/20230911125308_form_action/migration.ts b/packages/prisma-client/prisma/migrations/20230911125308_form_action/migration.ts
new file mode 100644
index 0000000000..9c3136711b
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230911125308_form_action/migration.ts
@@ -0,0 +1,144 @@
+import { nanoid } from "nanoid";
+import { PrismaClient } from "./client";
+
+const dataSourceVariablePrefix = "$ws$dataSource$";
+
+const encodeDataSourceVariable = (id: string) => {
+ const encoded = id.replaceAll("-", "__DASH__");
+ return `${dataSourceVariablePrefix}${encoded}`;
+};
+
+type Text = {
+ type: "text";
+ value: string;
+};
+
+type Id = {
+ type: "id";
+ value: string;
+};
+
+export type Instance = {
+ type: "instance";
+ id: string;
+ component: string;
+ label?: string;
+ children: Array<Id | Text>;
+};
+
+type InstancesList = Instance[];
+
+type BaseProp = {
+ id: string;
+ instanceId: string;
+ name: string;
+ required?: boolean;
+};
+
+type Prop = BaseProp &
+ (
+ | { type: "number"; value: number }
+ | { type: "string"; value: string }
+ | { type: "boolean"; value: boolean }
+ | { type: "asset"; value: string }
+ | { type: "page"; value: string | { pageId: string; instanceId: string } }
+ | { type: "string[]"; value: string[] }
+ | { type: "dataSource"; value: string }
+ | {
+ type: "action";
+ value: Array<{ type: "execute"; args: string[]; code: string }>;
+ }
+ );
+
+type PropsList = Prop[];
+
+export default async () => {
+ const client = new PrismaClient({
+ // Uncomment to see the queries in console as the migration runs
+ // log: ["query", "info", "warn", "error"],
+ });
+
+ await client.$transaction(
+ async (prisma) => {
+ const chunkSize = 1000;
+ let cursor: undefined | string = undefined;
+ let hasNext = true;
+ while (hasNext) {
+ const builds = await prisma.build.findMany({
+ take: chunkSize,
+ orderBy: {
+ id: "asc",
+ },
+ ...(cursor
+ ? {
+ skip: 1, // Skip the cursor
+ cursor: { id: cursor },
+ }
+ : null),
+ });
+ cursor = builds.at(-1)?.id;
+ hasNext = builds.length === chunkSize;
+ const changedBuilds: typeof builds = [];
+
+ for (const build of builds) {
+ const buildId = build.id;
+ try {
+ const instancesList: InstancesList = JSON.parse(build.instances);
+ const propsList: PropsList = JSON.parse(build.props);
+
+ let changed = false;
+
+ const formInstanceIds = new Set<string>();
+ for (const instance of instancesList) {
+ if (instance.component === "Form") {
+ formInstanceIds.add(instance.id);
+ changed = true;
+ }
+ }
+
+ for (const prop of propsList) {
+ if (
+ prop.name === "state" &&
+ formInstanceIds.has(prop.instanceId) &&
+ prop.type === "dataSource"
+ ) {
+ const dataSourceId = prop.value;
+ const formState = encodeDataSourceVariable(dataSourceId);
+ propsList.push({
+ id: nanoid(),
+ instanceId: prop.instanceId,
+ type: "action",
+ name: "onStateChange",
+ value: [
+ {
+ type: "execute",
+ args: ["state"],
+ code: `${formState} = state`,
+ },
+ ],
+ });
+ }
+ }
+
+ if (changed) {
+ build.instances = JSON.stringify(instancesList);
+ build.props = JSON.stringify(propsList);
+ changedBuilds.push(build);
+ }
+ } catch {
+ console.info(`build ${buildId} cannot be converted`);
+ }
+ }
+ await Promise.all(
+ changedBuilds.map(({ id, instances, props, dataSources }) =>
+ prisma.build.update({
+ where: { id },
+ data: { instances, props, dataSources },
+ })
+ )
+ );
+ }
+ },
+ { timeout: 1000 * 60 * 8 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20230911125308_form_action/schema.prisma b/packages/prisma-client/prisma/migrations/20230911125308_form_action/schema.prisma
new file mode 100644
index 0000000000..867ebf36bd
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230911125308_form_action/schema.prisma
@@ -0,0 +1,234 @@
+// DO NOT EDIT THIS FILE!
+// This is a copy of your schema.prisma that corresponds to the state of the database
+// when all migrations up until this one are applied.
+// It's used to generate a Prisma Client for the migration.
+
+// This is your Prisma schema file,
+// learn more about it in the docs: https://pris.ly/d/prisma-schema
+
+generator client {
+ provider = "prisma-client-js"
+ previewFeatures = ["views", "clientExtensions", "jsonProtocol"]
+ // see commands.ts
+ output = "client"
+}
+
+datasource db {
+ provider = "postgres"
+ url = env("DATABASE_URL")
+}
+
+model Team {
+ id String @id @default(uuid())
+ users User[]
+}
+
+enum UploadStatus {
+ UPLOADING
+ UPLOADED
+}
+
+model File {
+ name String @id
+ format String
+ size Int
+ description String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ meta String @default("{}")
+ status UploadStatus @default(UPLOADING)
+ isDeleted Boolean @default(false)
+ uploaderProject Project? @relation(fields: [uploaderProjectId], references: [id])
+ uploaderProjectId String?
+ assets Asset[]
+}
+
+model Asset {
+ id String @default(uuid()) // not unique!
+ projectId String
+ file File @relation(fields: [name], references: [name])
+ name String
+
+ @@id([id, projectId])
+}
+
+model User {
+ id String @id @default(uuid())
+ email String? @unique
+ provider String?
+ image String?
+ username String?
+ createdAt DateTime @default(now())
+ team Team? @relation(fields: [teamId], references: [id])
+ teamId String?
+ projects Project[]
+}
+
+model Project {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ title String
+ domain String @unique
+ user User? @relation(fields: [userId], references: [id])
+ userId String?
+ build Build[]
+ isDeleted Boolean @default(false)
+ files File[]
+ projectDomain ProjectDomain[]
+ latestBuild LatestBuildPerProject?
+
+ @@unique([id, isDeleted])
+ @@unique([domain, isDeleted])
+ @@unique([id, domain])
+}
+
+enum PublishStatus {
+ PENDING
+ PUBLISHED
+ FAILED
+}
+
+model Build {
+ id String @unique @default(uuid())
+ version Int @default(0)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ pages String
+
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+
+ breakpoints String @default("[]")
+ styles String @default("[]")
+ styleSources String @default("[]")
+ styleSourceSelections String @default("[]")
+ props String @default("[]")
+ dataSources String @default("[]")
+ instances String @default("[]")
+
+ deployment String?
+ publishStatus PublishStatus @default(PENDING)
+
+ @@id([id, projectId])
+}
+
+enum AuthorizationRelation {
+ viewers
+ editors
+ builders
+ administrators
+}
+
+model AuthorizationToken {
+ token String @default(uuid())
+ // No relation to Project, as the Authorization system is not tied to a project
+ projectId String
+ name String @default("")
+ relation AuthorizationRelation @default(viewers)
+ createdAt DateTime @default(now())
+
+ @@id([token, projectId])
+}
+
+enum DomainStatus {
+ INITIALIZING
+ ACTIVE
+ ERROR
+ PENDING
+}
+
+// Domains + last known status and last known txtRecord
+// In the future we can update this table using queue, n8n or temporal workflows.
+// As of now updates are done during UI interactions
+model Domain {
+ id String @id @default(uuid())
+ domain String @unique
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ ProjectDomain ProjectDomain[]
+ // Last known txtRecord of the domain (to check domain ownership)
+ txtRecord String?
+ // create, init, pending, active, error
+ status DomainStatus @default(INITIALIZING)
+ // In case of status="error", this will contain the error message
+ error String?
+
+ projectWithDomain ProjectWithDomain[]
+}
+
+model ProjectDomain {
+ projectId String
+ project Project @relation(fields: [projectId], references: [id])
+ domainId String
+ domain Domain @relation(fields: [domainId], references: [id])
+ createdAt DateTime @default(now())
+ // Generated txt record to check domain ownership
+ txtRecord String @unique @default(uuid())
+
+ // CNAME record to point to the domain
+ cname String
+
+ @@id([projectId, domainId])
+ @@index([domainId])
+}
+
+view ProjectWithDomain {
+ projectId String
+
+ domainId String
+ domain Domain @relation(fields: [domainId], references: [id])
+ txtRecord String
+
+ createdAt DateTime
+
+ // CNAME record to point to the domain
+ cname String
+
+ verified Boolean
+ // To count statistics per user
+ userId String?
+
+ // We can deploy on per domain basis, here for each project domain we have latest build
+ latestBuid LatestBuildPerProjectDomain?
+
+ @@id([projectId, domainId])
+}
+
+view LatestBuildPerProjectDomain {
+ domainId String
+ buildId String
+ projectId String
+ projectWithDomain ProjectWithDomain @relation(fields: [projectId, domainId], references: [projectId, domainId])
+
+ isLatestBuild Boolean
+ publishStatus PublishStatus
+ updatedAt DateTime
+
+ @@id([projectId, domainId])
+}
+
+view LatestBuildPerProject {
+ buildId String
+
+ projectId String
+ domain String
+ project Project @relation(fields: [projectId, domain], references: [id, domain])
+
+ isLatestBuild Boolean
+ publishStatus PublishStatus
+ updatedAt DateTime
+
+ @@id([projectId, domain])
+}
+
+// Dashboard
+view DashboardProject {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ title String
+ domain String
+ userId String?
+ isDeleted Boolean @default(false)
+ isPublished Boolean
+}
diff --git a/packages/react-sdk/src/context.tsx b/packages/react-sdk/src/context.tsx
index c7c89610b3..9bd5a6290b 100644
--- a/packages/react-sdk/src/context.tsx
+++ b/packages/react-sdk/src/context.tsx
@@ -1,6 +1,6 @@
import { type ReadableAtom, atom } from "nanostores";
import { createContext } from "react";
-import type { DataSource, Instance, Prop, Assets } from "@webstudio-is/sdk";
+import type { DataSource, Assets } from "@webstudio-is/sdk";
import type { Pages, PropsByInstanceId } from "./props";
import type { IndexesWithinAncestors } from "./instance-utils";
import type { ImageLoader } from "@webstudio-is/image";
@@ -47,11 +47,6 @@ export const ReactSdkContext = createContext<
values: DataSourceValues
) => DataSourceValues;
setDataSourceValues: (newValues: DataSourceValues) => void;
- setBoundDataSourceValue: (
- instanceId: Instance["id"],
- prop: Prop["name"],
- value: unknown
- ) => void;
indexesWithinAncestors: IndexesWithinAncestors;
}
>({
@@ -66,10 +61,7 @@ export const ReactSdkContext = createContext<
throw Error("React SDK executeEffectfulExpression is not implemented");
},
setDataSourceValues: () => {
- throw Error("React SDK setBoundDataSourceValue is not implemented");
- },
- setBoundDataSourceValue: () => {
- throw Error("React SDK setBoundDataSourceValue is not implemented");
+ throw Error("React SDK setDataSourceValues is not implemented");
},
indexesWithinAncestors: new Map(),
});
diff --git a/packages/react-sdk/src/tree/create-elements-tree.tsx b/packages/react-sdk/src/tree/create-elements-tree.tsx
index 74242f41cd..8d5b0ca9b7 100644
--- a/packages/react-sdk/src/tree/create-elements-tree.tsx
+++ b/packages/react-sdk/src/tree/create-elements-tree.tsx
@@ -97,18 +97,6 @@ export const createElementsTree = ({
indexesWithinAncestors,
executeEffectfulExpression,
setDataSourceValues: onDataSourceUpdate,
- setBoundDataSourceValue: (instanceId, propName, value) => {
- const propsByInstanceId = propsByInstanceIdStore.get();
- const props = propsByInstanceId.get(instanceId);
- const prop = props?.find((prop) => prop.name === propName);
- if (prop?.type !== "dataSource") {
- throw Error(`${propName} is not data source`);
- }
- const dataSourceId = prop.value;
- const newValues = new Map();
- newValues.set(dataSourceId, value);
- onDataSourceUpdate(newValues);
- },
}}
>
{root}
diff --git a/packages/sdk-components-react-remix/src/form.tsx b/packages/sdk-components-react-remix/src/form.tsx
index e15f1a7822..6c93ff346e 100644
--- a/packages/sdk-components-react-remix/src/form.tsx
+++ b/packages/sdk-components-react-remix/src/form.tsx
@@ -4,14 +4,10 @@ import {
forwardRef,
useRef,
useEffect,
- useContext,
} from "react";
import { useFetcher, type Fetcher, type FormProps } from "@remix-run/react";
import { formIdFieldName } from "@webstudio-is/form-handlers";
-import {
- ReactSdkContext,
- getInstanceIdFromComponentProps,
-} from "@webstudio-is/react-sdk";
+import { getInstanceIdFromComponentProps } from "@webstudio-is/react-sdk";
export const defaultTag = "form";
@@ -41,19 +37,26 @@ export const Form = forwardRef<
ElementRef<typeof defaultTag>,
ComponentProps<typeof defaultTag> & {
/** Use this property to reveal the Success and Error states on the canvas so they can be styled. The Initial state is displayed when the page first opens. The Success and Error states are displayed depending on whether the Form submits successfully or unsuccessfully. */
- state?: State;
+ state: State;
encType?: FormProps["encType"];
+ onStateChange?: (state: State) => void;
}
->(({ children, action, method, state = "initial", ...rest }, ref) => {
- const { setBoundDataSourceValue } = useContext(ReactSdkContext);
-
+>((props, ref) => {
+ const {
+ children,
+ action,
+ method,
+ state = "initial",
+ onStateChange,
+ ...rest
+ } = props;
const fetcher = useFetcher();
const instanceId = getInstanceIdFromComponentProps(rest);
useOnFetchEnd(fetcher, (data) => {
const state: State = data?.success === true ? "success" : "error";
- setBoundDataSourceValue(instanceId, "state", state);
+ onStateChange?.(state);
});
return (
diff --git a/packages/sdk-components-react-remix/src/form.ws.tsx b/packages/sdk-components-react-remix/src/form.ws.tsx
index b1b74c9c82..28d847297a 100644
--- a/packages/sdk-components-react-remix/src/form.ws.tsx
+++ b/packages/sdk-components-react-remix/src/form.ws.tsx
@@ -42,6 +42,13 @@ export const meta: WsComponentMeta = {
name: "state",
dataSourceName: "formState",
},
+ {
+ type: "action",
+ name: "onStateChange",
+ value: [
+ { type: "execute", args: ["state"], code: `formState = state` },
+ ],
+ },
],
children: [
{