Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Add System Resource instead of $resources url (#3341)
Oleg Isonen2496f68d32ef
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxindex 5bbc6a2db2..1e7a1c5dfb 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -12,7 +12,7 @@ import type { DataSource, Resource } from "@webstudio-is/sdk";import {encodeDataSourceVariable,isLiteralExpression,- isLocalResource,+ sitemapResourceUrl,} from "@webstudio-is/sdk";import {Box,@@ -446,10 +446,6 @@ export const ResourceForm = forwardRef<try {new URL(evaluatedValue);} catch {- if (isLocalResource(evaluatedValue, "sitemap.xml")) {- return;- }-return "URL is invalid";}},@@ -630,3 +626,96 @@ export const ResourceForm = forwardRef<);});ResourceForm.displayName = "ResourceForm";++export const SystemResourceForm = forwardRef<+ undefined | PanelApi,+ { variable?: DataSource; nameField: Field<string> }+>(({ variable, nameField }, ref) => {+ const resources = useStore($resources);++ const resource =+ variable?.type === "resource"+ ? resources.get(variable.resourceId)+ : undefined;++ const method = "get";++ const localResources = [+ {+ label: "Sitemap",+ value: JSON.stringify(sitemapResourceUrl),+ description: "Resource that loads the sitemap data of the current site.",+ },+ ];++ const [localResource, setLocalResource] = useState(() => {+ return (+ localResources.find(+ (localResource) => localResource.value === resource?.url+ ) ?? localResources[0]+ );+ });++ const form = composeFields(nameField);++ useImperativeHandle(ref, () => ({+ ...form,+ save: () => {+ const instanceSelector = $selectedInstanceSelector.get();+ if (instanceSelector === undefined) {+ return;+ }+ const [instanceId] = instanceSelector;++ const newResource: Resource = {+ id: resource?.id ?? nanoid(),+ name: nameField.value,+ url: localResource.value,+ method,+ headers: [],+ };++ const newVariable: DataSource = {+ id: variable?.id ?? nanoid(),+ // preserve existing instance scope when edit+ scopeInstanceId: variable?.scopeInstanceId ?? instanceId,+ name: nameField.value,+ type: "resource",+ resourceId: newResource.id,+ };++ serverSyncStore.createTransaction(+ [$dataSources, $resources],+ (dataSources, resources) => {+ dataSources.set(newVariable.id, newVariable);+ resources.set(newResource.id, newResource);+ }+ );+ },+ }));++ const resourceId = useId();++ return (+ <>+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>+ <Label htmlFor={resourceId}>Resource</Label>+ <Select+ options={localResources}+ getLabel={(option) => option.label}+ getValue={(option) => option.value}+ getDescription={(option) => {+ return (+ <Box css={{ width: theme.spacing[25] }}>+ {option?.description}+ </Box>+ );+ }}+ value={localResource}+ onChange={setLocalResource}+ />+ </Flex>+ </>+ );+});+SystemResourceForm.displayName = "ResourceForm";diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsxindex f9da97217e..36d112fe18 100644--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx@@ -33,7 +33,7 @@ import {Tooltip,theme,} from "@webstudio-is/design-system";-import { transpileExpression } from "@webstudio-is/sdk";+import { isLocalResource, transpileExpression } from "@webstudio-is/sdk";import type { DataSource } from "@webstudio-is/sdk";import {ExpressionEditor,@@ -62,7 +62,7 @@ import {EditorDialogButton,EditorDialogControl,} from "~/builder/shared/code-editor-base";-import { ResourceForm } from "./resource-panel";+import { ResourceForm, SystemResourceForm } from "./resource-panel";import { generateCurl } from "./curl";/**@@ -108,6 +108,7 @@ type VariableType =| "boolean"| "json"| "resource"+ | "system-resource"| "parameter";type PanelApi = ComposedFields & {@@ -359,6 +360,7 @@ const VariablePanel = forwardRef<}>(({ variable }, ref) => {const { allowDynamicData } = useStore($userPlanFeatures);+ const resources = useStore($resources);const nameField = useField({initialValue: variable?.name ?? "",@@ -383,10 +385,18 @@ const VariablePanel = forwardRef<</Flex>);- const [type, setType] = useState<VariableType>(() => {+ const [variableType, setVariableType] = useState<VariableType>(() => {+ if (+ variable?.type === "resource" &&+ isLocalResource(JSON.parse(resources.get(variable.resourceId)?.url ?? ""))+ ) {+ return "system-resource";+ }+if (variable?.type === "parameter" || variable?.type === "resource") {return variable.type;}+if (variable?.type === "variable") {const type = variable.value.type;if (type === "string" || type === "number" || type === "boolean") {@@ -427,7 +437,20 @@ const VariablePanel = forwardRef<"A Resource is a configuration for secure data fetching. You can safely use secrets in any field.",},],+ [+ "system-resource",+ {+ label: (+ <Flex direction="row" gap="2" align="center">+ System Resource+ {allowDynamicData === false && <ProBadge>Pro</ProBadge>}+ </Flex>+ ),+ description: "A System Resource is a configuration for Webstudio data.",+ },+ ],]);+const typeFieldElement = (<Flex direction="column" gap="1"><Label>Type</Label>@@ -444,13 +467,13 @@ const VariablePanel = forwardRef<</Box>);}}- value={type}- onChange={setType}+ value={variableType}+ onChange={setVariableType}/></Flex>);- if (type === "parameter") {+ if (variableType === "parameter") {return (<>{nameFieldElement}@@ -458,7 +481,7 @@ const VariablePanel = forwardRef<</>);}- if (type === "string") {+ if (variableType === "string") {return (<>{nameFieldElement}@@ -467,7 +490,7 @@ const VariablePanel = forwardRef<</>);}- if (type === "number") {+ if (variableType === "number") {return (<>{nameFieldElement}@@ -476,7 +499,7 @@ const VariablePanel = forwardRef<</>);}- if (type === "boolean") {+ if (variableType === "boolean") {return (<>{nameFieldElement}@@ -485,7 +508,7 @@ const VariablePanel = forwardRef<</>);}- if (type === "json") {+ if (variableType === "json") {return (<>{nameFieldElement}@@ -494,7 +517,8 @@ const VariablePanel = forwardRef<</>);}- if (type === "resource") {++ if (variableType === "resource") {return (<>{nameFieldElement}@@ -503,6 +527,22 @@ const VariablePanel = forwardRef<</>);}++ if (variableType === "system-resource") {+ return (+ <>+ {nameFieldElement}+ {typeFieldElement}+ <SystemResourceForm+ ref={ref}+ variable={variable}+ nameField={nameField}+ />+ </>+ );+ }++ variableType satisfies never;});VariablePanel.displayName = "VariablePanel";@@ -522,6 +562,8 @@ export const VariablePopoverTrigger = forwardRef<const [triggerRef, sideOffsset] = useSideOffset({ isOpen, containerRef });const bindingPopoverContainerRef = useRef<HTMLDivElement>(null);const panelRef = useRef<undefined | PanelApi>();+ const resources = useStore($resources);+const saveAndClose = () => {if (panelRef.current) {if (panelRef.current.allErrorsVisible === false) {@@ -597,28 +639,32 @@ export const VariablePopoverTrigger = forwardRef<) : (<FloatingPanelPopoverTitleactions={- variable.type === "resource" && (+ variable?.type === "resource" && (<>- <Tooltip- content="Copy resource as cURL command"- side="bottom"- >- <Button- aria-label="Copy resource as cURL command"- prefix={<CopyIcon />}- color="ghost"- onClick={() => {- const resourceRequest = getComputedResource(- variable.resourceId- );- if (resourceRequest) {- navigator.clipboard.writeText(- generateCurl(resourceRequest)+ {isLocalResource(+ JSON.parse(resources.get(variable.resourceId)?.url ?? "")+ ) === false && (+ <Tooltip+ content="Copy resource as cURL command"+ side="bottom"+ >+ <Button+ aria-label="Copy resource as cURL command"+ prefix={<CopyIcon />}+ color="ghost"+ onClick={() => {+ const resourceRequest = getComputedResource(+ variable.resourceId);- }- }}- />- </Tooltip>+ if (resourceRequest) {+ navigator.clipboard.writeText(+ generateCurl(resourceRequest)+ );+ }+ }}+ />+ </Tooltip>+ )}<Tooltip content="Refresh resource data" side="bottom"><Buttonaria-label="Refresh resource data"diff --git a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsxindex 86670b1199..36128c86a0 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx+++ b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx@@ -57,7 +57,7 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {// Only xml category is allowed for xml document typeif (documentType === "xml") {- return category === "xml";+ return category === "xml" || category === "data";}// Hide xml category for non-xml document typesif (category === "xml") {@@ -81,8 +81,16 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {wrap="wrap"css={{ px: theme.spacing[9], overflow: "auto" }}>- {(metaByCategory.get(category) ?? []).map(- (meta: WsComponentMeta, index) => {+ {(metaByCategory.get(category) ?? [])+ .filter((meta: WsComponentMeta) => {+ if (documentType === "xml" && meta.category === "data") {+ return (+ componentNamesByMeta.get(meta) === "ws:collection"+ );+ }+ return true;+ })+ .map((meta: WsComponentMeta, index) => {const component = componentNamesByMeta.get(meta);if (component === undefined) {return;@@ -123,8 +131,7 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {/></ListItem>);- }- )}+ })}{dragCard}</Flex></List>diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.tsindex 33a8323a01..ca71a919c0 100644--- a/apps/builder/app/routes/rest.resources-loader.ts+++ b/apps/builder/app/routes/rest.resources-loader.ts@@ -1,5 +1,5 @@import { z } from "zod";-import type { ActionFunctionArgs } from "@remix-run/server-runtime";+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";import {loadResource,isLocalResource,@@ -21,9 +21,26 @@ export const action = async ({ request }: ActionFunctionArgs) => {return fetch(input, init);};- const computedResources = z+ const requestJson = await request.json();++ const computedResourcesParsed = z.array(ResourceRequest)- .parse(await request.json());+ .safeParse(requestJson);++ if (computedResourcesParsed.success === false) {+ console.error(+ "computedResources.parse",+ computedResourcesParsed.error.toString()+ );+ console.error("data:", requestJson);++ throw json(computedResourcesParsed.error, {+ status: 400,+ });+ }++ const computedResources = computedResourcesParsed.data;+const responses = await Promise.all(computedResources.map((resource) => loadResource(customFetch, resource)));diff --git a/packages/sdk/src/schema/resources.ts b/packages/sdk/src/schema/resources.tsindex 28b4e5eb77..3d89b8e78f 100644--- a/packages/sdk/src/schema/resources.ts+++ b/packages/sdk/src/schema/resources.ts@@ -49,6 +49,14 @@ const LOCAL_RESOURCE_PREFIX = "$resources";/*** Prevents fetch cycles by prefixing local resources.*/-export const isLocalResource = (pathname: string, resourceName: string) =>- pathname.split("/").filter(Boolean).join("/") ===- `${LOCAL_RESOURCE_PREFIX}/${resourceName}`;+export const isLocalResource = (pathname: string, resourceName?: string) => {+ const segments = pathname.split("/").filter(Boolean);++ if (resourceName === undefined) {+ return segments[0] === LOCAL_RESOURCE_PREFIX;+ }++ return segments.join("/") === `${LOCAL_RESOURCE_PREFIX}/${resourceName}`;+};++export const sitemapResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/sitemap.xml`;