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.

feat: load data before saving resource variable (#5392)

Bogdan Chadkinf5583118971a
diff --git a/apps/builder/app/builder/features/pages/page-utils.test.ts b/apps/builder/app/builder/features/pages/page-utils.test.ts
index 57424ff8cc..188f5e6807 100644
--- a/apps/builder/app/builder/features/pages/page-utils.test.ts
+++ b/apps/builder/app/builder/features/pages/page-utils.test.ts
@@ -7,6 +7,7 @@ import {
ROOT_FOLDER_ID,
type Page,
SYSTEM_VARIABLE_ID,
+ Resource,
} from "@webstudio-is/sdk";
import {
cleanupChildRefsMutable,
@@ -23,11 +24,12 @@ import {
$dataSourceVariables,
$dataSources,
$pages,
- $resourceValues,
+ $resources,
} from "~/shared/nano-states";
import { registerContainers } from "~/shared/sync";
import { $awareness } from "~/shared/awareness";
import { updateCurrentSystem } from "~/shared/system";
+import { $resourcesCache, getResourceKey } from "~/shared/resources";
setEnv("*");
registerContainers();
@@ -521,7 +523,25 @@ test("page root scope should use variable and resource values", () => {
$dataSourceVariables.set(
new Map([["valueVariableId", "value variable value"]])
);
- $resourceValues.set(new Map([["resourceId", "resource variable value"]]));
+ const resourceKey = getResourceKey({
+ name: "my-resource",
+ url: "",
+ searchParams: [],
+ method: "get",
+ headers: [],
+ });
+ $resources.set(
+ toMap<Resource>([
+ {
+ id: "resourceId",
+ name: "my-resource",
+ url: `""`,
+ method: "get",
+ headers: [],
+ },
+ ])
+ );
+ $resourcesCache.set(new Map([[resourceKey, "resource variable value"]]));
expect($pageRootScope.get()).toEqual({
aliases: new Map([
["$ws$system", "system"],
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 1f32e44cd5..dbbf64c29b 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -75,7 +75,7 @@ export const parseResource = ({
formData,
}: {
id: string;
- name: string;
+ name?: string;
formData: FormData;
}) => {
const searchParamNames = formData.getAll("search-param-name") as string[];
@@ -84,7 +84,7 @@ export const parseResource = ({
const headerValues = formData.getAll("header-value") as string[];
return Resource.parse({
id,
- name,
+ name: name ?? formData.get("name"),
url: formData.get("url"),
searchParams: searchParamNames
.map((name, index) => ({ name, value: searchParamValues[index] }))
@@ -175,17 +175,21 @@ export const UrlField = ({
}
try {
const url = new URL(value);
- const searchParams: Resource["searchParams"] = [];
- for (const [name, value] of url.searchParams) {
- searchParams.push({ name, value: JSON.stringify(value) });
+ if (url.searchParams.size > 0) {
+ const searchParams: Resource["searchParams"] = [];
+ for (const [name, value] of url.searchParams) {
+ searchParams.push({ name, value: JSON.stringify(value) });
+ }
+ // remove all search params from url
+ url.search = "";
+ // update text value as string literal
+ onChange(JSON.stringify(url.href), searchParams);
+ return;
}
- // remove all search params from url
- url.search = "";
- // update text value as string literal
- onChange(JSON.stringify(url.href), searchParams);
} catch {
- onChange(JSON.stringify(value));
+ // serialize without changes when url is invalid
}
+ onChange(JSON.stringify(value));
}}
onBlur={(event) => event.currentTarget.checkValidity()}
onInvalid={(event) =>
@@ -515,9 +519,9 @@ export const getResourceScopeForInstance = ({
}
if (dataSource) {
const name = encodeDataVariableId(dataSourceId);
- variableValues.set(dataSourceId, value);
scope[name] = value;
aliases.set(name, dataSource.name);
+ variableValues.set(dataSource.name, value);
}
}
}
@@ -544,7 +548,7 @@ const getVariableInstanceKey = ({
return getInstanceKey(instancePath[0].instanceSelector);
};
-const useScope = ({ variable }: { variable?: DataSource }) => {
+export const useResourceScope = ({ variable }: { variable?: DataSource }) => {
return useStore(
useMemo(
() =>
@@ -561,22 +565,32 @@ const useScope = ({ variable }: { variable?: DataSource }) => {
variableValuesByInstanceSelector,
dataSources
) => {
- const { scope, aliases } = getResourceScopeForInstance({
- page,
- instanceKey: getVariableInstanceKey({
- variable,
- instancePath,
- }),
- dataSources,
- variableValuesByInstanceSelector,
- });
+ const { scope, aliases, variableValues } =
+ getResourceScopeForInstance({
+ page,
+ instanceKey: getVariableInstanceKey({
+ variable,
+ instancePath,
+ }),
+ dataSources,
+ variableValuesByInstanceSelector,
+ });
// prevent showing currently edited variable in suggestions
// to avoid cirular dependeny
const newScope = { ...scope };
+ const newAliases = new Map(aliases);
+ const newVariableValues = new Map(variableValues);
if (variable) {
- delete newScope[encodeDataVariableId(variable.id)];
+ const key = encodeDataVariableId(variable.id);
+ delete newScope[key];
+ newAliases.delete(key);
+ newVariableValues.delete(variable.name);
}
- return { scope: newScope, aliases };
+ return {
+ scope: newScope,
+ aliases: newAliases,
+ variableValues: newVariableValues,
+ };
}
),
[variable]
@@ -706,7 +720,7 @@ export const ResourceForm = forwardRef<
undefined | PanelApi,
{ variable?: DataSource }
>(({ variable }, ref) => {
- const { scope, aliases } = useScope({ variable });
+ const { scope, aliases } = useResourceScope({ variable });
const resources = useStore($resources);
const resource =
@@ -739,16 +753,14 @@ export const ResourceForm = forwardRef<
if (scopeInstanceId === undefined) {
return;
}
- const name = z.string().parse(formData.get("name"));
const newResource = parseResource({
id: resource?.id ?? nanoid(),
- name,
formData,
});
const newVariable: DataSource = {
id: variable?.id ?? nanoid(),
scopeInstanceId,
- name,
+ name: newResource.name,
type: "resource",
resourceId: newResource.id,
};
@@ -942,7 +954,7 @@ export const GraphqlResourceForm = forwardRef<
undefined | PanelApi,
{ variable?: DataSource }
>(({ variable }, ref) => {
- const { scope, aliases } = useScope({ variable });
+ const { scope, aliases } = useResourceScope({ variable });
const resources = useStore($resources);
const resource =
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 a692f59950..df3400bc9e 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -12,7 +12,6 @@ import {
useState,
useImperativeHandle,
useRef,
- createContext,
useEffect,
useCallback,
useMemo,
@@ -48,6 +47,7 @@ import {
transpileExpression,
lintExpression,
SYSTEM_VARIABLE_ID,
+ ResourceRequest,
} from "@webstudio-is/sdk";
import {
ExpressionEditor,
@@ -56,9 +56,6 @@ import {
import {
$dataSources,
$resources,
- $areResourcesLoading,
- invalidateResource,
- getComputedResourceRequest,
$userPlanFeatures,
$instances,
$props,
@@ -68,7 +65,6 @@ import {
$selectedInstance,
$selectedInstanceKeyWithRoot,
} from "~/shared/awareness";
-import { BindingPopoverProvider } from "~/builder/shared/binding-popover";
import {
EditorContent,
EditorDialog,
@@ -83,10 +79,19 @@ import {
} from "~/shared/data-variables";
import {
GraphqlResourceForm,
+ parseResource,
ResourceForm,
SystemResourceForm,
+ useResourceScope,
} from "./resource-panel";
import { generateCurl } from "./curl";
+import {
+ $hasPendingResources,
+ $resourcesCache,
+ computeResourceRequest,
+ getResourceKey,
+ invalidateResource,
+} from "~/shared/resources";
const NameField = ({
variable,
@@ -103,7 +108,7 @@ const NameField = ({
// validate same name on variable instance
// and fallback to selected instance for new variables
const scopeInstanceId =
- variable?.scopeInstanceId ?? $selectedInstance.get();
+ variable?.scopeInstanceId ?? $selectedInstance.get()?.id;
for (const dataSource of $dataSources.get().values()) {
if (
dataSource.scopeInstanceId === scopeInstanceId &&
@@ -308,42 +313,59 @@ const ParameterForm = forwardRef<
});
ParameterForm.displayName = "ParameterForm";
+const saveVariable = (variable: undefined | DataSource, formData: FormData) => {
+ const dataSourceId = variable?.id ?? nanoid();
+ // preserve existing instance scope when edit
+ const scopeInstanceId =
+ variable?.scopeInstanceId ?? $selectedInstance.get()?.id;
+ if (scopeInstanceId === undefined) {
+ return;
+ }
+ const type = z.string().parse(formData.get("type"));
+ const name = z.string().parse(formData.get("name"));
+ const value = z.string().nullable().parse(formData.get("value"));
+ let variableValue: Extract<DataSource, { type: "variable" }>["value"];
+ if (type === "string") {
+ variableValue = { type: "string", value: value ?? "" };
+ } else if (type === "number") {
+ variableValue = { type: "number", value: Number(value || 0) };
+ } else if (type === "boolean") {
+ variableValue = { type: "boolean", value: value != null };
+ } else {
+ variableValue = {
+ type: "json",
+ value: value ? parseJsonValue(value) : undefined,
+ };
+ }
+ updateWebstudioData((data) => {
+ // cleanup resource when value variable is set
+ if (variable?.type === "resource") {
+ data.resources.delete(variable.resourceId);
+ }
+ data.dataSources.set(dataSourceId, {
+ id: dataSourceId,
+ scopeInstanceId,
+ name,
+ type: "variable",
+ value: variableValue,
+ });
+ rebindTreeVariablesMutable({
+ startingInstanceId: scopeInstanceId,
+ ...data,
+ });
+ });
+};
+
const useValuePanelRef = ({
ref,
variable,
- variableValue,
}: {
ref: Ref<undefined | PanelApi>;
variable?: DataSource;
- variableValue: Extract<DataSource, { type: "variable" }>["value"];
}) => {
useImperativeHandle(ref, () => ({
save: (formData) => {
- const dataSourceId = variable?.id ?? nanoid();
- // preserve existing instance scope when edit
- const scopeInstanceId =
- variable?.scopeInstanceId ?? $selectedInstance.get()?.id;
- if (scopeInstanceId === undefined) {
- return;
- }
- const name = z.string().parse(formData.get("name"));
- updateWebstudioData((data) => {
- // cleanup resource when value variable is set
- if (variable?.type === "resource") {
- data.resources.delete(variable.resourceId);
- }
- data.dataSources.set(dataSourceId, {
- id: dataSourceId,
- scopeInstanceId,
- name,
- type: "variable",
- value: variableValue,
- });
- rebindTreeVariablesMutable({
- startingInstanceId: scopeInstanceId,
- ...data,
- });
- });
+ saveVariable(variable, formData);
},
}));
};
@@ -352,49 +374,41 @@ const StringForm = forwardRef<
undefined | PanelApi,
{
variable?: DataSource;
+ value: unknown;
+ onChange: (value: unknown) => void;
}
->(({ variable }, ref) => {
- const [value, setValue] = useState(
- variable?.type === "variable" && variable.value.type === "string"
- ? variable.value.value
- : ""
- );
- useValuePanelRef({
- ref,
- variable,
- variableValue: { type: "string", value },
- });
+>(({ variable, value: unknownValue, onChange }, ref) => {
+ const value = typeof unknownValue === "string" ? unknownValue : "";
+ useValuePanelRef({ ref, variable });
const valueId = useId();
return (
- <>
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label htmlFor={valueId}>Value</Label>
- <EditorDialogControl>
- <TextArea
- name="value"
- rows={1}
- maxRows={10}
- autoGrow={true}
- id={valueId}
- value={value}
- onChange={setValue}
- />
- <EditorDialog
- title="Variable value"
- content={
- <TextArea
- grow={true}
- id={valueId}
- value={value}
- onChange={setValue}
- />
- }
- >
- <EditorDialogButton />
- </EditorDialog>
- </EditorDialogControl>
- </Flex>
- </>
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label htmlFor={valueId}>Value</Label>
+ <EditorDialogControl>
+ <TextArea
+ name="value"
+ rows={1}
+ maxRows={10}
+ autoGrow={true}
+ id={valueId}
+ value={value}
+ onChange={onChange}
+ />
+ <EditorDialog
+ title="Variable value"
+ content={
+ <TextArea
+ grow={true}
+ id={valueId}
+ value={value}
+ onChange={onChange}
+ />
+ }
+ >
+ <EditorDialogButton />
+ </EditorDialog>
+ </EditorDialogControl>
+ </Flex>
);
});
StringForm.displayName = "StringForm";
@@ -411,24 +425,21 @@ const NumberForm = forwardRef<
undefined | PanelApi,
{
variable?: DataSource;
+ value: unknown;
+ onChange: (value: unknown) => void;
}
->(({ variable }, ref) => {
- const [value, setValue] = useState(
- variable?.type === "variable" && variable.value.type === "number"
- ? variable.value.value
- : ""
- );
+>(({ variable, value: unknownValue, onChange }, ref) => {
+ const value =
+ typeof unknownValue === "number" || typeof unknownValue === "string"
+ ? unknownValue
+ : "";
const [valueError, setValueError] = useState("");
const valueRef = useRef<HTMLInputElement>(null);
useEffect(() => {
valueRef.current?.setCustomValidity(validateNumberValue(value));
setValueError("");
}, [value]);
- useValuePanelRef({
- ref,
- variable,
- variableValue: { type: "number", value: Number(value) },
- });
+ useValuePanelRef({ ref, variable });
const valueId = useId();
return (
<>
@@ -442,7 +453,7 @@ const NumberForm = forwardRef<
inputMode="numeric"
color={valueError ? "error" : undefined}
value={value}
- onChange={(event) => setValue(event.target.value)}
+ onChange={(event) => onChange(event.target.value)}
onBlur={() => valueRef.current?.checkValidity()}
onInvalid={(event) =>
setValueError(event.currentTarget.validationMessage)
@@ -459,18 +470,12 @@ const BooleanForm = forwardRef<
undefined | PanelApi,
{
variable?: DataSource;
+ value: unknown;
+ onChange: (value: unknown) => void;
}
->(({ variable }, ref) => {
- const [value, setValue] = useState(
- variable?.type === "variable" && variable.value.type === "boolean"
- ? variable.value.value
- : false
- );
- useValuePanelRef({
- ref,
- variable,
- variableValue: { type: "boolean", value },
- });
+>(({ variable, value: unknownValue, onChange }, ref) => {
+ const value = typeof unknownValue === "boolean" ? unknownValue : false;
+ useValuePanelRef({ ref, variable });
const valueId = useId();
return (
<>
@@ -478,9 +483,10 @@ const BooleanForm = forwardRef<
<Label htmlFor={valueId}>Value</Label>
<Switch
name="value"
+ value="on"
id={valueId}
checked={value}
- onCheckedChange={setValue}
+ onCheckedChange={onChange}
/>
</Flex>
</>
@@ -508,28 +514,18 @@ const JsonForm = forwardRef<
undefined | PanelApi,
{
variable?: DataSource;
+ value: unknown;
+ onChange: (value: unknown) => void;
}
->(({ variable }, ref) => {
- const [value, setValue] = useState<string>(
- variable?.type === "variable" &&
- (variable.value.type === "json" || variable.value.type === "string[]")
- ? formatValue(variable.value.value)
- : ``
- );
+>(({ variable, value: unknownValue, onChange }, ref) => {
+ const value = typeof unknownValue === "string" ? unknownValue : "";
const [valueError, setValueError] = useState("");
const valueRef = useRef<HTMLInputElement>(null);
useEffect(() => {
valueRef.current?.setCustomValidity(validateJsonValue(value));
setValueError("");
}, [value]);
- useValuePanelRef({
- ref,
- variable,
- variableValue: {
- type: "json",
- value: parseJsonValue(value),
- },
- });
+ useValuePanelRef({ ref, variable });
return (
<>
<input
@@ -548,7 +544,7 @@ const JsonForm = forwardRef<
<ExpressionEditor
color={valueError ? "error" : undefined}
value={value}
- onChange={setValue}
+ onChange={onChange}
onChangeComplete={() => valueRef.current?.checkValidity()}
/>
</Flex>
@@ -557,13 +553,225 @@ const JsonForm = forwardRef<
});
JsonForm.displayName = "JsonForm";
-const VariablePanel = forwardRef<
+const VariablePanelForm = forwardRef<
undefined | PanelApi,
- { variable?: DataSource }
->(({ variable }, ref) => {
+ {
+ variable?: DataSource;
+ variableType: VariableType;
+ onVariableTypeChange: (variableType: VariableType) => void;
+ value: unknown;
+ onValueChange: (value: unknown) => void;
+ }
+>(
+ (
+ { variable, variableType, onVariableTypeChange, value, onValueChange },
+ ref
+ ) => {
+ const { allowDynamicData } = useStore($userPlanFeatures);
+
+ const isResource =
+ variableType === "resource" ||
+ variableType === "graphql-resource" ||
+ variableType === "system-resource";
+ const requiresUpgrade = allowDynamicData === false && isResource;
+ return (
+ <>
+ {requiresUpgrade && (
+ <PanelBanner>
+ <Text>Resource fetching is part of the CMS functionality.</Text>
+ <Flex align="center" gap={1}>
+ <UpgradeIcon />
+ <Link
+ color="inherit"
+ target="_blank"
+ href="https://webstudio.is/pricing"
+ >
+ Upgrade to Pro
+ </Link>
+ </Flex>
+ </PanelBanner>
+ )}
+ <Flex
+ direction="column"
+ css={{
+ overflow: "hidden",
+ padding: theme.panel.padding,
+ gap: theme.spacing[7],
+ }}
+ >
+ <NameField variable={variable} defaultValue={variable?.name ?? ""} />
+ {variableType !== "parameter" && (
+ <TypeField value={variableType} onChange={onVariableTypeChange} />
+ )}
+ {variableType === "parameter" && (
+ <ParameterForm ref={ref} variable={variable} />
+ )}
+ {variableType === "string" && (
+ <StringForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ )}
+ {variableType === "number" && (
+ <NumberForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ )}
+ {variableType === "boolean" && (
+ <BooleanForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ )}
+ {variableType === "json" && (
+ <JsonForm
+ ref={ref}
+ variable={variable}
+ value={value}
+ onChange={onValueChange}
+ />
+ )}
+ {variableType === "resource" && (
+ <ResourceForm ref={ref} variable={variable} />
+ )}
+ {variableType === "graphql-resource" && (
+ <GraphqlResourceForm ref={ref} variable={variable} />
+ )}
+ {variableType === "system-resource" && (
+ <SystemResourceForm ref={ref} variable={variable} />
+ )}
+ </Flex>
+ </>
+ );
+ }
+);
+VariablePanelForm.displayName = "VariableForm";
+
+const $instanceVariableValues = computed(
+ [$selectedInstanceKeyWithRoot, $variableValuesByInstanceSelector],
+ (instanceKey, variableValuesByInstanceSelector) =>
+ variableValuesByInstanceSelector.get(instanceKey ?? "") ??
+ new Map<string, unknown>()
+);
+
+const VariablePreview = ({
+ variable,
+ variableType,
+ variableValue,
+ onLoadData,
+}: {
+ variable?: DataSource;
+ variableType: VariableType;
+ variableValue: unknown;
+ onLoadData: () => void;
+}) => {
+ const isResource =
+ variableType === "resource" ||
+ variableType === "graphql-resource" ||
+ variableType === "system-resource";
+ const hasPendingResources = useStore($hasPendingResources);
const resources = useStore($resources);
- const { allowDynamicData } = useStore($userPlanFeatures);
+ const variableValues = useStore($instanceVariableValues);
+ const resourcesCache = useStore($resourcesCache);
+ const resourceScope = useResourceScope({ variable });
+ let computedValue: unknown;
+ if (variableType === "string" || variableType === "boolean") {
+ computedValue = variableValue;
+ } else if (variableType === "json") {
+ computedValue = parseJsonValue(String(variableValue));
+ } else if (variableType === "number") {
+ computedValue = Number(variableValue);
+ if (Number.isNaN(computedValue)) {
+ computedValue = variableValue;
+ }
+ } else if (variableType === "parameter") {
+ computedValue = variable ? variableValues.get(variable.id) : undefined;
+ } else {
+ // try to load current resource or saved one
+ let resourceRequest = ResourceRequest.safeParse(variableValue).data;
+ if (!resourceRequest && variable?.type === "resource") {
+ const resource = resources.get(variable.resourceId);
+ if (resource) {
+ resourceRequest = computeResourceRequest(
+ resource,
+ resourceScope.variableValues
+ );
+ }
+ }
+ if (resourceRequest) {
+ computedValue = resourcesCache.get(getResourceKey(resourceRequest));
+ }
+ }
+ const extensions = useMemo(() => [javascript({}), foldGutterExtension], []);
+ const editorProps = {
+ readOnly: true,
+ extensions,
+ // compute value as json lazily only when dialog is open
+ // by spliting into separate component which is invoked
+ // only when dialog content is rendered
+ value: formatValue(computedValue),
+ onChange: () => {},
+ onChangeComplete: () => {},
+ };
+ return (
+ <Grid
+ align="stretch"
+ css={{
+ height: "100%",
+ overflow: "hidden",
+ boxSizing: "content-box",
+ position: "relative",
+ }}
+ >
+ <EditorContent {...editorProps} />
+ {isResource && !computedValue && (
+ <Flex
+ justify="center"
+ align="center"
+ css={{ position: "absolute", inset: 0 }}
+ >
+ <Button
+ color="neutral"
+ disabled={hasPendingResources}
+ onClick={onLoadData}
+ >
+ {hasPendingResources ? "Loading..." : "Load data"}
+ </Button>
+ </Flex>
+ )}
+ </Grid>
+ );
+};
+
+const VariablePopoverContent = ({
+ formRef,
+ variable,
+ onClose,
+}: {
+ formRef: RefObject<HTMLFormElement>;
+ variable?: DataSource;
+ onClose: () => void;
+}) => {
+ const hasPendingResources = useStore($hasPendingResources);
+ const panelRef = useRef<undefined | PanelApi>(undefined);
+ const isSystemVariable = variable?.id === SYSTEM_VARIABLE_ID;
+ const [value, setValue] = useState<unknown>(() => {
+ if (variable?.type === "variable") {
+ if (variable.value.type === "json") {
+ return formatValue(variable.value.value);
+ }
+ return variable.value.value;
+ }
+ });
+ const resources = useStore($resources);
const [variableType, setVariableType] = useState<VariableType>(() => {
if (variable?.type === "resource") {
const resource = resources.get(variable.resourceId);
@@ -588,111 +796,158 @@ const VariablePanel = forwardRef<
return "string";
});
- let fields: ReactNode;
- if (variableType === "parameter") {
- fields = <ParameterForm ref={ref} variable={variable} />;
- }
- if (variableType === "string") {
- fields = (
- <>
- <TypeField value={variableType} onChange={setVariableType} />
- <StringForm ref={ref} variable={variable} />
- </>
- );
- }
- if (variableType === "number") {
- fields = (
- <>
- <TypeField value={variableType} onChange={setVariableType} />
- <NumberForm ref={ref} variable={variable} />
- </>
- );
- }
- if (variableType === "boolean") {
- fields = (
- <>
- <TypeField value={variableType} onChange={setVariableType} />
- <BooleanForm ref={ref} variable={variable} />
- </>
- );
- }
- if (variableType === "json") {
- fields = (
- <>
- <TypeField value={variableType} onChange={setVariableType} />
- <JsonForm ref={ref} variable={variable} />
- </>
- );
- }
+ const updateVariableType = (variableType: VariableType) => {
+ setVariableType(variableType);
+ setValue((prev: unknown) => {
+ if (variableType === "string" && typeof prev !== "string") {
+ return "";
+ }
+ if (variableType === "number" && typeof prev !== "number") {
+ return "";
+ }
+ if (variableType === "boolean" && typeof prev !== "boolean") {
+ return false;
+ }
+ if (variableType === "json") {
+ // empty string gives an error
+ return prev || "{}";
+ }
+ return prev;
+ });
+ };
- if (variableType === "resource") {
- fields = (
- <>
- <TypeField value={variableType} onChange={setVariableType} />
- <ResourceForm ref={ref} variable={variable} />
- </>
- );
- }
- if (variableType === "graphql-resource") {
- fields = (
- <>
- <TypeField value={variableType} onChange={setVariableType} />
- <GraphqlResourceForm ref={ref} variable={variable} />
- </>
+ const resourceScope = useResourceScope({ variable });
+
+ const reloadData = () => {
+ const formData = new FormData(formRef.current ?? undefined);
+ const resource = parseResource({
+ id: variable?.id ?? "new",
+ formData,
+ });
+ const resourceRequest = computeResourceRequest(
+ resource,
+ resourceScope.variableValues
);
- }
- if (variableType === "system-resource") {
- fields = (
- <>
- <TypeField value={variableType} onChange={setVariableType} />
- <SystemResourceForm ref={ref} variable={variable} />
- </>
+ invalidateResource(resourceRequest);
+ setValue(resourceRequest);
+ };
+
+ const copyAsCurl = () => {
+ const formData = new FormData(formRef.current ?? undefined);
+ const resource = parseResource({
+ id: variable?.id ?? "new",
+ formData,
+ });
+ const resourceRequest = computeResourceRequest(
+ resource,
+ resourceScope.variableValues
);
- }
+ navigator.clipboard.writeText(generateCurl(resourceRequest));
+ };
- const isResource =
- variableType === "resource" ||
- variableType === "graphql-resource" ||
- variableType === "system-resource";
- const requiresUpgrade = allowDynamicData === false && isResource;
return (
<>
- {requiresUpgrade && (
- <PanelBanner>
- <Text>Resource fetching is part of the CMS functionality.</Text>
- <Flex align="center" gap={1}>
- <UpgradeIcon />
- <Link
- color="inherit"
- target="_blank"
- href="https://webstudio.is/pricing"
- >
- Upgrade to Pro
- </Link>
- </Flex>
- </PanelBanner>
- )}
- <Flex
- direction="column"
+ <Grid
css={{
- overflow: "hidden",
- padding: theme.panel.padding,
- gap: theme.spacing[7],
+ height: "100%",
+ gridTemplateColumns: "320px 1fr",
}}
>
- <NameField variable={variable} defaultValue={variable?.name ?? ""} />
- {fields}
- </Flex>
+ <ScrollArea
+ // flex fixes content overflowing artificial scroll area
+ css={{ display: "flex", flexDirection: "column" }}
+ >
+ <form
+ ref={formRef}
+ noValidate={true}
+ // exclude from the flow
+ style={{ display: "contents" }}
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (isSystemVariable) {
+ return;
+ }
+ const nameElement =
+ event.currentTarget.elements.namedItem("name");
+ // make sure only name is valid and allow to save everything else
+ // to avoid loosing complex configuration when closed accidentally
+ if (
+ nameElement instanceof HTMLInputElement &&
+ nameElement.checkValidity()
+ ) {
+ const formData = new FormData(event.currentTarget);
+ panelRef.current?.save(formData);
+ // close popover whenever new variable is created
+ // to prevent creating duplicated variable
+ if (variable === undefined) {
+ onClose();
+ }
+ }
+ }}
+ >
+ {/* submit is not triggered when press enter on input without submit button */}
+ <button hidden></button>
+ <fieldset
+ style={{ display: "contents" }}
+ // forbid editing system variable
+ disabled={isSystemVariable}
+ >
+ <VariablePanelForm
+ ref={panelRef}
+ variable={variable}
+ variableType={variableType}
+ onVariableTypeChange={updateVariableType}
+ value={value}
+ onValueChange={setValue}
+ />
+ </fieldset>
+ </form>
+ </ScrollArea>
+ <VariablePreview
+ variable={variable}
+ variableType={variableType}
+ variableValue={value}
+ onLoadData={reloadData}
+ />
+ </Grid>
+
+ <DialogTitle
+ suffix={
+ <DialogTitleActions>
+ {(variableType === "resource" ||
+ variableType === "graphql-resource") && (
+ <Tooltip content="Copy resource as cURL command" side="bottom">
+ <Button
+ aria-label="Copy resource as cURL command"
+ prefix={<CopyIcon />}
+ color="ghost"
+ onClick={copyAsCurl}
+ />
+ </Tooltip>
+ )}
+ {(variableType === "resource" ||
+ variableType === "graphql-resource" ||
+ variableType === "system-resource") && (
+ <Tooltip content="Refresh resource data" side="bottom">
+ <Button
+ aria-label="Refresh resource data"
+ prefix={<RefreshIcon />}
+ color="ghost"
+ disabled={hasPendingResources}
+ onClick={reloadData}
+ />
+ </Tooltip>
+ )}
+ <DialogMaximize />
+ <DialogClose />
+ </DialogTitleActions>
+ }
+ >
+ {variable ? "Edit Variable" : "New Variable"}
+ </DialogTitle>
</>
);
-});
-VariablePanel.displayName = "VariableForm";
-
-const VariablePopoverContext = createContext<{
- containerRef?: RefObject<null | HTMLElement>;
-}>({});
-
-export const VariablePopoverProvider = VariablePopoverContext.Provider;
+};
const areAllFormErrorsVisible = (form: null | HTMLFormElement) => {
if (form === null) {
@@ -717,40 +972,6 @@ const areAllFormErrorsVisible = (form: null | HTMLFormElement) => {
return true;
};
-const $instanceVariableValues = computed(
- [$selectedInstanceKeyWithRoot, $variableValuesByInstanceSelector],
- (instanceKey, variableValuesByInstanceSelector) =>
- variableValuesByInstanceSelector.get(instanceKey ?? "") ??
- new Map<string, unknown>()
-);
-
-const VariablePreview = ({ variable }: { variable: DataSource }) => {
- const variableValues = useStore($instanceVariableValues);
- const extensions = useMemo(() => [javascript({}), foldGutterExtension], []);
- const editorProps = {
- readOnly: true,
- extensions,
- // compute value as json lazily only when dialog is open
- // by spliting into separate component which is invoked
- // only when dialog content is rendered
- value: JSON.stringify(variableValues.get(variable.id), null, 2),
- onChange: () => {},
- onChangeComplete: () => {},
- };
- return (
- <Grid
- align="stretch"
- css={{
- height: "100%",
- overflow: "hidden",
- boxSizing: "content-box",
- }}
- >
- <EditorContent {...editorProps} />
- </Grid>
- );
-};
-
export const VariablePopoverTrigger = ({
variable,
children,
@@ -758,18 +979,13 @@ export const VariablePopoverTrigger = ({
variable?: DataSource;
children: ReactNode;
}) => {
- const areResourcesLoading = useStore($areResourcesLoading);
const [isOpen, setOpen] = useState(false);
- const bindingPopoverContainerRef = useRef<HTMLDivElement>(null);
- const panelRef = useRef<undefined | PanelApi>(undefined);
const formRef = useRef<HTMLFormElement>(null);
- const resources = useStore($resources);
- const isSystemVariable = variable?.id === SYSTEM_VARIABLE_ID;
return (
<FloatingPanel
placement="center"
- width={variable ? 740 : 320}
+ width={740}
height={480}
open={isOpen}
onOpenChange={(newOpen) => {
@@ -786,120 +1002,13 @@ export const VariablePopoverTrigger = ({
// prevent closing when not all errors are shown to user
}
}}
- title={
- variable === undefined ? (
- <DialogTitle>New Variable</DialogTitle>
- ) : (
- <DialogTitle
- suffix={
- <DialogTitleActions>
- {variable?.type === "resource" && (
- <>
- {/* allow to copy curl only for default and graphql resource controls */}
- {resources.get(variable.resourceId)?.control !==
- "system" && (
- <Tooltip
- content="Copy resource as cURL command"
- side="bottom"
- >
- <Button
- aria-label="Copy resource as cURL command"
- prefix={<CopyIcon />}
- color="ghost"
- onClick={() => {
- const resourceRequest = getComputedResourceRequest(
- variable.resourceId
- );
- if (resourceRequest) {
- navigator.clipboard.writeText(
- generateCurl(resourceRequest)
- );
- }
- }}
- />
- </Tooltip>
- )}
- <Tooltip content="Refresh resource data" side="bottom">
- <Button
- aria-label="Refresh resource data"
- prefix={<RefreshIcon />}
- color="ghost"
- disabled={areResourcesLoading}
- onClick={() => {
- formRef.current?.requestSubmit();
- if (formRef.current?.checkValidity()) {
- invalidateResource(variable.resourceId);
- }
- }}
- />
- </Tooltip>
- </>
- )}
- <DialogMaximize />
- <DialogClose />
- </DialogTitleActions>
- }
- >
- Edit Variable
- </DialogTitle>
- )
- }
+ title={undefined}
content={
- <Grid
- css={{
- height: "100%",
- gridTemplateColumns: "320px 1fr",
- }}
- >
- <ScrollArea
- // flex fixes content overflowing artificial scroll area
- css={{ display: "flex", flexDirection: "column" }}
- >
- <form
- ref={formRef}
- noValidate={true}
- // exclude from the flow
- style={{ display: "contents" }}
- onSubmit={(event) => {
- event.preventDefault();
- if (isSystemVariable) {
- return;
- }
- const nameElement =
- event.currentTarget.elements.namedItem("name");
- // make sure only name is valid and allow to save everything else
- // to avoid loosing complex configuration when closed accidentally
- if (
- nameElement instanceof HTMLInputElement &&
- nameElement.checkValidity()
- ) {
- const formData = new FormData(event.currentTarget);
- panelRef.current?.save(formData);
- // close popover whenever new variable is created
- // to prevent creating duplicated variable
- if (variable === undefined) {
- setOpen(false);
- }
- }
- }}
- >
- {/* submit is not triggered when press enter on input without submit button */}
- <button hidden></button>
- <fieldset
- style={{ display: "contents" }}
- // forbid editing system variable
- disabled={isSystemVariable}
- >
- <BindingPopoverProvider
- value={{ containerRef: bindingPopoverContainerRef }}
- >
- <VariablePanel ref={panelRef} variable={variable} />
- </BindingPopoverProvider>
- </fieldset>
- </form>
- </ScrollArea>
- {variable && <VariablePreview variable={variable} />}
- </Grid>
+ <VariablePopoverContent
+ formRef={formRef}
+ variable={variable}
+ onClose={() => setOpen(false)}
+ />
}
>
{children}
diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
index 45bafa30e5..454bb0038d 100644
--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState } from "react";
+import { useState } from "react";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import {
@@ -40,10 +40,7 @@ import {
useOpenState,
} from "~/builder/shared/collapsible-section";
import { formatValuePreview } from "~/builder/shared/expression-editor";
-import {
- VariablePopoverProvider,
- VariablePopoverTrigger,
-} from "./variable-popover";
+import { VariablePopoverTrigger } from "./variable-popover";
import {
$selectedInstance,
$selectedInstanceKeyWithRoot,
@@ -289,40 +286,37 @@ const VariablesList = () => {
const label = "Data Variables";
export const VariablesSection = () => {
- const containerRef = useRef<HTMLDivElement>(null);
const [isOpen, setIsOpen] = useOpenState(label);
return (
- <VariablePopoverProvider value={{ containerRef }}>
- <CollapsibleSectionRoot
- label={label}
- fullWidth={true}
- isOpen={isOpen}
- onOpenChange={setIsOpen}
- trigger={
- <SectionTitle
- suffix={
- <VariablePopoverTrigger>
- <SectionTitleButton
- prefix={<PlusIcon />}
- // open panel when add new varable
- onClick={() => {
- if (isOpen === false) {
- setIsOpen(true);
- }
- }}
- />
- </VariablePopoverTrigger>
- }
- >
- <SectionTitleLabel>Data Variables</SectionTitleLabel>
- </SectionTitle>
- }
- >
- {/* prevent applyig gap to list items */}
- <div ref={containerRef}>
- <VariablesList />
- </div>
- </CollapsibleSectionRoot>
- </VariablePopoverProvider>
+ <CollapsibleSectionRoot
+ label={label}
+ fullWidth={true}
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ trigger={
+ <SectionTitle
+ suffix={
+ <VariablePopoverTrigger>
+ <SectionTitleButton
+ prefix={<PlusIcon />}
+ // open panel when add new varable
+ onClick={() => {
+ if (isOpen === false) {
+ setIsOpen(true);
+ }
+ }}
+ />
+ </VariablePopoverTrigger>
+ }
+ >
+ <SectionTitleLabel>Data Variables</SectionTitleLabel>
+ </SectionTitle>
+ }
+ >
+ {/* prevent applyig gap to list items */}
+ <div>
+ <VariablesList />
+ </div>
+ </CollapsibleSectionRoot>
);
};
diff --git a/apps/builder/app/builder/inspector.tsx b/apps/builder/app/builder/inspector.tsx
index 8a80c72355..590c8a2bd0 100644
--- a/apps/builder/app/builder/inspector.tsx
+++ b/apps/builder/app/builder/inspector.tsx
@@ -27,7 +27,6 @@ import {
} from "~/shared/nano-states";
import { NavigatorTree } from "~/builder/features/navigator";
import type { Settings } from "~/builder/shared/client-settings";
-import { BindingPopoverProvider } from "~/builder/shared/binding-popover";
import { $activeInspectorPanel } from "~/builder/shared/nano-states";
import {
$selectedInstance,
@@ -109,57 +108,72 @@ export const Inspector = ({ navigatorLayout }: InspectorProps) => {
skipDelayDuration={0}
>
<FloatingPanelProvider container={tabsRef}>
- <BindingPopoverProvider value={{ containerRef: tabsRef }}>
- <PanelTabs
- ref={tabsRef}
- value={
- availablePanels.has(activeInspectorPanel)
- ? activeInspectorPanel
- : Array.from(availablePanels)[0]
- }
- onValueChange={(panel) => {
- $activeInspectorPanel.set(panel as PanelName);
- }}
- asChild
- >
- <Flex direction="column">
- <PanelTabsList>
- {availablePanels.has("style") && (
- <Tooltip
- variant="wrapped"
- content={
- <Text>
- CSS for the selected instance&nbsp;&nbsp;
- <Kbd value={["S"]} color="moreSubtle" />
- </Text>
- }
- >
- <div>
- <PanelTabsTrigger value="style">Style</PanelTabsTrigger>
- </div>
- </Tooltip>
- )}
- {availablePanels.has("settings") && (
- <Tooltip
- variant="wrapped"
- content={
- <Text>
- Settings, properties and attributes of the selected
- instance&nbsp;&nbsp;
- <Kbd value={["D"]} color="moreSubtle" />
- </Text>
- }
- >
- <div>
- <PanelTabsTrigger value="settings">
- Settings
- </PanelTabsTrigger>
- </div>
- </Tooltip>
- )}
- </PanelTabsList>
- <Separator />
- <PanelTabsContent value="style" css={contentStyle} tabIndex={-1}>
+ <PanelTabs
+ ref={tabsRef}
+ value={
+ availablePanels.has(activeInspectorPanel)
+ ? activeInspectorPanel
+ : Array.from(availablePanels)[0]
+ }
+ onValueChange={(panel) => {
+ $activeInspectorPanel.set(panel as PanelName);
+ }}
+ asChild
+ >
+ <Flex direction="column">
+ <PanelTabsList>
+ {availablePanels.has("style") && (
+ <Tooltip
+ variant="wrapped"
+ content={
+ <Text>
+ CSS for the selected instance&nbsp;&nbsp;
+ <Kbd value={["S"]} color="moreSubtle" />
+ </Text>
+ }
+ >
+ <div>
+ <PanelTabsTrigger value="style">Style</PanelTabsTrigger>
+ </div>
+ </Tooltip>
+ )}
+ {availablePanels.has("settings") && (
+ <Tooltip
+ variant="wrapped"
+ content={
+ <Text>
+ Settings, properties and attributes of the selected
+ instance&nbsp;&nbsp;
+ <Kbd value={["D"]} color="moreSubtle" />
+ </Text>
+ }
+ >
+ <div>
+ <PanelTabsTrigger value="settings">
+ Settings
+ </PanelTabsTrigger>
+ </div>
+ </Tooltip>
+ )}
+ </PanelTabsList>
+ <Separator />
+ <PanelTabsContent value="style" css={contentStyle} tabIndex={-1}>
+ <Flex
+ justify="between"
+ align="center"
+ shrink={false}
+ css={{
+ paddingInline: theme.panel.paddingInline,
+ height: theme.spacing[13],
+ }}
+ >
+ <InstanceInfo instance={selectedInstance} />
+ <ModeMenu />
+ </Flex>
+ <StylePanel $styleSourceInputElement={$styleSourceInputElement} />
+ </PanelTabsContent>
+ <PanelTabsContent value="settings" css={contentStyle} tabIndex={-1}>
+ <ScrollArea>
<Flex
justify="between"
align="center"
@@ -170,40 +184,17 @@ export const Inspector = ({ navigatorLayout }: InspectorProps) => {
}}
>
<InstanceInfo instance={selectedInstance} />
- <ModeMenu />
</Flex>
- <StylePanel
- $styleSourceInputElement={$styleSourceInputElement}
+ <SettingsPanel
+ // Re-render when instance changes
+ key={selectedInstance.id}
+ selectedInstance={selectedInstance}
+ selectedInstanceKey={selectedInstanceKey}
/>
- </PanelTabsContent>
- <PanelTabsContent
- value="settings"
- css={contentStyle}
- tabIndex={-1}
- >
- <ScrollArea>
- <Flex
- justify="between"
- align="center"
- shrink={false}
- css={{
- paddingInline: theme.panel.paddingInline,
- height: theme.spacing[13],
- }}
- >
- <InstanceInfo instance={selectedInstance} />
- </Flex>
- <SettingsPanel
- // Re-render when instance changes
- key={selectedInstance.id}
- selectedInstance={selectedInstance}
- selectedInstanceKey={selectedInstanceKey}
- />
- </ScrollArea>
- </PanelTabsContent>
- </Flex>
- </PanelTabs>
- </BindingPopoverProvider>
+ </ScrollArea>
+ </PanelTabsContent>
+ </Flex>
+ </PanelTabs>
</FloatingPanelProvider>
</EnhancedTooltipProvider>
);
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index 0dcb08ad40..9636aec9f2 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -1,11 +1,9 @@
import {
type ButtonHTMLAttributes,
- type RefObject,
forwardRef,
useMemo,
useRef,
useState,
- createContext,
type ReactNode,
} from "react";
import { useStore } from "@nanostores/react";
@@ -334,13 +332,6 @@ const BindingButton = forwardRef<
});
BindingButton.displayName = "BindingButton";
-const BindingPopoverContext = createContext<{
- containerRef?: RefObject<null | HTMLElement>;
- side?: "left" | "right";
-}>({});
-
-export const BindingPopoverProvider = BindingPopoverContext.Provider;
-
export const BindingPopover = ({
scope,
aliases,
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index 5920e38e08..aa8a040582 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -45,16 +45,21 @@ import {
export type { EditorApi };
export const formatValue = (value: unknown) => {
- if (Array.isArray(value)) {
- // format arrays as multiline
- return JSON.stringify(value, null, 2);
- }
- if (typeof value === "object" && value !== null) {
- // format objects with parentheses to enforce correct
- // syntax highlighting as expression instead of block
- return `(${JSON.stringify(value, null, 2)})`;
+ try {
+ if (Array.isArray(value)) {
+ // format arrays as multiline
+ return JSON.stringify(value, null, 2);
+ }
+ if (typeof value === "object" && value !== null) {
+ // format objects with parentheses to enforce correct
+ // syntax highlighting as expression instead of block
+ return `(${JSON.stringify(value, null, 2)})`;
+ }
+ return JSON.stringify(value);
+ } catch {
+ // show nothing when value is invalid
+ return "";
}
- return JSON.stringify(value);
};
export const formatValuePreview = (value: unknown) => {
diff --git a/apps/builder/app/builder/shared/extended-sidebar-panel.tsx b/apps/builder/app/builder/shared/extended-sidebar-panel.tsx
index d3ade3e59c..533c0e87aa 100644
--- a/apps/builder/app/builder/shared/extended-sidebar-panel.tsx
+++ b/apps/builder/app/builder/shared/extended-sidebar-panel.tsx
@@ -1,7 +1,6 @@
import { styled, Collapsible, Flex } from "@webstudio-is/design-system";
import { theme } from "@webstudio-is/design-system";
import { useEffect, useRef } from "react";
-import { BindingPopoverProvider } from "~/builder/shared/binding-popover";
import { $canvasToolsVisible } from "~/shared/nano-states";
const CollapsibleRoot = styled(Collapsible.Root, {
@@ -46,11 +45,7 @@ export const ExtendedPanel = ({ children }: { children: React.ReactNode }) => {
borderRight: `1px solid ${theme.colors.borderMain}`,
}}
>
- <BindingPopoverProvider
- value={{ containerRef: settingsRef, side: "right" }}
- >
- {children}
- </BindingPopoverProvider>
+ {children}
</Flex>
</CollapsibleContent>
</CollapsibleRoot>
diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.ts
index 07529a9b74..0954d19295 100644
--- a/apps/builder/app/routes/rest.resources-loader.ts
+++ b/apps/builder/app/routes/rest.resources-loader.ts
@@ -1,10 +1,11 @@
import { z } from "zod";
-import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
+import { type ActionFunctionArgs, data } from "@remix-run/server-runtime";
import { ResourceRequest } from "@webstudio-is/sdk";
import { isLocalResource, loadResource } from "@webstudio-is/sdk/runtime";
import { loader as siteMapLoader } from "../shared/$resources/sitemap.xml.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { checkCsrf } from "~/services/csrf-session.server";
+import { getResourceKey } from "~/shared/resources";
export const action = async ({ request }: ActionFunctionArgs) => {
preventCrossOriginCookie(request);
@@ -36,7 +37,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
);
console.error("data:", requestJson);
- throw json(computedResourcesParsed.error, {
+ throw data(computedResourcesParsed.error, {
status: 400,
});
}
@@ -46,10 +47,10 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const responses = await Promise.all(
computedResources.map((resource) => loadResource(customFetch, resource))
);
- const output: [ResourceRequest["id"], unknown][] = [];
+ const output: [string, unknown][] = [];
responses.forEach((response, index) => {
const request = computedResources[index];
- output.push([request.id, response]);
+ output.push([getResourceKey(request), response]);
});
return output;
};
diff --git a/apps/builder/app/shared/nano-states/props.test.tsx b/apps/builder/app/shared/nano-states/props.test.tsx
index ba397b15d8..0df4b0e583 100644
--- a/apps/builder/app/shared/nano-states/props.test.tsx
+++ b/apps/builder/app/shared/nano-states/props.test.tsx
@@ -6,6 +6,7 @@ import {
DataSource,
type Instance,
ROOT_INSTANCE_ID,
+ Resource,
SYSTEM_VARIABLE_ID,
collectionComponent,
} from "@webstudio-is/sdk";
@@ -17,7 +18,7 @@ import {
} from "./props";
import { $pages } from "./pages";
import { $assets, $dataSources, $props, $resources } from "./misc";
-import { $dataSourceVariables, $resourceValues } from "./variables";
+import { $dataSourceVariables } from "./variables";
import { $awareness, getInstanceKey } from "../awareness";
import {
$,
@@ -30,6 +31,7 @@ import {
} from "@webstudio-is/template";
import { $systemDataByPage, updateCurrentSystem } from "../system";
import { registerContainers } from "../sync";
+import { $resourcesCache, getResourceKey } from "../resources";
const initialSystem = {
origin: "https://undefined.wstd.work",
@@ -71,7 +73,7 @@ beforeEach(() => {
$resources.set(new Map());
$dataSources.set(new Map());
$dataSourceVariables.set(new Map());
- $resourceValues.set(new Map());
+ $resourcesCache.set(new Map());
});
test("collect prop values", () => {
@@ -434,7 +436,25 @@ test("compute props bound to resource variables", () => {
},
])
);
- $resourceValues.set(new Map([["resourceId", "my-value"]]));
+ $resources.set(
+ toMap<Resource>([
+ {
+ id: "resourceId",
+ name: "my-resource",
+ url: `""`,
+ method: "get",
+ headers: [],
+ },
+ ])
+ );
+ const key = getResourceKey({
+ name: "my-resource",
+ url: "",
+ method: "get",
+ headers: [],
+ searchParams: [],
+ });
+ $resourcesCache.set(new Map([[key, "my-value"]]));
$props.set(
toMap([
{
@@ -784,11 +804,18 @@ test("compute resource variable values", () => {
);
$instances.set(data.instances);
$dataSources.set(data.dataSources);
+ $resources.set(data.resources);
$props.set(data.props);
const [resourceVariableId] = data.dataSources.keys();
- const [resourceId] = data.resources.keys();
selectPageRoot("bodyId");
- $resourceValues.set(new Map([[resourceId, "my-value"]]));
+ const key = getResourceKey({
+ name: "resourceVariable",
+ url: "",
+ method: "get",
+ headers: [],
+ searchParams: [],
+ });
+ $resourcesCache.set(new Map([[key, "my-value"]]));
expect(
$variableValuesByInstanceSelector
.get()
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index d01038695a..287a707d8c 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -1,6 +1,5 @@
-import { atom, computed } from "nanostores";
+import { computed } from "nanostores";
import type {
- Resource,
DataSource,
Instance,
Prop,
@@ -31,13 +30,17 @@ import {
} from "./misc";
import { $pages } from "./pages";
import type { InstanceSelector } from "../tree-utils";
-import { restResourcesLoader } from "../router-utils";
-import { $dataSourceVariables, $resourceValues } from "./variables";
+import { $dataSourceVariables } from "./variables";
import { uploadingFileDataToAsset } from "~/builder/shared/assets/asset-utils";
-import { fetch } from "~/shared/fetch.client";
import { $selectedPage, getInstanceKey } from "../awareness";
import { computeExpression } from "../data-variables";
import { $currentSystem } from "../system";
+import {
+ $resourcesCache,
+ computeResourceRequest,
+ getResourceKey,
+ preloadResource,
+} from "../resources";
export const assetBaseUrl = "/cgi/asset/";
@@ -123,6 +126,32 @@ const getAction = (
}
};
+/**
+ * similar to below but should not depend on resource values
+ * because these values are used to load resources
+ * which result in updated resource values and may trigger
+ * circular updates
+ */
+const $resourceVariableValues = computed(
+ [$dataSources, $selectedPage, $currentSystem],
+ (dataSources, selectedPage, system) => {
+ const values = new Map<string, unknown>();
+ values.set(SYSTEM_VARIABLE_ID, system);
+ for (const [dataSourceId, dataSource] of dataSources) {
+ if (dataSource.type === "variable") {
+ values.set(dataSourceId, dataSource.value.value);
+ }
+ if (
+ dataSource.type === "parameter" ||
+ dataSource.id === selectedPage?.systemDataSourceId
+ ) {
+ values.set(dataSourceId, system);
+ }
+ }
+ return values;
+ }
+);
+
/**
* values of all variables without computing scope specifics like collections
* simplified version of variable values by instance selector
@@ -131,11 +160,21 @@ const $unscopedVariableValues = computed(
[
$dataSources,
$dataSourceVariables,
- $resourceValues,
+ $resources,
+ $resourceVariableValues,
+ $resourcesCache,
$selectedPage,
$currentSystem,
],
- (dataSources, dataSourceVariables, resourceValues, page, system) => {
+ (
+ dataSources,
+ dataSourceVariables,
+ resources,
+ resourceVariableValues,
+ resourcesCache,
+ page,
+ system
+ ) => {
const values = new Map<string, unknown>();
// support global system
values.set(SYSTEM_VARIABLE_ID, system);
@@ -155,33 +194,17 @@ const $unscopedVariableValues = computed(
values.set(dataSourceId, value);
}
if (dataSource.type === "resource") {
- values.set(dataSourceId, resourceValues.get(dataSource.resourceId));
- }
- }
- return values;
- }
-);
-
-/**
- * similar to above but should not depend on resource values
- * because these values are used to load resources
- * which result in updated resource values and may trigger
- * circular updates
- */
-const $loaderVariableValues = computed(
- [$dataSources, $selectedPage, $currentSystem],
- (dataSources, selectedPage, system) => {
- const values = new Map<string, unknown>();
- values.set(SYSTEM_VARIABLE_ID, system);
- for (const [dataSourceId, dataSource] of dataSources) {
- if (dataSource.type === "variable") {
- values.set(dataSourceId, dataSource.value.value);
- }
- if (
- dataSource.type === "parameter" ||
- dataSource.id === selectedPage?.systemDataSourceId
- ) {
- values.set(dataSourceId, system);
+ const resource = resources.get(dataSource.resourceId);
+ if (resource) {
+ const resourceRequest = computeResourceRequest(
+ resource,
+ resourceVariableValues
+ );
+ values.set(
+ dataSourceId,
+ resourcesCache.get(getResourceKey(resourceRequest))
+ );
+ }
}
}
return values;
@@ -358,7 +381,9 @@ export const $variableValuesByInstanceSelector = computed(
$selectedPage,
$dataSources,
$dataSourceVariables,
- $resourceValues,
+ $resources,
+ $resourceVariableValues,
+ $resourcesCache,
$currentSystem,
],
(
@@ -367,7 +392,9 @@ export const $variableValuesByInstanceSelector = computed(
page,
dataSources,
dataSourceVariables,
- resourceValues,
+ resources,
+ resourceVariableValues,
+ resourcesCache,
system
) => {
const propsByInstanceId = mapGroupBy(
@@ -426,8 +453,17 @@ export const $variableValuesByInstanceSelector = computed(
}
}
if (variable.type === "resource") {
- const value = resourceValues.get(variable.resourceId);
- variableValues.set(variable.id, value);
+ const resource = resources.get(variable.resourceId);
+ if (resource) {
+ const resourceRequest = computeResourceRequest(
+ resource,
+ resourceVariableValues
+ );
+ variableValues.set(
+ variable.id,
+ resourcesCache.get(getResourceKey(resourceRequest))
+ );
+ }
}
}
}
@@ -532,32 +568,14 @@ export const $variableValuesByInstanceSelector = computed(
}
);
-const computeResourceRequest = (
- resource: Resource,
- values: Map<DataSource["id"], unknown>
-): ResourceRequest => {
- const request: ResourceRequest = {
- id: resource.id,
- name: resource.name,
- method: resource.method,
- url: computeExpression(resource.url, values),
- searchParams: (resource.searchParams ?? []).map(({ name, value }) => ({
- name,
- value: computeExpression(value, values),
- })),
- headers: resource.headers.map(({ name, value }) => ({
- name,
- value: computeExpression(value, values),
- })),
- };
- if (resource.body !== undefined) {
- request.body = computeExpression(resource.body, values);
- }
- return request;
-};
-
const $computedResourceRequests = computed(
- [$selectedPage, $instances, $dataSources, $resources, $loaderVariableValues],
+ [
+ $selectedPage,
+ $instances,
+ $dataSources,
+ $resources,
+ $resourceVariableValues,
+ ],
(page, instances, dataSources, resources, values) => {
const computedResourceRequests: ResourceRequest[] = [];
if (page === undefined) {
@@ -584,101 +602,15 @@ const $computedResourceRequests = computed(
}
);
-const $resourcesLoadingCount = atom(0);
-export const $areResourcesLoading = computed(
- $resourcesLoadingCount,
- (resourcesLoadingCount) => resourcesLoadingCount > 0
-);
-
-const loadResources = async (resourceRequests: ResourceRequest[]) => {
- $resourcesLoadingCount.set($resourcesLoadingCount.get() + 1);
- const response = await fetch(restResourcesLoader(), {
- method: "POST",
- body: JSON.stringify(resourceRequests),
- });
- $resourcesLoadingCount.set($resourcesLoadingCount.get() - 1);
- if (response.ok === false) {
- return new Map<Resource["id"], unknown>();
- }
- return new Map<Resource["id"], unknown>(await response.json());
-};
-
-const cacheByKeys = new Map<string, unknown>();
-
-const $invalidator = atom(0);
-
-export const getComputedResourceRequest = (resourceId: Resource["id"]) => {
- const resources = $resources.get();
- const resource = resources.get(resourceId);
- if (resource === undefined) {
- return;
- }
- const values = $loaderVariableValues.get();
- return computeResourceRequest(resource, values);
-};
-
-// bump index of resource to invaldate cache entry
-export const invalidateResource = (resourceId: Resource["id"]) => {
- const request = getComputedResourceRequest(resourceId);
- if (request === undefined) {
- return;
- }
- const cacheKey = JSON.stringify(request);
- cacheByKeys.delete(cacheKey);
- // trigger invalidation
- $invalidator.set($invalidator.get() + 1);
-};
-
/**
* subscribe to all resources changes
* load them with currently available variable values
* and store in cache
*/
export const subscribeResources = () => {
- let frameId: undefined | number;
- // subscribe changing resources or global invalidation
- return computed(
- [$computedResourceRequests, $invalidator],
- (computedResourceRequests, invalidator) =>
- [computedResourceRequests, invalidator] as const
- ).subscribe(([computedResourceRequests]) => {
- if (frameId) {
- cancelAnimationFrame(frameId);
+ return $computedResourceRequests.subscribe((computedResourceRequests) => {
+ for (const resourceRequest of computedResourceRequests) {
+ preloadResource(resourceRequest);
}
- // batch updates into next frame
- // to avoid issues with untransactioned updates in nanostores
- frameId = requestAnimationFrame(async () => {
- const matched = new Map<Resource["id"], ResourceRequest>();
- const missing = new Map<Resource["id"], ResourceRequest>();
- for (const request of computedResourceRequests) {
- const cacheKey = JSON.stringify(request);
- if (cacheByKeys.has(cacheKey)) {
- matched.set(request.id, request);
- } else {
- missing.set(request.id, request);
- }
- }
-
- // preset undefined to prevent loading already requested data
- for (const request of missing.values()) {
- const cacheKey = JSON.stringify(request);
- cacheByKeys.set(cacheKey, undefined);
- }
-
- let result = new Map<string, unknown>();
- if (missing.size > 0) {
- result = await loadResources(Array.from(missing.values()));
- }
- const newResourceValues = new Map();
- for (const request of computedResourceRequests) {
- const cacheKey = JSON.stringify(request);
- // read from cache or store in cache
- const response = result.get(request.id) ?? cacheByKeys.get(cacheKey);
- cacheByKeys.set(cacheKey, response);
- newResourceValues.set(request.id, response);
- }
- // update resource values only when new resources are loaded
- $resourceValues.set(newResourceValues);
- });
});
};
diff --git a/apps/builder/app/shared/nano-states/variables.ts b/apps/builder/app/shared/nano-states/variables.ts
index 2c6fc0e6df..783f97c187 100644
--- a/apps/builder/app/shared/nano-states/variables.ts
+++ b/apps/builder/app/shared/nano-states/variables.ts
@@ -1,8 +1,6 @@
import { atom } from "nanostores";
-import type { DataSource, Resource } from "@webstudio-is/sdk";
+import type { DataSource } from "@webstudio-is/sdk";
export const $dataSourceVariables = atom<Map<DataSource["id"], unknown>>(
new Map()
);
-
-export const $resourceValues = atom(new Map<Resource["id"], unknown>());
diff --git a/apps/builder/app/shared/resources.ts b/apps/builder/app/shared/resources.ts
new file mode 100644
index 0000000000..815368b595
--- /dev/null
+++ b/apps/builder/app/shared/resources.ts
@@ -0,0 +1,120 @@
+import { atom, computed } from "nanostores";
+import hash from "@emotion/hash";
+import type { DataSource, Resource, ResourceRequest } from "@webstudio-is/sdk";
+import { restResourcesLoader } from "./router-utils";
+import { computeExpression } from "./data-variables";
+import { fetch } from "./fetch.client";
+
+const MAX_PENDING_RESOURCES = 5;
+
+export const getResourceKey = (resource: ResourceRequest) =>
+ hash(
+ JSON.stringify([
+ // explicitly list all fields to keep hash stable
+ resource.name,
+ resource.method,
+ resource.url,
+ resource.searchParams,
+ resource.headers,
+ resource.body,
+ ])
+ );
+
+const queue = new Map<string, ResourceRequest>();
+const pending = new Map<string, ResourceRequest>();
+const cache = new Map<string, unknown>();
+
+export const $resourcesCache = atom(cache);
+
+const updateCache = () => {
+ $resourcesCache.set(new Map(cache));
+};
+
+const $pendingUpdater = atom({});
+
+const updatePending = () => {
+ $pendingUpdater.set({});
+};
+
+export const $hasPendingResources = computed(
+ $pendingUpdater,
+ () => queue.size > 0 || pending.size > 0
+);
+
+const loadResources = async () => {
+ const list = Array.from(queue.values()).slice(0, MAX_PENDING_RESOURCES);
+ for (const resource of list) {
+ const key = getResourceKey(resource);
+ queue.delete(key);
+ pending.set(key, resource);
+ }
+ updatePending();
+ const response = await fetch(restResourcesLoader(), {
+ method: "POST",
+ body: JSON.stringify(Array.from(pending.values())),
+ });
+ if (response.ok) {
+ const results = new Map<string, unknown>(await response.json());
+ for (const [key, result] of results) {
+ cache.set(key, result);
+ pending.delete(key);
+ }
+ }
+ updateCache();
+ updatePending();
+ // restart loading until queue is empty
+ scheduleLoading();
+};
+
+let timeoutId: undefined | number;
+
+const scheduleLoading = () => {
+ // scheduling will be restarted after finishing pending one
+ // skip when there is nothing in queue
+ if (pending.size > 0 || queue.size === 0) {
+ return;
+ }
+ window.clearTimeout(timeoutId);
+ // start loading after one second of "preload" call
+ timeoutId = window.setTimeout(loadResources, 1000);
+};
+
+export const preloadResource = (resource: ResourceRequest) => {
+ const key = getResourceKey(resource);
+ if (queue.has(key) || pending.has(key) || cache.has(key)) {
+ return;
+ }
+ // deduplicate resources in queue
+ queue.set(key, resource);
+ updatePending();
+ scheduleLoading();
+};
+
+export const invalidateResource = (resource: ResourceRequest) => {
+ const key = getResourceKey(resource);
+ cache.delete(key);
+ preloadResource(resource);
+};
+
+export const computeResourceRequest = (
+ resource: Resource,
+ values: Map<DataSource["id"], unknown>
+): ResourceRequest => {
+ const request: ResourceRequest = {
+ name: resource.name,
+ method: resource.method,
+ url: computeExpression(resource.url, values),
+ searchParams: (resource.searchParams ?? []).map(({ name, value }) => ({
+ name,
+ value: computeExpression(value, values),
+ })),
+ headers: resource.headers.map(({ name, value }) => ({
+ name,
+ value: computeExpression(value, values),
+ })),
+ };
+ if (resource.body !== undefined) {
+ request.body = computeExpression(resource.body, values);
+ }
+ return request;
+};
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index c202f6c465..9fd1a67479 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -24,7 +24,6 @@ import {
$dragAndDropState,
$selectedInstanceStates,
$resources,
- $resourceValues,
$marketplaceProduct,
$canvasIframeState,
$uploadingFilesDataStore,
@@ -57,6 +56,7 @@ import {
import { $canvasScrollbarSize } from "~/builder/shared/nano-states";
import { $awareness, $temporaryInstances } from "../awareness";
import { $systemDataByPage } from "../system";
+import { $resourcesCache } from "../resources";
enableMapSet();
// safari structuredClone fix
@@ -89,7 +89,7 @@ export const createObjectPool = () => {
new NanostoresSyncObject("project", $project),
new NanostoresSyncObject("dataSourceVariables", $dataSourceVariables),
- new NanostoresSyncObject("resourceValues", $resourceValues),
+ new NanostoresSyncObject("resourcesCache", $resourcesCache),
new NanostoresSyncObject("selectedPageHash", $selectedPageHash),
new NanostoresSyncObject("selectedInstanceSizes", $selectedInstanceSizes),
new NanostoresSyncObject(
diff --git a/apps/builder/package.json b/apps/builder/package.json
index dc5d8ad09b..beb71c1af1 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -30,6 +30,7 @@
"@codemirror/lint": "^6.8.5",
"@codemirror/state": "^6.5.2",
"@codemirror/view": "^6.36.4",
+ "@emotion/hash": "^0.9.2",
"@floating-ui/dom": "^1.6.13",
"@fontsource-variable/inter": "^5.0.20",
"@fontsource-variable/manrope": "^5.0.20",
diff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
index ae0c9252ac..67cc24284c 100644
--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
@@ -5,7 +5,6 @@ import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const jsonResourceVariable_1: ResourceRequest = {
- id: "fjMzCru8O2U31xY2P1Ovr",
name: "jsonResourceVariable",
url: "https://httpbin.org/get?hello=world",
searchParams: [],
diff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
index f14016ed67..252e4bae83 100644
--- a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
@@ -5,7 +5,6 @@ import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const action: ResourceRequest = {
- id: "isNSM3wXcnHFikwNPlEOL",
name: "action",
url: "/custom",
searchParams: [],
diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
index 0a125bf68b..35b84844c2 100644
--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
@@ -5,7 +5,6 @@ import type { PageMeta } from "@webstudio-is/sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const list_1: ResourceRequest = {
- id: "1vX6SQdaCjJN6MvJlG_cQ",
name: "list",
url: "https://gist.githubusercontent.com/TrySound/56507c301ec85669db5f1541406a9259/raw/a49548730ab592c86b9e7781f5b29beec4765494/collection.json",
searchParams: [],
diff --git a/packages/sdk/src/resource-loader.test.ts b/packages/sdk/src/resource-loader.test.ts
index b6d163424d..1d11d305a9 100644
--- a/packages/sdk/src/resource-loader.test.ts
+++ b/packages/sdk/src/resource-loader.test.ts
@@ -20,7 +20,6 @@ describe("loadResource", () => {
mockFetch.mockResolvedValue(mockResponse);
const resourceRequest: ResourceRequest = {
- id: "1",
name: "resource",
url: "https://example.com/resource",
searchParams: [],
@@ -53,7 +52,6 @@ describe("loadResource", () => {
mockFetch.mockResolvedValue(mockResponse);
const resourceRequest: ResourceRequest = {
- id: "1",
name: "resource",
url: "https://example.com/resource",
searchParams: [],
@@ -84,7 +82,6 @@ describe("loadResource", () => {
mockFetch.mockResolvedValue(mockResponse);
const resourceRequest: ResourceRequest = {
- id: "1",
name: "resource",
url: "https://example.com/resource",
searchParams: [
@@ -114,7 +111,6 @@ describe("loadResource", () => {
mockFetch.mockResolvedValue(mockResponse);
const resourceRequest: ResourceRequest = {
- id: "1",
name: "resource",
url: "https://example.com/resource",
searchParams: [
@@ -142,7 +138,6 @@ describe("loadResource", () => {
mockFetch.mockResolvedValue(mockResponse);
const resourceRequest: ResourceRequest = {
- id: "1",
name: "resource",
url: "https://example.com/resource",
searchParams: [],
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index 75dfae3c4f..2b6fbee10e 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -23,29 +23,29 @@ export const loadResource = async (
customFetch: typeof fetch,
resourceRequest: ResourceRequest
) => {
- const { method, searchParams, headers, body } = resourceRequest;
- // cloudflare workers fail when fetching url contains spaces
- // even though new URL suppose to trim them on parsing by spec
- const url = new URL(resourceRequest.url.trim());
- if (searchParams) {
- for (const { name, value } of searchParams) {
- url.searchParams.append(name, serializeValue(value));
- }
- }
- const requestHeaders = new Headers(
- headers.map(({ name, value }): [string, string] => [
- name,
- serializeValue(value),
- ])
- );
- const requestInit: RequestInit = {
- method,
- headers: requestHeaders,
- };
- if (method !== "get" && body !== undefined) {
- requestInit.body = serializeValue(body);
- }
try {
+ const { method, searchParams, headers, body } = resourceRequest;
+ // cloudflare workers fail when fetching url contains spaces
+ // even though new URL suppose to trim them on parsing by spec
+ const url = new URL(resourceRequest.url.trim());
+ if (searchParams) {
+ for (const { name, value } of searchParams) {
+ url.searchParams.append(name, serializeValue(value));
+ }
+ }
+ const requestHeaders = new Headers(
+ headers.map(({ name, value }): [string, string] => [
+ name,
+ serializeValue(value),
+ ])
+ );
+ const requestInit: RequestInit = {
+ method,
+ headers: requestHeaders,
+ };
+ if (method !== "get" && body !== undefined) {
+ requestInit.body = serializeValue(body);
+ }
const response = await customFetch(url.href, requestInit);
let data = await response.text();
diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsx
index 166fbeeb76..9e621ac58e 100644
--- a/packages/sdk/src/resources-generator.test.tsx
+++ b/packages/sdk/src/resources-generator.test.tsx
@@ -46,7 +46,6 @@ test("generate resources loader", () => {
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const resourceName: ResourceRequest = {
- id: "resourceId",
name: "resourceName",
url: "https://my-json.com",
searchParams: [
@@ -113,7 +112,6 @@ test("generate variable and use in resources loader", () => {
export const getResources = (_props: { system: System }) => {
let AccessToken = "my-token"
const resourceName: ResourceRequest = {
- id: "resourceId",
name: "resourceName",
url: "https://my-json.com/",
searchParams: [
@@ -176,7 +174,6 @@ test("generate page system variable and use in resources loader", () => {
export const getResources = (_props: { system: System }) => {
const system = _props.system
const resourceName: ResourceRequest = {
- id: "resourceId",
name: "resourceName",
url: "https://my-json.com/" + system?.params?.slug,
searchParams: [
@@ -220,7 +217,6 @@ test("generate global system variable and use in resources loader", () => {
export const getResources = (_props: { system: System }) => {
const system = _props.system
const MyResource: ResourceRequest = {
- id: "resource:0",
name: "My Resource",
url: "https://my-json.com/" + system?.params?.slug,
searchParams: [
@@ -307,7 +303,6 @@ test("generate resource loader with search params", () => {
export const getResources = (_props: { system: System }) => {
let term = "my-term"
const resourceName: ResourceRequest = {
- id: "resourceId",
name: "resourceName",
url: "https://my-json.com",
searchParams: [
@@ -422,7 +417,6 @@ test("generate action resource", () => {
"import type { System, ResourceRequest } from "@webstudio-is/sdk";
export const getResources = (_props: { system: System }) => {
const resourceName: ResourceRequest = {
- id: "resourceId",
name: "resourceName",
url: "https://my-url.com",
searchParams: [
diff --git a/packages/sdk/src/resources-generator.ts b/packages/sdk/src/resources-generator.ts
index 14dce06f7d..3fefb9b2d7 100644
--- a/packages/sdk/src/resources-generator.ts
+++ b/packages/sdk/src/resources-generator.ts
@@ -27,7 +27,6 @@ export const generateResources = ({
// call resource by bound variable name
const resourceName = scope.getName(resource.id, resource.name);
generatedRequest += ` const ${resourceName}: ResourceRequest = {\n`;
- generatedRequest += ` id: "${resource.id}",\n`;
generatedRequest += ` name: ${JSON.stringify(resource.name)},\n`;
const url = generateExpression({
expression: resource.url,
diff --git a/packages/sdk/src/schema/resources.ts b/packages/sdk/src/schema/resources.ts
index f51eaca7cf..a22b0a0134 100644
--- a/packages/sdk/src/schema/resources.ts
+++ b/packages/sdk/src/schema/resources.ts
@@ -40,7 +40,6 @@ export type Resource = z.infer<typeof Resource>;
// evaluated variant of resource
export const ResourceRequest = z.object({
- id: ResourceId,
name: z.string(),
method: Method,
url: z.string(),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 19da03f5b2..ba2a74f2bc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -151,6 +151,9 @@ importers:
'@codemirror/view':
specifier: ^6.36.4
version: 6.36.4
+ '@emotion/hash':
+ specifier: ^0.9.2
+ version: 0.9.2
'@floating-ui/dom':
specifier: ^1.6.13
version: 1.6.13