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.

Ability to replace SDK components (#516)

Roman Pominova9fede0a1d65
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsx
index 9e9ac5551c..6e3d59022a 100644
--- a/apps/designer/app/canvas/canvas.tsx
+++ b/apps/designer/app/canvas/canvas.tsx
@@ -4,6 +4,9 @@ import type { Build, CanvasData } from "@webstudio-is/project";
import {
createElementsTree,
useAllUserProps,
+ registerComponents,
+ customComponents,
+ setParams,
type OnChangeChildren,
type Tree,
} from "@webstudio-is/react-sdk";
@@ -133,6 +136,10 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
const assets = useAssets(data.assets);
useAllUserProps(data.props);
usePopulateRootInstance(data.tree);
+ setParams(data.params ?? null);
+
+ registerComponents(customComponents);
+
// e.g. toggling preview is still needed in both modes
useShortcuts();
const isPreviewMode = useSubscribePreviewMode();
diff --git a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx
index a8458c8359..fbdede4503 100644
--- a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx
+++ b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx
@@ -4,7 +4,7 @@ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext
import {
useUserProps,
renderWrapperComponentChildren,
- components,
+ getComponent,
type Instance,
type OnChangeChildren,
idAttribute,
@@ -66,7 +66,7 @@ export const WrapperComponentDev = ({
const readonlyProps =
instance.component === "Input" ? { readOnly: true } : undefined;
- const { Component } = components[instance.component];
+ const Component = getComponent(instance.component);
const props = {
...userProps,
diff --git a/apps/designer/app/canvas/shared/instance.ts b/apps/designer/app/canvas/shared/instance.ts
index 2dba11d9d5..0c9bc3ec51 100644
--- a/apps/designer/app/canvas/shared/instance.ts
+++ b/apps/designer/app/canvas/shared/instance.ts
@@ -4,7 +4,7 @@ import {
type Instance,
type InstanceProps,
type Tree,
- components,
+ getComponentMeta,
allUserPropsContainer,
getBrowserStyle,
useAllUserProps,
@@ -79,7 +79,7 @@ export const findInsertLocation = (
path.reverse();
const parentIndex = path.findIndex(
- ({ item }) => components[item.component].canAcceptChildren
+ ({ item }) => getComponentMeta(item.component).canAcceptChildren
);
// Just in case selected Instance is not in the tree for some reason.
diff --git a/apps/designer/app/canvas/shared/use-drag-drop.ts b/apps/designer/app/canvas/shared/use-drag-drop.ts
index 86b251ccfd..9ea65efec1 100644
--- a/apps/designer/app/canvas/shared/use-drag-drop.ts
+++ b/apps/designer/app/canvas/shared/use-drag-drop.ts
@@ -18,7 +18,7 @@ import {
} from "@webstudio-is/design-system";
import {
type Instance,
- components,
+ getComponentMeta,
BaseInstance,
toBaseInstance,
} from "@webstudio-is/react-sdk";
@@ -116,7 +116,7 @@ export const useDragAndDrop = () => {
}
const data = path.find(
- (instance) => components[instance.component].canAcceptChildren
+ (instance) => getComponentMeta(instance.component).canAcceptChildren
);
if (data === undefined) {
@@ -179,7 +179,7 @@ export const useDragAndDrop = () => {
}
// When trying to drag an inline instance, drag its parent instead
- if (components[instance.component].isInlineOnly) {
+ if (getComponentMeta(instance.component).isInlineOnly) {
const nonInlineParent = utils.tree.findClosestNonInlineParent(
rootInstance,
instance.id
diff --git a/apps/designer/app/canvas/shared/use-shortcuts.ts b/apps/designer/app/canvas/shared/use-shortcuts.ts
index 272e3651b3..52ba409c46 100644
--- a/apps/designer/app/canvas/shared/use-shortcuts.ts
+++ b/apps/designer/app/canvas/shared/use-shortcuts.ts
@@ -1,6 +1,6 @@
import { useHotkeys } from "react-hotkeys-hook";
import store from "immerhin";
-import { type Instance, components } from "@webstudio-is/react-sdk";
+import { type Instance, getComponentMeta } from "@webstudio-is/react-sdk";
import { shortcuts, options } from "~/shared/shortcuts";
import { publish, useSubscribe } from "~/shared/pubsub";
import { useSelectedInstance } from "./nano-states";
@@ -120,7 +120,9 @@ export const useShortcuts = () => {
"enter",
(event) => {
if (selectedInstance === undefined) return;
- const { isContentEditable } = components[selectedInstance.component];
+ const { isContentEditable } = getComponentMeta(
+ selectedInstance.component
+ );
if (isContentEditable === false) return;
// Prevents inserting a newline when entering text-editing mode
event.preventDefault();
diff --git a/apps/designer/app/canvas/shared/use-track-selected-element.ts b/apps/designer/app/canvas/shared/use-track-selected-element.ts
index 6efdf1f5c2..5a93503f68 100644
--- a/apps/designer/app/canvas/shared/use-track-selected-element.ts
+++ b/apps/designer/app/canvas/shared/use-track-selected-element.ts
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef } from "react";
-import { type Instance, components } from "@webstudio-is/react-sdk";
+import { type Instance, getComponentMeta } from "@webstudio-is/react-sdk";
import { useSubscribe } from "~/shared/pubsub";
import { useSelectedElement, useSelectedInstance } from "./nano-states";
import {
@@ -91,10 +91,10 @@ export const useTrackSelectedElement = () => {
// It's the second click in a double click.
if (event.detail === 2) {
const component = dataset.wsComponent as Instance["component"];
- if (component === undefined || component in components === false) {
+ if (component === undefined /*|| component in components === false*/) {
return;
}
- const { isInlineOnly, isContentEditable } = components[component];
+ const { isInlineOnly, isContentEditable } = getComponentMeta(component);
// When user double clicks on an inline instance, we need to select the parent instance and put it indo text editing mode.
// Inline instances are not editable directly, only through parent instance.
@@ -102,7 +102,7 @@ export const useTrackSelectedElement = () => {
const parent =
rootInstance &&
utils.tree.findClosestNonInlineParent(rootInstance, id);
- if (parent && components[parent.component].isContentEditable) {
+ if (parent && getComponentMeta(parent.component).isContentEditable) {
selectInstance(parent.id);
setEditingInstanceId(parent.id);
}
diff --git a/apps/designer/app/designer/features/props-panel/control.tsx b/apps/designer/app/designer/features/props-panel/control.tsx
index dab2e52657..7662311082 100644
--- a/apps/designer/app/designer/features/props-panel/control.tsx
+++ b/apps/designer/app/designer/features/props-panel/control.tsx
@@ -1,5 +1,5 @@
import {
- componentsMeta,
+ getComponentMetaProps,
type Instance,
type UserProp,
} from "@webstudio-is/react-sdk";
@@ -183,7 +183,7 @@ export function Control({
userProp,
onChangePropValue,
}: ControlProps) {
- const meta = componentsMeta[component];
+ const meta = getComponentMetaProps(component);
const argType = meta[userProp.prop as keyof typeof meta];
const defaultValue = argType.defaultValue;
diff --git a/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx b/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx
index 1502a804b1..4160b4f109 100644
--- a/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx
+++ b/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx
@@ -1,5 +1,5 @@
import { ComponentStoryObj } from "@storybook/react";
-import { componentsMeta, type UserProp } from "@webstudio-is/react-sdk";
+import { getComponentMetaProps, type UserProp } from "@webstudio-is/react-sdk";
import { PropsPanel } from "./props-panel";
export default {
@@ -64,7 +64,7 @@ export const DefaultProps: ComponentStoryObj<typeof PropsPanel> = {
},
};
-const meta = componentsMeta["Button"];
+const meta = getComponentMetaProps("Button");
export const AllProps: ComponentStoryObj<typeof PropsPanel> = {
args: {
diff --git a/apps/designer/app/designer/features/props-panel/props-panel.tsx b/apps/designer/app/designer/features/props-panel/props-panel.tsx
index 892dcdcd78..ff1f55d2fa 100644
--- a/apps/designer/app/designer/features/props-panel/props-panel.tsx
+++ b/apps/designer/app/designer/features/props-panel/props-panel.tsx
@@ -1,5 +1,5 @@
import {
- componentsMeta,
+ getComponentMetaProps,
type Instance,
type UserProp,
} from "@webstudio-is/react-sdk";
@@ -121,7 +121,7 @@ const Property = ({
onChangePropValue,
onDelete,
}: PropertyProps) => {
- const meta = componentsMeta[component];
+ const meta = getComponentMetaProps(component);
const argType = meta[userProp.prop as keyof typeof meta];
const isInvalid =
diff --git a/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts b/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts
index 2410e67056..a133664c79 100644
--- a/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts
+++ b/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts
@@ -1,11 +1,11 @@
import { renderHook, act } from "@testing-library/react-hooks";
-import { components, UserProp } from "@webstudio-is/react-sdk";
+import { type ComponentName, UserProp } from "@webstudio-is/react-sdk";
import { nanoid } from "nanoid";
import type { SelectedInstanceData } from "@webstudio-is/project";
import { usePropsLogic } from "./use-props-logic";
const getSelectedInstanceData = (
- componentName: keyof typeof components,
+ componentName: ComponentName,
props: UserProp[]
): SelectedInstanceData => {
return {
diff --git a/apps/designer/app/designer/features/props-panel/use-props-logic.ts b/apps/designer/app/designer/features/props-panel/use-props-logic.ts
index 4e2c76794d..f234c868f7 100644
--- a/apps/designer/app/designer/features/props-panel/use-props-logic.ts
+++ b/apps/designer/app/designer/features/props-panel/use-props-logic.ts
@@ -4,7 +4,7 @@ import type {
UserPropsUpdates,
} from "@webstudio-is/react-sdk";
import { type Publish } from "~/shared/pubsub";
-import { componentsMeta } from "@webstudio-is/react-sdk";
+import { getComponentMetaProps } from "@webstudio-is/react-sdk";
import ObjectId from "bson-objectid";
import produce from "immer";
import uniqBy from "lodash/uniqBy";
@@ -37,7 +37,7 @@ const getRequiredProps = (
selectedInstanceData: SelectedInstanceData
): UserProp[] => {
const { component } = selectedInstanceData;
- const meta = componentsMeta[component];
+ const meta = getComponentMetaProps(component);
return Object.entries(meta)
.filter(([_, value]) => value.required)
.map(([prop, _]) => ({
@@ -54,7 +54,7 @@ const getPropsWithDefaultValue = (
selectedInstanceData: SelectedInstanceData
): UserProp[] => {
const { component } = selectedInstanceData;
- const meta = componentsMeta[component];
+ const meta = getComponentMetaProps(component);
return Object.entries(meta)
.filter(([_, value]) => value.defaultValue != null)
.map(([prop, propObj]) => {
diff --git a/apps/designer/app/designer/features/sidebar-left/panels/components/component-thumb.tsx b/apps/designer/app/designer/features/sidebar-left/panels/components/component-thumb.tsx
index f2544d51b6..2fabc04a7f 100644
--- a/apps/designer/app/designer/features/sidebar-left/panels/components/component-thumb.tsx
+++ b/apps/designer/app/designer/features/sidebar-left/panels/components/component-thumb.tsx
@@ -1,4 +1,4 @@
-import { type Instance, components } from "@webstudio-is/react-sdk";
+import { type Instance, getComponentMeta } from "@webstudio-is/react-sdk";
import { forwardRef, type ElementRef, type ComponentProps } from "react";
import { Flex, Text, styled } from "@webstudio-is/design-system";
@@ -30,7 +30,7 @@ export const ComponentThumb = forwardRef<
ElementRef<typeof Thumb>,
ComponentThumbProps
>(({ component, ...rest }, ref) => {
- const { Icon, label } = components[component];
+ const { Icon, label } = getComponentMeta(component);
return (
<Thumb
direction="column"
diff --git a/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsx b/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsx
index 6d8800c0db..2c121afeb8 100644
--- a/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsx
+++ b/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsx
@@ -1,6 +1,10 @@
import { type MouseEventHandler, useState } from "react";
import { createPortal } from "react-dom";
-import { type Instance, components } from "@webstudio-is/react-sdk";
+import {
+ type Instance,
+ getComponentMeta,
+ componentNames,
+} from "@webstudio-is/react-sdk";
import { useSubscribe, type Publish } from "~/shared/pubsub";
import { Flex, useDrag, type Point } from "@webstudio-is/design-system";
import { PlusIcon } from "@webstudio-is/icons";
@@ -10,9 +14,9 @@ import { ComponentThumb } from "./component-thumb";
import { useCanvasRect, useZoom } from "~/designer/shared/nano-states";
import { Header, CloseButton } from "../../lib/header";
-const componentNames = (
- Object.keys(components) as Array<Instance["component"]>
-).filter((component) => components[component].isListed);
+const listedComponentNames = componentNames.filter(
+ (name) => getComponentMeta(name).isListed
+);
type DraggableThumbProps = {
onClick: MouseEventHandler<HTMLDivElement>;
@@ -74,7 +78,7 @@ const elementToComponentName = (element: Element) => {
return;
}
const { dragComponent } = parentWithData.dataset;
- return componentNames.find((component) => component === dragComponent);
+ return listedComponentNames.find((component) => component === dragComponent);
};
export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
@@ -142,7 +146,7 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
css={{ padding: "$spacing$3", overflow: "auto" }}
ref={useDragHandlers.rootRef}
>
- {componentNames.map((component: Instance["component"]) => (
+ {listedComponentNames.map((component: Instance["component"]) => (
<DraggableThumb
key={component}
component={component}
diff --git a/apps/designer/app/designer/features/workspace/canvas-tools/outline/label.tsx b/apps/designer/app/designer/features/workspace/canvas-tools/outline/label.tsx
index bcc4afa305..a301856f64 100644
--- a/apps/designer/app/designer/features/workspace/canvas-tools/outline/label.tsx
+++ b/apps/designer/app/designer/features/workspace/canvas-tools/outline/label.tsx
@@ -1,6 +1,6 @@
import { useCallback, useState } from "react";
import { styled, type Rect } from "@webstudio-is/design-system";
-import { type Instance, components } from "@webstudio-is/react-sdk";
+import { type Instance, getComponentMeta } from "@webstudio-is/react-sdk";
type LabelPosition = "top" | "inside" | "bottom";
type LabelRefCallback = (element: HTMLElement | null) => void;
@@ -74,7 +74,7 @@ type LabelProps = {
export const Label = ({ component, instanceRect }: LabelProps) => {
const [labelRef, position] = useLabelPosition(instanceRect);
- const { Icon, label } = components[component];
+ const { Icon, label } = getComponentMeta(component);
return (
<LabelContainer position={position} ref={labelRef}>
<Icon width="1em" height="1em" />
diff --git a/apps/designer/app/designer/shared/inspector/component-info.tsx b/apps/designer/app/designer/shared/inspector/component-info.tsx
index bd5a5b89cd..bee801a1cd 100644
--- a/apps/designer/app/designer/shared/inspector/component-info.tsx
+++ b/apps/designer/app/designer/shared/inspector/component-info.tsx
@@ -1,4 +1,4 @@
-import { components } from "@webstudio-is/react-sdk";
+import { getComponentMeta } from "@webstudio-is/react-sdk";
import { Flex, Text } from "@webstudio-is/design-system";
import type { SelectedInstanceData } from "@webstudio-is/project";
@@ -15,7 +15,9 @@ export const ComponentInfo = ({
color: "$colors$slate11",
fontWeight: "500",
}}
- >{`Selected: ${components[selectedInstanceData.component].label}`}</Text>
+ >{`Selected: ${
+ getComponentMeta(selectedInstanceData.component).label
+ }`}</Text>
</Flex>
);
};
diff --git a/apps/designer/app/designer/shared/tree/index.tsx b/apps/designer/app/designer/shared/tree/index.tsx
index 9d7cbacfdc..5628c991d4 100644
--- a/apps/designer/app/designer/shared/tree/index.tsx
+++ b/apps/designer/app/designer/shared/tree/index.tsx
@@ -7,7 +7,7 @@ import {
type TreeProps,
type TreeItemRenderProps,
} from "@webstudio-is/design-system";
-import { components, Instance } from "@webstudio-is/react-sdk";
+import { getComponentMeta, Instance } from "@webstudio-is/react-sdk";
import { utils } from "@webstudio-is/project";
const instanceRelatedProps = {
@@ -15,13 +15,13 @@ const instanceRelatedProps = {
getItemPath: utils.tree.getInstancePath,
getItemPathWithPositions: utils.tree.getInstancePathWithPositions,
canLeaveParent(item: Instance) {
- return components[item.component].isInlineOnly !== true;
+ return getComponentMeta(item.component).isInlineOnly !== true;
},
canAcceptChild(item: Instance) {
- return components[item.component].canAcceptChildren;
+ return getComponentMeta(item.component).canAcceptChildren;
},
getItemChildren(item: Instance) {
- const component = components[item.component];
+ const component = getComponentMeta(item.component);
// We want to avoid calling .filter() unnecessarily, because this is a hot path for performance.
// We rely on the fact that only content editable or inline components may have `string` children.
@@ -37,7 +37,7 @@ const instanceRelatedProps = {
) as Instance[];
},
renderItem(props: TreeItemRenderProps<Instance>) {
- const { Icon, label } = components[props.itemData.component];
+ const { Icon, label } = getComponentMeta(props.itemData.component);
return (
<TreeItemBody {...props} selectionEvent="focus">
<TreeItemLabel prefix={<Icon />}>{label}</TreeItemLabel>
diff --git a/apps/designer/app/env.server.ts b/apps/designer/app/env.server.ts
index 06738d30d0..1c26652878 100644
--- a/apps/designer/app/env.server.ts
+++ b/apps/designer/app/env.server.ts
@@ -9,6 +9,8 @@ const env = {
PUBLISHER_ENDPOINT: process.env.PUBLISHER_ENDPOINT || null,
PUBLISHER_HOST: process.env.PUBLISHER_HOST || null,
BUILD_REQUIRE_SUBDOMAIN: process.env.BUILD_REQUIRE_SUBDOMAIN === "true",
+ // Must be set for Vercel deployments
+ RESIZE_ORIGIN: process.env.RESIZE_ORIGIN,
} as const;
export default env;
diff --git a/apps/designer/app/routes/$.tsx b/apps/designer/app/routes/$.tsx
index 6774d7b94c..7fd42bbd59 100644
--- a/apps/designer/app/routes/$.tsx
+++ b/apps/designer/app/routes/$.tsx
@@ -69,7 +69,13 @@ export const loader: LoaderFunction = async ({ request }): Promise<Data> => {
throw json("Page not found", { status: 404 });
}
- return { ...canvasData, env, mode };
+ const params: CanvasData["params"] = {};
+
+ if (env.RESIZE_ORIGIN != null) {
+ params.resizeOrigin = env.RESIZE_ORIGIN;
+ }
+
+ return { ...canvasData, env, mode, params };
};
export const ErrorBoundary: ErrorBoundaryComponent = ({ error }) => {
diff --git a/packages/image/package.json b/packages/image/package.json
index bc7846dc16..d2e441431b 100644
--- a/packages/image/package.json
+++ b/packages/image/package.json
@@ -11,7 +11,8 @@
"checks": "yarn typecheck && yarn lint && yarn test",
"dev": "tsup --watch",
"build:args": "generate-arg-types './src/*.tsx !./src/**/*.stories.tsx !./src/**/*.ws.tsx' && prettier --write \"**/*.props.json\"",
- "build": "rm -fr lib tsconfig.tsbuildinfo && tsc",
+ "build": "rm -fr lib tsconfig.tsbuildinfo && yarn build:cjs && tsc",
+ "build:cjs": "tsc --module commonjs --outDir lib/cjs && find lib/cjs -name '*.js' | while read NAME; do mv $NAME ${NAME%.js}.cjs; done",
"lint": "eslint ./src --ext .ts,.tsx --max-warnings 0",
"storybook:run": "start-storybook -p 6006",
"storybook:build": "build-storybook",
@@ -38,8 +39,8 @@
},
"module": "./lib/index.js",
"exports": {
- ".": "./lib/index.js",
- "./server": "./server.js"
+ "import": "./lib/index.js",
+ "require": "./lib/cjs/index.cjs"
},
"types": "lib/index.d.ts",
"files": [
diff --git a/packages/image/src/image-dev.stories.tsx b/packages/image/src/image-dev.stories.tsx
index d1573f1279..d9a776f12c 100644
--- a/packages/image/src/image-dev.stories.tsx
+++ b/packages/image/src/image-dev.stories.tsx
@@ -2,11 +2,7 @@
import React, { type ComponentProps, type HTMLAttributes } from "react";
import type { ComponentMeta, ComponentStory } from "@storybook/react";
-import {
- Image as ImagePrimitive,
- cloudflareImageLoader,
- localImageLoader,
-} from "./";
+import { Image as ImagePrimitive, loaders } from "./";
// to not allow include local assets everywhere, just enable it for this file
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -33,8 +29,8 @@ const imageSrc = USE_CLOUDFLARE_IMAGE_TRANSFORM
: localLogoImage;
const imageLoader = USE_CLOUDFLARE_IMAGE_TRANSFORM
- ? cloudflareImageLoader({ resizeOrigin: "https://webstudio.is" })
- : localImageLoader();
+ ? loaders.cloudflareImageLoader({ resizeOrigin: "https://webstudio.is" })
+ : loaders.localImageLoader();
const ImageBase: ComponentStory<
React.ForwardRefExoticComponent<
diff --git a/packages/image/src/index.ts b/packages/image/src/index.ts
index 1049e16356..62882121e1 100644
--- a/packages/image/src/index.ts
+++ b/packages/image/src/index.ts
@@ -1,4 +1,4 @@
export { Image } from "./image";
export type { ImageLoader } from "./image-optimize";
-export { cloudflareImageLoader, localImageLoader } from "./image-loaders";
+export * as loaders from "./image-loaders";
export { default as imageProps } from "./__generated__/image.props.json";
diff --git a/packages/project/src/shared/tree-utils/create-instance.ts b/packages/project/src/shared/tree-utils/create-instance.ts
index 8995cef2bc..8d50b9bc38 100644
--- a/packages/project/src/shared/tree-utils/create-instance.ts
+++ b/packages/project/src/shared/tree-utils/create-instance.ts
@@ -1,5 +1,5 @@
import ObjectId from "bson-objectid";
-import { type Instance, components } from "@webstudio-is/react-sdk";
+import { type Instance, getComponentMeta } from "@webstudio-is/react-sdk";
import { CssRule } from "@webstudio-is/css-data";
export const createInstanceId = () => {
@@ -17,7 +17,7 @@ export const createInstance = ({
children?: Instance["children"];
cssRules?: Array<CssRule>;
}): Instance => {
- const componentMeta = components[component];
+ const componentMeta = getComponentMeta(component);
return {
component,
id: id === undefined ? createInstanceId() : id,
diff --git a/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.ts b/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.ts
index da5a74e182..0126842d62 100644
--- a/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.ts
+++ b/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.ts
@@ -1,4 +1,4 @@
-import { Instance, components } from "@webstudio-is/react-sdk";
+import { Instance, getComponentMeta } from "@webstudio-is/react-sdk";
import { getInstancePath } from "./get-instance-path";
export const findClosestNonInlineParent = (
@@ -7,5 +7,7 @@ export const findClosestNonInlineParent = (
): Instance | undefined => {
const path = getInstancePath(rootInstance, instanceId);
path.reverse();
- return path.find((item) => components[item.component].isInlineOnly === false);
+ return path.find(
+ (item) => getComponentMeta(item.component).isInlineOnly === false
+ );
};
diff --git a/packages/project/src/shared/tree-utils/populate.ts b/packages/project/src/shared/tree-utils/populate.ts
index 6da307af1e..e647a46b92 100644
--- a/packages/project/src/shared/tree-utils/populate.ts
+++ b/packages/project/src/shared/tree-utils/populate.ts
@@ -1,5 +1,5 @@
import { Breakpoint } from "@webstudio-is/css-data";
-import { type Instance, components } from "@webstudio-is/react-sdk";
+import { type Instance, getComponentMeta } from "@webstudio-is/react-sdk";
/**
* Populate instance with:
@@ -11,7 +11,7 @@ export const populateInstance = (
breakpoint: Breakpoint["id"] = ""
): Instance => {
const populatedInstance = { ...instance };
- const componentMeta = components[instance.component];
+ const componentMeta = getComponentMeta(instance.component);
if (componentMeta !== undefined && "defaultStyle" in componentMeta) {
const cssRule = {
breakpoint,
diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.json
index 75a168b75b..d5ba4d6b96 100644
--- a/packages/react-sdk/package.json
+++ b/packages/react-sdk/package.json
@@ -34,6 +34,7 @@
"@storybook/react": "^6.5.6",
"@storybook/testing-library": "^0.0.11",
"@types/node": "^17.0.21",
+ "@webstudio-is/image": "*",
"@webstudio-is/jest-config": "*",
"@webstudio-is/prisma-client": "*",
"@webstudio-is/generate-arg-types": "*",
diff --git a/packages/react-sdk/src/app/custom-components/image.tsx b/packages/react-sdk/src/app/custom-components/image.tsx
new file mode 100644
index 0000000000..6b9e5ac4f1
--- /dev/null
+++ b/packages/react-sdk/src/app/custom-components/image.tsx
@@ -0,0 +1,40 @@
+import {
+ forwardRef,
+ useMemo,
+ type ComponentProps,
+ type ElementRef,
+} from "react";
+import { Image as WebstudioImage, loaders } from "@webstudio-is/image";
+import { Image as SdkImage } from "../../components/image";
+import { useUserPropsAsset } from "../../user-props/use-user-props-asset";
+import { idAttribute } from "../../tree/wrapper-component";
+import { getParams } from "../params";
+
+const defaultTag = "img";
+
+type Props = ComponentProps<typeof WebstudioImage> & { [idAttribute]: string };
+
+export const Component = forwardRef<ElementRef<typeof defaultTag>, Props>(
+ (props, ref) => {
+ const componentId = props[idAttribute] as string;
+
+ const asset = useUserPropsAsset(componentId, "src");
+ const params = getParams();
+
+ const loader = useMemo(() => {
+ if (asset == null) return null;
+ if (asset.location === "REMOTE")
+ return loaders.cloudflareImageLoader(params);
+ return loaders.localImageLoader();
+ }, [asset, params]);
+
+ if (asset === null || loader == null)
+ return <SdkImage {...props} ref={ref} />;
+
+ return (
+ <WebstudioImage {...props} loader={loader} optimize={true} ref={ref} />
+ );
+ }
+);
+
+Component.displayName = "Image";
diff --git a/packages/react-sdk/src/app/custom-components/index.ts b/packages/react-sdk/src/app/custom-components/index.ts
new file mode 100644
index 0000000000..e2620a03d0
--- /dev/null
+++ b/packages/react-sdk/src/app/custom-components/index.ts
@@ -0,0 +1 @@
+export * as Image from "./image";
diff --git a/packages/react-sdk/src/remix/handle-request.server.tsx b/packages/react-sdk/src/app/handle-request.server.tsx
similarity index 100%
rename from packages/react-sdk/src/remix/handle-request.server.tsx
rename to packages/react-sdk/src/app/handle-request.server.tsx
diff --git a/packages/react-sdk/src/remix/index.ts b/packages/react-sdk/src/app/index.ts
similarity index 71%
rename from packages/react-sdk/src/remix/index.ts
rename to packages/react-sdk/src/app/index.ts
index 1287530143..aed4524196 100644
--- a/packages/react-sdk/src/remix/index.ts
+++ b/packages/react-sdk/src/app/index.ts
@@ -1,2 +1,3 @@
export * from "./root";
export * from "./handle-request.server";
+export * from "./params";
diff --git a/packages/react-sdk/src/app/params.ts b/packages/react-sdk/src/app/params.ts
new file mode 100644
index 0000000000..fd4b2dbdaf
--- /dev/null
+++ b/packages/react-sdk/src/app/params.ts
@@ -0,0 +1,13 @@
+export type Params = {
+ resizeOrigin?: string;
+};
+
+let params: Params | null = {};
+
+const emptyParams: Params = {};
+
+export const getParams = (): Params => params ?? emptyParams;
+
+export const setParams = (newParams: Params | null) => {
+ params = newParams;
+};
diff --git a/packages/react-sdk/src/remix/root.tsx b/packages/react-sdk/src/app/root.tsx
similarity index 100%
rename from packages/react-sdk/src/remix/root.tsx
rename to packages/react-sdk/src/app/root.tsx
diff --git a/packages/react-sdk/src/components/index.test.ts b/packages/react-sdk/src/components/index.test.ts
index 0265c11cfc..40e39d8616 100644
--- a/packages/react-sdk/src/components/index.test.ts
+++ b/packages/react-sdk/src/components/index.test.ts
@@ -1,12 +1,6 @@
-import * as components from "./index";
+import { componentNames, getComponentMeta } from "./index";
import { WsComponentMeta } from "./component-type";
-test.each(Object.entries(components))(
- "validating meta definition of %s",
- (name, component) => {
- if (name === "default") {
- return;
- }
- WsComponentMeta.parse(component);
- }
-);
+test.each(componentNames)("validating meta definition of %s", (name) => {
+ WsComponentMeta.parse(getComponentMeta(name));
+});
diff --git a/packages/react-sdk/src/components/index.ts b/packages/react-sdk/src/components/index.ts
index bb57b1d48c..de89e52907 100644
--- a/packages/react-sdk/src/components/index.ts
+++ b/packages/react-sdk/src/components/index.ts
@@ -1,15 +1,87 @@
-export { default as Body } from "./body.ws";
-export { default as Box } from "./box.ws";
-export { default as TextBlock } from "./text-block.ws";
-export { default as Heading } from "./heading.ws";
-export { default as Paragraph } from "./paragraph.ws";
-export { default as Link } from "./link.ws";
-export { default as Span } from "./span.ws";
-export { default as Bold } from "./bold.ws";
-export { default as Italic } from "./italic.ws";
-export { default as Superscript } from "./superscript.ws";
-export { default as Subscript } from "./subscript.ws";
-export { default as Button } from "./button.ws";
-export { default as Input } from "./input.ws";
-export { default as Form } from "./form.ws";
-export { default as Image } from "./image.ws";
+import Body from "./body.ws";
+import Box from "./box.ws";
+import TextBlock from "./text-block.ws";
+import Heading from "./heading.ws";
+import Paragraph from "./paragraph.ws";
+import Link from "./link.ws";
+import Span from "./span.ws";
+import Bold from "./bold.ws";
+import Italic from "./italic.ws";
+import Superscript from "./superscript.ws";
+import Subscript from "./subscript.ws";
+import Button from "./button.ws";
+import Input from "./input.ws";
+import Form from "./form.ws";
+import Image from "./image.ws";
+
+const components = {
+ Body,
+ Box,
+ TextBlock,
+ Heading,
+ Paragraph,
+ Link,
+ Span,
+ Bold,
+ Italic,
+ Superscript,
+ Subscript,
+ Button,
+ Input,
+ Form,
+ Image,
+} as const;
+
+type RegisteredComponents = Partial<{
+ [p in ComponentName]: {
+ // @todo: Anyone knows what the type can be for any React Component?
+ // eslint-disable-next-line @typescript-eslint/ban-types
+ Component: {};
+ meta?: Partial<Omit<typeof components[p], "Component">>;
+ };
+}>;
+
+let registeredComponents: RegisteredComponents | null = null;
+
+export type ComponentName = keyof typeof components;
+
+export const componentNames = Object.keys(components) as ComponentName[];
+
+export const getComponentMeta = <Name extends ComponentName>(
+ name: Name
+): Omit<typeof components[Name], "Component"> => {
+ if (
+ registeredComponents != null &&
+ name in registeredComponents &&
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ registeredComponents[name]!.meta != null
+ ) {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ return { ...components[name], ...registeredComponents[name]!.meta };
+ }
+
+ return components[name];
+};
+
+/**
+ * @todo Remove Component from meta and read directly (via import),
+ * as meta information is not needed during production render.
+ **/
+export const getComponent = <Name extends ComponentName>(
+ name: Name
+): typeof components[Name]["Component"] => {
+ return registeredComponents != null && name in registeredComponents
+ ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ (registeredComponents[name]!
+ .Component as typeof components[Name]["Component"])
+ : components[name].Component;
+};
+
+/**
+ * @todo: Allow register any component.
+ * Now we can register only existings Components, as all our type system would
+ * break otherwise, see getComponent etc. So its overwriteComponent now
+ **/
+export const registerComponents = (components: RegisteredComponents) => {
+ registeredComponents = components;
+};
diff --git a/packages/react-sdk/src/components/meta.ts b/packages/react-sdk/src/components/meta.ts
index 9ecd091efe..d8e783b383 100644
--- a/packages/react-sdk/src/components/meta.ts
+++ b/packages/react-sdk/src/components/meta.ts
@@ -58,6 +58,6 @@ type MetaProp =
type MetaProps = Record<string, MetaProp>;
-// Probably better instead of JSON to generate ts with `as const`
-export const componentsMeta: Record<keyof typeof meta, MetaProps> =
- meta as Record<keyof typeof meta, MetaProps>;
+export const getComponentMetaProps = (name: keyof typeof meta): MetaProps => {
+ return meta[name] as MetaProps;
+};
diff --git a/packages/react-sdk/src/db/instance.ts b/packages/react-sdk/src/db/instance.ts
index 2bf3904626..f901149477 100644
--- a/packages/react-sdk/src/db/instance.ts
+++ b/packages/react-sdk/src/db/instance.ts
@@ -1,12 +1,12 @@
import { CssRule } from "@webstudio-is/css-data";
import { z } from "zod";
-import * as components from "../components";
+import { ComponentName } from "../components";
// This should be used when passing a lot of data is potentially costly.
// For example, when passing data from an iframe.
export type BaseInstance = {
id: string;
- component: keyof typeof components;
+ component: ComponentName;
cssRules: Array<CssRule>;
};
diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.ts
index 910e6096c7..a4b245bd94 100644
--- a/packages/react-sdk/src/index.ts
+++ b/packages/react-sdk/src/index.ts
@@ -1,8 +1,9 @@
export * from "./css";
export * from "./tree";
-export * as components from "./components";
+export * from "./components";
export * from "./components/meta";
export * from "./user-props";
export * from "./pubsub";
export * from "./db";
-export * from "./remix";
+export * from "./app";
+export * as customComponents from "./app/custom-components";
diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.ts
index bb1841bdb6..e7d06b8831 100644
--- a/packages/react-sdk/src/tree/root.ts
+++ b/packages/react-sdk/src/tree/root.ts
@@ -5,12 +5,16 @@ import { WrapperComponent } from "./wrapper-component";
import type { Asset } from "@webstudio-is/asset-uploader";
import { type ComponentProps } from "react";
import type { Breakpoint } from "@webstudio-is/css-data";
+import { registerComponents } from "../components";
+import * as customComponents from "../app/custom-components";
+import { setParams, type Params } from "../app/params";
export type Data = {
tree: Tree | null;
breakpoints: Array<Breakpoint>;
props: Array<InstanceProps>;
assets: Array<Asset>;
+ params?: Params;
};
type RootProps = {
@@ -26,6 +30,10 @@ export const InstanceRoot = ({
throw new Error("Tree is null");
}
useAllUserProps(data.props);
+ setParams(data.params ?? null);
+
+ registerComponents(customComponents);
+
return createElementsTree({
instance: data.tree.root,
Component: Component ?? WrapperComponent,
diff --git a/packages/react-sdk/src/tree/wrapper-component.tsx b/packages/react-sdk/src/tree/wrapper-component.tsx
index 526941caaf..41369234ee 100644
--- a/packages/react-sdk/src/tree/wrapper-component.tsx
+++ b/packages/react-sdk/src/tree/wrapper-component.tsx
@@ -1,6 +1,6 @@
import { Fragment } from "react";
import type { Instance } from "../db";
-import * as components from "../components";
+import { getComponent } from "../components";
import { useUserProps } from "../user-props/use-user-props";
import type { OnChangeChildren } from "./create-elements-tree";
@@ -37,7 +37,7 @@ export const WrapperComponent = ({
children,
...rest
}: WrapperComponentProps) => {
- const { Component } = components[instance.component];
+ const Component = getComponent(instance.component);
const userProps = useUserProps(instance.id);
const props = { ...userProps, ...rest, [idAttribute]: instance.id };
return (
diff --git a/packages/react-sdk/src/user-props/use-user-props-asset.ts b/packages/react-sdk/src/user-props/use-user-props-asset.ts
new file mode 100644
index 0000000000..a537db5559
--- /dev/null
+++ b/packages/react-sdk/src/user-props/use-user-props-asset.ts
@@ -0,0 +1,26 @@
+import { useMemo } from "react";
+import { type Instance } from "../db";
+import { type UserProp } from "./schema";
+import { useAllUserProps } from "./all-user-props";
+import type { Asset } from "@webstudio-is/asset-uploader";
+
+/**
+ * Get asset for prop, like src on the Image component
+ */
+export const useUserPropsAsset = (
+ instanceId: Instance["id"],
+ propName: UserProp["prop"]
+): Asset | null => {
+ const [allUserProps] = useAllUserProps();
+
+ const propsData = allUserProps[instanceId];
+ const asset = useMemo(() => {
+ if (propsData == null) return null;
+ const prop = propsData.props.find((prop) => prop.prop === propName);
+ if (prop == null) return null;
+
+ return prop.asset ?? null;
+ }, [propName, propsData]);
+
+ return asset;
+};
diff --git a/packages/react-sdk/src/user-props/use-user-props.ts b/packages/react-sdk/src/user-props/use-user-props.ts
index 6f9e33aca7..fe0a193d20 100644
--- a/packages/react-sdk/src/user-props/use-user-props.ts
+++ b/packages/react-sdk/src/user-props/use-user-props.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from "react";
+import { useMemo } from "react";
import { type Instance } from "../db";
import { type UserProp } from "./schema";
import { useAllUserProps } from "./all-user-props";
@@ -13,24 +13,13 @@ export const useUserProps = (instanceId: Instance["id"]) => {
const [allUserProps] = useAllUserProps();
const propsData = allUserProps[instanceId];
- const initialUserProps = useMemo(() => {
- if (propsData === undefined) return {};
+ const props = useMemo(() => {
+ if (propsData == null) return {};
return propsData.props.reduce((props, { prop, value }) => {
props[prop] = value;
return props;
}, {} as UserProps);
}, [propsData]);
- const [props, setProps] = useState<UserProps>(initialUserProps);
-
- useEffect(() => {
- if (propsData == undefined) return;
- const nextProps: UserProps = {};
- for (const prop of propsData.props) {
- nextProps[prop.prop] = prop.value;
- }
- setProps(nextProps);
- }, [propsData]);
-
return props;
};
diff --git a/packages/react-sdk/tsconfig.json b/packages/react-sdk/tsconfig.json
index 651a772bea..40682627c2 100644
--- a/packages/react-sdk/tsconfig.json
+++ b/packages/react-sdk/tsconfig.json
@@ -35,6 +35,10 @@
"path": "../icons"
},
+ {
+ "path": "../image"
+ },
+
{
"path": "../prisma-client"
}