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.

refactor: access form element directly in variable popover (#3395)

Bogdan Chadkin14fd1efd88da
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index 2b158ae242..199ad8ab24 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -9,7 +9,6 @@ import {
useMemo,
useRef,
useState,
- type RefObject,
} from "react";
import { useStore } from "@nanostores/react";
import type { DataSource, Resource } from "@webstudio-is/sdk";
@@ -58,49 +57,6 @@ import {
} from "~/builder/shared/code-editor-base";
import { parseCurl, type CurlRequest } from "./curl";
-export type ComposedFields = {
- isValid: () => boolean;
- areAllErrorsVisible: () => boolean;
- showAllErrors: () => void;
-};
-
-export const composeWithNativeForm = (
- formAccessorRef: RefObject<HTMLInputElement>
-): ComposedFields => {
- return {
- isValid() {
- const formElement = formAccessorRef.current?.form;
- return formElement?.checkValidity() === true;
- },
- areAllErrorsVisible() {
- const formElement = formAccessorRef.current?.form;
- // check all errors in form fields are visible
- if (formElement) {
- for (const element of formElement.elements) {
- if (
- element instanceof HTMLInputElement ||
- element instanceof HTMLTextAreaElement
- ) {
- // field is invalid and the error is not visible
- if (
- element.validity.valid === false &&
- // rely on data-color=error convention in webstudio design system
- element.getAttribute("data-color") !== "error"
- ) {
- return false;
- }
- }
- }
- }
- return true;
- },
- showAllErrors() {
- const formElement = formAccessorRef.current?.form;
- formElement?.checkValidity();
- },
- };
-};
-
const validateUrl = (value: string, scope: Record<string, unknown>) => {
const evaluatedValue = evaluateExpressionWithinScope(value, scope);
if (typeof evaluatedValue !== "string") {
@@ -479,8 +435,8 @@ const useScope = ({ variable }: { variable?: DataSource }) => {
return { scope, aliases };
};
-type PanelApi = ComposedFields & {
- save: () => void;
+type PanelApi = {
+ save: (formData: FormData) => void;
};
const validateBody = (
@@ -623,15 +579,12 @@ export const ResourceForm = forwardRef<
? evaluateExpressionWithinScope(contentType, scope)
: undefined;
- const formAccessorRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
- ...composeWithNativeForm(formAccessorRef),
- save: () => {
+ save: (formData) => {
const instanceSelector = $selectedInstanceSelector.get();
if (instanceSelector === undefined) {
return;
}
- const formData = new FormData(formAccessorRef.current?.form ?? undefined);
const name = z.string().parse(formData.get("name"));
const [instanceId] = instanceSelector;
const newResource: Resource = {
@@ -662,7 +615,6 @@ export const ResourceForm = forwardRef<
return (
<>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
<UrlField
scope={scope}
aliases={aliases}
@@ -761,16 +713,12 @@ export const SystemResourceForm = forwardRef<
);
});
- const formAccessorRef = useRef<HTMLInputElement>(null);
-
useImperativeHandle(ref, () => ({
- ...composeWithNativeForm(formAccessorRef),
- save: () => {
+ save: (formData) => {
const instanceSelector = $selectedInstanceSelector.get();
if (instanceSelector === undefined) {
return;
}
- const formData = new FormData(formAccessorRef.current?.form ?? undefined);
const name = z.string().parse(formData.get("name"));
const [instanceId] = instanceSelector;
const newResource: Resource = {
@@ -803,7 +751,6 @@ export const SystemResourceForm = forwardRef<
return (
<>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
<Label htmlFor={resourceId}>Resource</Label>
<Select
@@ -872,16 +819,12 @@ export const GraphqlResourceForm = forwardRef<
setVariablesError("");
}, [variables, scope]);
- const formAccessorRef = useRef<HTMLInputElement>(null);
- const form = composeWithNativeForm(formAccessorRef);
useImperativeHandle(ref, () => ({
- ...form,
- save: () => {
+ save: (formData) => {
const instanceSelector = $selectedInstanceSelector.get();
if (instanceSelector === undefined) {
return;
}
- const formData = new FormData(formAccessorRef.current?.form ?? undefined);
const name = z.string().parse(formData.get("name"));
const body = generateObjectExpression(
new Map([
@@ -919,7 +862,6 @@ export const GraphqlResourceForm = forwardRef<
return (
<>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
<UrlField scope={scope} aliases={aliases} value={url} onChange={setUrl} />
<Grid gap={1}>
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index 8f2d62db42..ea368c6b77 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -66,8 +66,6 @@ import {
GraphqlResourceForm,
ResourceForm,
SystemResourceForm,
- composeWithNativeForm,
- type ComposedFields,
} from "./resource-panel";
import { generateCurl } from "./curl";
@@ -206,53 +204,41 @@ const TypeField = ({
);
};
-type PanelApi = ComposedFields & {
- save: () => void;
+type PanelApi = {
+ save: (formData: FormData) => void;
};
const ParameterForm = forwardRef<
undefined | PanelApi,
{ variable?: DataSource }
>(({ variable }, ref) => {
- const formAccessorRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
- ...composeWithNativeForm(formAccessorRef),
- save: () => {
+ save: (formData) => {
// only existing parameter variables can be renamed
if (variable === undefined) {
return;
}
- const formData = new FormData(formAccessorRef.current?.form ?? undefined);
const name = z.string().parse(formData.get("name"));
serverSyncStore.createTransaction([$dataSources], (dataSources) => {
dataSources.set(variable.id, { ...variable, name });
});
},
}));
- return (
- <>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
- </>
- );
+ return <></>;
});
ParameterForm.displayName = "ParameterForm";
const useValuePanelRef = ({
ref,
variable,
- form,
- formAccessorRef,
variableValue,
}: {
ref: Ref<undefined | PanelApi>;
variable?: DataSource;
- form: ComposedFields;
- formAccessorRef: RefObject<HTMLInputElement>;
variableValue: Extract<DataSource, { type: "variable" }>["value"];
}) => {
useImperativeHandle(ref, () => ({
- ...form,
- save: () => {
+ save: (formData) => {
const instanceSelector = $selectedInstanceSelector.get();
if (instanceSelector === undefined) {
return;
@@ -261,7 +247,6 @@ const useValuePanelRef = ({
const dataSourceId = variable?.id ?? nanoid();
// preserve existing instance scope when edit
const scopeInstanceId = variable?.scopeInstanceId ?? instanceId;
- const formData = new FormData(formAccessorRef.current?.form ?? undefined);
const name = z.string().parse(formData.get("name"));
serverSyncStore.createTransaction(
[$dataSources, $resources],
@@ -294,18 +279,14 @@ const StringForm = forwardRef<
? variable.value.value
: ""
);
- const formAccessorRef = useRef<HTMLInputElement>(null);
useValuePanelRef({
ref,
variable,
- form: composeWithNativeForm(formAccessorRef),
- formAccessorRef,
variableValue: { type: "string", value },
});
const valueId = useId();
return (
<>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
<Label htmlFor={valueId}>Value</Label>
<EditorDialogControl>
@@ -363,18 +344,14 @@ const NumberForm = forwardRef<
valueRef.current?.setCustomValidity(validateNumberValue(value));
setValueError("");
}, [value]);
- const formAccessorRef = useRef<HTMLInputElement>(null);
useValuePanelRef({
ref,
variable,
- form: composeWithNativeForm(formAccessorRef),
- formAccessorRef,
variableValue: { type: "number", value: Number(value) },
});
const valueId = useId();
return (
<>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
<Label htmlFor={valueId}>Value</Label>
<InputErrorsTooltip errors={valueError ? [valueError] : undefined}>
@@ -409,18 +386,14 @@ const BooleanForm = forwardRef<
? variable.value.value
: false
);
- const formAccessorRef = useRef<HTMLInputElement>(null);
useValuePanelRef({
ref,
variable,
- form: composeWithNativeForm(formAccessorRef),
- formAccessorRef,
variableValue: { type: "boolean", value },
});
const valueId = useId();
return (
<>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
<Label htmlFor={valueId}>Value</Label>
<Switch
@@ -468,12 +441,9 @@ const JsonForm = forwardRef<
valueRef.current?.setCustomValidity(validateJsonValue(value));
setValueError("");
}, [value]);
- const formAccessorRef = useRef<HTMLInputElement>(null);
useValuePanelRef({
ref,
variable,
- form: composeWithNativeForm(formAccessorRef),
- formAccessorRef,
variableValue: {
type: "json",
value: parseJsonValue(value),
@@ -481,7 +451,6 @@ const JsonForm = forwardRef<
});
return (
<>
- <input ref={formAccessorRef} type="hidden" name="form-accessor" />
<input
ref={valueRef}
style={{ display: "none" }}
@@ -629,6 +598,29 @@ const VariablePopoverContext = createContext<{
export const VariablePopoverProvider = VariablePopoverContext.Provider;
+const areAllFormErrorsVisible = (form: null | HTMLFormElement) => {
+ if (form === null) {
+ return true;
+ }
+ // check all errors in form fields are visible
+ for (const element of form.elements) {
+ if (
+ element instanceof HTMLInputElement ||
+ element instanceof HTMLTextAreaElement
+ ) {
+ // field is invalid and the error is not visible
+ if (
+ element.validity.valid === false &&
+ // rely on data-color=error convention in webstudio design system
+ element.getAttribute("data-color") !== "error"
+ ) {
+ return false;
+ }
+ }
+ }
+ return true;
+};
+
export const VariablePopoverTrigger = forwardRef<
HTMLButtonElement,
{ variable?: DataSource; children: ReactNode }
@@ -639,30 +631,26 @@ export const VariablePopoverTrigger = forwardRef<
const [triggerRef, sideOffsset] = useSideOffset({ isOpen, containerRef });
const bindingPopoverContainerRef = useRef<HTMLDivElement>(null);
const panelRef = useRef<undefined | PanelApi>();
+ const formRef = useRef<HTMLFormElement>(null);
const resources = useStore($resources);
- const saveAndClose = () => {
- if (panelRef.current) {
- if (panelRef.current.areAllErrorsVisible() === false) {
- panelRef.current.showAllErrors();
- return;
- }
- if (panelRef.current.isValid()) {
- panelRef.current.save();
- }
- }
- setOpen(false);
- };
return (
<FloatingPanelPopover
modal
open={isOpen}
onOpenChange={(newOpen) => {
- if (newOpen === false) {
- saveAndClose();
+ if (newOpen) {
+ setOpen(true);
return;
}
- setOpen(newOpen);
+ // attempt to save form on close
+ if (areAllFormErrorsVisible(formRef.current)) {
+ formRef.current?.requestSubmit();
+ setOpen(false);
+ } else {
+ formRef.current?.checkValidity();
+ // prevent closing when not all errors are shown to user
+ }
}}
>
<FloatingPanelPopoverTrigger ref={mergeRefs(ref, triggerRef)} asChild>
@@ -693,16 +681,20 @@ export const VariablePopoverTrigger = forwardRef<
}}
>
<form
+ ref={formRef}
noValidate={true}
// exclude from the flow
style={{ display: "contents" }}
onSubmit={(event) => {
event.preventDefault();
- saveAndClose();
+ if (event.currentTarget.checkValidity()) {
+ const formData = new FormData(event.currentTarget);
+ panelRef.current?.save(formData);
+ }
}}
>
{/* submit is not triggered when press enter on input without submit button */}
- <button style={{ display: "none" }}>submit</button>
+ <button hidden></button>
<BindingPopoverProvider
value={{ containerRef: bindingPopoverContainerRef }}
>
@@ -750,18 +742,10 @@ export const VariablePopoverTrigger = forwardRef<
color="ghost"
disabled={areResourcesLoading}
onClick={() => {
- if (panelRef.current) {
- if (
- panelRef.current.areAllErrorsVisible() === false
- ) {
- panelRef.current.showAllErrors();
- return;
- }
- if (panelRef.current.isValid()) {
- panelRef.current.save();
- }
+ formRef.current?.requestSubmit();
+ if (formRef.current?.checkValidity()) {
+ invalidateResource(variable.resourceId);
}
- invalidateResource(variable.resourceId);
}}
/>
</Tooltip>