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
Add tooltip (#1957)
Ivan Starkovf5cbd28962ab
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 27fca951c9..fbd54441cf 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@@ -26,6 +26,7 @@ import {import { MetaIcon } from "~/builder/shared/meta-icon";import { registeredComponentMetasStore } from "~/shared/nano-states";import { getMetaMaps } from "./get-meta-maps";+import { isFeatureEnabled } from "@webstudio-is/feature-flags";type TabContentProps = {onSetActiveTab: (tabName: TabName) => void;@@ -67,6 +68,9 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {<ScrollArea>{componentCategories.filter((category) => category !== "hidden")+ .filter((category) =>+ isFeatureEnabled("radix") ? true : category !== "radix"+ ).map((category) => (<CollapsibleSection label={category} key={category} fullWidth><ArrowFocusdiff --git a/apps/builder/app/canvas/collapsed.ts b/apps/builder/app/canvas/collapsed.tsindex e1ebb23d8c..e653758e05 100644--- a/apps/builder/app/canvas/collapsed.ts+++ b/apps/builder/app/canvas/collapsed.ts@@ -9,6 +9,7 @@ import {breakpointsStore,instancesStore,registeredComponentMetasStore,+ selectedPageStore,stylesIndexStore,} from "~/shared/nano-states";import { selectedBreakpointStore } from "~/shared/nano-states";@@ -92,8 +93,21 @@ const getInstanceSize = (instanceId: string, tagName: HtmlTags | undefined) => {};};+const MAX_SIZE_TO_USE_OPTIMIZATION = 50;+const recalculate = () => {- const instanceIds = Array.from(instanceIdSet);+ const rootInstanceId = selectedPageStore.get()?.rootInstanceId;++ // Below algorithm quickly finds the common ancestor of all elements with an instanceId.+ // However, for a large number of elements, it's more efficient to calculate from the root.+ // In almost all cases, if instanceIdsSet >= MAX_SIZE_TO_USE_OPTIMIZATION, it likely includes all elements.+ const instanceIds =+ instanceIdSet.size < MAX_SIZE_TO_USE_OPTIMIZATION+ ? Array.from(instanceIdSet)+ : rootInstanceId !== undefined+ ? [rootInstanceId]+ : [];+instanceIdSet.clear();if (instanceIds.length === 0) {return;diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex 939252b892..67a44bd587 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -1,4 +1,11 @@-import { type MouseEvent, type FormEvent, useEffect } from "react";+import {+ type MouseEvent,+ type FormEvent,+ useEffect,+ forwardRef,+ type RefObject,+ useState,+} from "react";import { Suspense, lazy, useCallback, useRef } from "react";import { useStore } from "@nanostores/react";import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";@@ -16,6 +23,7 @@ import {componentAttribute,showAttribute,useInstanceProps,+ selectorIdAttribute,} from "@webstudio-is/react-sdk";import {instancesStore,@@ -33,6 +41,9 @@ import {} from "~/shared/tree-utils";import { SelectedInstanceConnector } from "./selected-instance-connector";import { handleLinkClick } from "./link";+import { mergeRefs } from "@react-aria/utils";+import { composeEventHandlers } from "@radix-ui/primitive";+import { setDataCollapsed } from "~/canvas/collapsed";const TextEditor = lazy(() => import("../text-editor"));@@ -108,12 +119,84 @@ type WebstudioComponentDevProps = {components: Components;};-export const WebstudioComponentDev = ({- instance,- instanceSelector,- children,- components,-}: WebstudioComponentDevProps) => {+/**+ * Radix's VisuallyHiddenPrimitive.Root https://github.com/radix-ui/primitives/blob/main/packages/react/visually-hidden/src/VisuallyHidden.tsx+ * component makes content from hidden elements accessible to screen readers.+ * react-aria VisuallyHidden https://github.com/adobe/react-spectrum/blob/e4bc3269fa41aa096700445c6bfa9c8620545e6a/packages/%40react-aria/visually-hidden/src/VisuallyHidden.tsx#L32-L43+ * The problem we're addressing is that the Radix reuses the same Content children for VisuallyHiddenPrimitive.Root within the Tooltip component.+ * Using the same Content children, however, leads to duplicated React elements, breaking our 'isSelected' logic.+ * To prevent this, we check if an instance is a descendant of VisuallyHiddenPrimitive.Root, and if so,+ * we avoid rendering it.+ */+const useIsVisuallyHidden = (ref: RefObject<HTMLElement>) => {+ const [isScreenReaderDescendant, setIsScreenReaderDescendant] =+ useState(false);++ useEffect(() => {+ if (ref.current !== null) {+ for (+ let element: HTMLElement | null = ref.current;+ element !== null;+ element = element.parentElement+ ) {+ if (+ element.style.overflow === "hidden" &&+ element.style.clip === "rect(0px, 0px, 0px, 0px)" &&+ element.style.position === "absolute" &&+ element.style.width === "1px" &&+ element.style.height === "1px"+ ) {+ setIsScreenReaderDescendant(true);+ return;+ }+ }+ }+ }, [ref]);++ return isScreenReaderDescendant;+};++/**+ * For some components that are wrapped with Radix Slot-like components (Triggers etc where asChild=true),+ * Slots in react-aria https://react-spectrum.adobe.com/react-spectrum/layout.html#slots+ * events are passed implicitly. We aim to merge these implicit events with the explicitly defined ones.+ **/+type ImplicitEvents = {+ onClick?: undefined | ((event: never) => void);+ onSubmit?: undefined | ((event: never) => void);+ /**+ * We ignore the remaining events because we currently detect events using the 'on' prefix.+ * This approach (defining type like above instead of Partial<Record<`on${string}`, Handler>>)+ * is necessary due to our TypeScript settings, where 'no exactOptionalPropertyTypes' is set,+ * which makes it impossible to define a Partial<Record<>> with optional keys.+ * (without exactOptionalPropertyTypes ts defines it as {[key: string]: Handler | undefined)}+ * instead of {[key: string]?: Handler | undefined)})+ **/+};++const existingElements = new Set<string>();++/**+ * We are identifying newly created instances like Tooltips and ensuring the calculation of 'collapsed' elements.+ */+const useCollapsedOnNewElement = (instanceId: Instance["id"]) => {+ useEffect(() => {+ if (existingElements.has(instanceId) === false) {+ setDataCollapsed(instanceId);+ }++ existingElements.add(instanceId);+ return () => {+ existingElements.delete(instanceId);+ };+ }, [instanceId]);+};++// eslint-disable-next-line react/display-name+export const WebstudioComponentDev = forwardRef<+ HTMLElement,+ WebstudioComponentDevProps & ImplicitEvents+>(({ instance, instanceSelector, children, components, ...restProps }, ref) => {const instanceId = instance.id;const instanceElementRef = useRef<HTMLElement>(null);const instanceStyles = useInstanceStyles(instanceId);@@ -134,6 +217,8 @@ export const WebstudioComponentDev = ({);const isPreviewMode = useStore(isPreviewModeStore);+ useCollapsedOnNewElement(instanceId);+// Scroll the selected instance into view when selected from navigator.useEffect(() => {if (isSelected) {@@ -158,6 +243,11 @@ export const WebstudioComponentDev = ({}});+ const isScreenReaderDescendant = useIsVisuallyHidden(instanceElementRef);+ if (isScreenReaderDescendant) {+ return <></>;+ }+const readonlyProps =isPreviewMode === false &&(instance.component === "Input" || instance.component === "Textarea")@@ -178,8 +268,6 @@ export const WebstudioComponentDev = ({...userProps,...readonlyProps,tabIndex: 0,- [componentAttribute]: instance.component,- [idAttribute]: instance.id,onClick: (event: MouseEvent) => {event.preventDefault();if (event.currentTarget instanceof HTMLAnchorElement) {@@ -199,8 +287,33 @@ export const WebstudioComponentDev = ({userProps.onSubmit(event);}},+ [componentAttribute]: instance.component,+ [idAttribute]: instance.id,+ [selectorIdAttribute]: instanceSelector.join(","),};+ const composedHandlers: ImplicitEvents = {};++ /**+ * We combine Radix's implicit event handlers with user-defined ones, such as onClick or onSubmit.+ * For instance, a Button within a TooltipTrigger receives+ * an onClick handler from the TooltipTrigger.+ * We might also need an additional onClick handler on the Button for other purposes (setting variable).+ **/+ for (const [key, value] of Object.entries(restProps)) {+ const propHandler = props[key as keyof typeof props];+ if (+ key.startsWith("on") &&+ propHandler !== undefined &&+ typeof propHandler === "function"+ ) {+ composedHandlers[key as keyof ImplicitEvents] = composeEventHandlers(+ value,+ propHandler+ );+ }+ }+const instanceElement = (<>{isSelected && (@@ -212,7 +325,12 @@ export const WebstudioComponentDev = ({instanceProps={instanceProps}/>)}- <Component {...props} ref={instanceElementRef}>+ <Component+ {...restProps}+ {...props}+ {...composedHandlers}+ ref={mergeRefs(instanceElementRef, ref)}+ >{renderWebstudioComponentChildren(children)}</Component></>@@ -264,4 +382,4 @@ export const WebstudioComponentDev = ({/></Suspense>);-};+});diff --git a/apps/builder/app/shared/dom-utils.ts b/apps/builder/app/shared/dom-utils.tsindex 84eea5f2e8..9331132d82 100644--- a/apps/builder/app/shared/dom-utils.ts+++ b/apps/builder/app/shared/dom-utils.ts@@ -1,5 +1,5 @@import type { Instance } from "@webstudio-is/project-build";-import { idAttribute } from "@webstudio-is/react-sdk";+import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";import type { InstanceSelector } from "./tree-utils";export const getInstanceIdFromElement = (@@ -10,16 +10,13 @@ export const getInstanceIdFromElement = (// traverse dom to the root and find all instancesexport const getInstanceSelectorFromElement = (element: Element) => {- const instanceSelector: InstanceSelector = [];- let matched: undefined | Element =+ // Change logic to support Portals+ const matched: undefined | Element =element.closest(`[${idAttribute}]`) ?? undefined;- while (matched) {- const instanceId = matched.getAttribute(idAttribute) ?? undefined;- if (instanceId !== undefined) {- instanceSelector.push(instanceId);- }- matched = matched.parentElement?.closest(`[${idAttribute}]`) ?? undefined;- }++ const instanceSelector: InstanceSelector =+ matched?.getAttribute(selectorIdAttribute)?.split(",") ?? [];+if (instanceSelector.length === 0) {return;}@@ -29,12 +26,11 @@ export const getInstanceSelectorFromElement = (element: Element) => {export const getElementByInstanceSelector = (instanceSelector: InstanceSelector | Readonly<InstanceSelector>) => {- // query instance from root to target- const domSelector = instanceSelector- .map((id) => `[${idAttribute}="${id}"]`)- .reverse()- .join(" ");- return document.querySelector<HTMLElement>(domSelector) ?? undefined;+ return (+ document.querySelector<HTMLElement>(+ `[${selectorIdAttribute}="${instanceSelector.join(",")}"]`+ ) ?? undefined+ );};type Rect = {diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 3b35076e94..6bab6cd5a3 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -29,6 +29,7 @@"@nanostores/react": "^0.7.1","@radix-ui/react-select": "^1.2.2","@radix-ui/react-tooltip": "^1.0.6",+ "@radix-ui/primitive": "1.0.1","@react-aria/interactions": "^3.11.0","@react-aria/utils": "^3.13.3","@remix-run/node": "^1.18.1",diff --git a/packages/feature-flags/src/flags.ts b/packages/feature-flags/src/flags.tsindex ea5c5e0ad9..e830e93748 100644--- a/packages/feature-flags/src/flags.ts+++ b/packages/feature-flags/src/flags.ts@@ -2,3 +2,4 @@ export const example = false;export const dark = false;export const unsupportedBrowsers = false;export const displayContents = false;+export const radix = false;diff --git a/packages/generate-arg-types/src/arg-types.ts b/packages/generate-arg-types/src/arg-types.tsindex 98ff14b52e..ac7c2dbb05 100644--- a/packages/generate-arg-types/src/arg-types.ts+++ b/packages/generate-arg-types/src/arg-types.ts@@ -5,19 +5,23 @@ export type FilterPredicate = (prop: PropItem) => boolean;export const propsToArgTypes = (props: Record<string, PropItem>) => {const entries = Object.entries(props);- return entries- .sort((item1, item2) => {- return item1[0].localeCompare(item2[0]);- })- .reduce((result, current) => {- const [propName, prop] = current;+ return (+ entries+ .sort((item1, item2) => {+ return item1[0].localeCompare(item2[0]);+ })+ // Exclude webstudio builder props see react-sdk/src/tree/webstudio-component.tsx+ .filter(([propName]) => propName.startsWith("data-ws-") === false)+ .reduce((result, current) => {+ const [propName, prop] = current;- const argType = getArgType(prop);- if (argType != null) {- result[propName] = argType;- }- return result;- }, {} as Record<string, PropMeta>);+ const argType = getArgType(prop);+ if (argType != null) {+ result[propName] = argType;+ }+ return result;+ }, {} as Record<string, PropMeta>)+ );};const matchers = {diff --git a/packages/react-sdk/src/components/component-meta.ts b/packages/react-sdk/src/components/component-meta.tsindex d2952124a6..938649b77c 100644--- a/packages/react-sdk/src/components/component-meta.ts+++ b/packages/react-sdk/src/components/component-meta.ts@@ -22,6 +22,7 @@ export const componentCategories = ["text","media","forms",+ "radix","hidden",] as const;diff --git a/packages/react-sdk/src/tree/create-elements-tree.tsx b/packages/react-sdk/src/tree/create-elements-tree.tsxindex 7bc30d3670..499905727c 100644--- a/packages/react-sdk/src/tree/create-elements-tree.tsx+++ b/packages/react-sdk/src/tree/create-elements-tree.tsx@@ -1,4 +1,8 @@-import { type ComponentProps, Fragment } from "react";+import {+ Fragment,+ type ForwardRefExoticComponent,+ type RefAttributes,+} from "react";import type { ReadableAtom } from "nanostores";import { Scripts, ScrollRestoration } from "@remix-run/react";import type { Assets } from "@webstudio-is/asset-uploader";@@ -10,7 +14,7 @@ import {ReactSdkContext,} from "../context";import type { Pages, PropsByInstanceId } from "../props";-import type { WebstudioComponent } from "./webstudio-component";+import type { WebstudioComponentProps } from "./webstudio-component";type InstanceSelector = Instance["id"][];@@ -40,7 +44,10 @@ export const createElementsTree = ({) => DataSourceValues;dataSourceValuesStore: ReadableAtom<DataSourceValues>;onDataSourceUpdate: (newValues: DataSourceValues) => void;- Component: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;++ Component: ForwardRefExoticComponent<+ WebstudioComponentProps & RefAttributes<HTMLElement>+ >;components: Components;}) => {const rootInstance = instances.get(rootInstanceId);@@ -110,7 +117,9 @@ const createInstanceChildrenElements = ({instances: Instances;instanceSelector: InstanceSelector;children: Instance["children"];- Component: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;+ Component: ForwardRefExoticComponent<+ WebstudioComponentProps & RefAttributes<HTMLElement>+ >;components: Components;}) => {const elements = [];@@ -152,7 +161,9 @@ const createInstanceElement = ({}: {instance: Instance;instanceSelector: InstanceSelector;- Component: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;+ Component: ForwardRefExoticComponent<+ WebstudioComponentProps & RefAttributes<HTMLElement>+ >;children?: Array<JSX.Element | string>;components: Components;}) => {diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.tsindex e750bdd634..d2c7e64919 100644--- a/packages/react-sdk/src/tree/root.ts+++ b/packages/react-sdk/src/tree/root.ts@@ -1,4 +1,9 @@-import { useRef, type ComponentProps, useCallback } from "react";+import {+ useRef,+ useCallback,+ type ForwardRefExoticComponent,+ type RefAttributes,+} from "react";import {atom,computed,@@ -8,7 +13,10 @@ import {import { type Build, type Page } from "@webstudio-is/project-build";import type { Asset } from "@webstudio-is/asset-uploader";import { createElementsTree } from "./create-elements-tree";-import { WebstudioComponent } from "./webstudio-component";+import {+ WebstudioComponent,+ type WebstudioComponentProps,+} from "./webstudio-component";import { getPropsByInstanceId } from "../props";import type { Components } from "../components/components-utils";import type { Params, DataSourceValues } from "../context";@@ -32,7 +40,9 @@ type RootProps = {expression: string,values: DataSourceValues) => DataSourceValues;- Component?: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;+ Component?: ForwardRefExoticComponent<+ WebstudioComponentProps & RefAttributes<HTMLElement>+ >;components: Components;};diff --git a/packages/react-sdk/src/tree/webstudio-component.tsx b/packages/react-sdk/src/tree/webstudio-component.tsxindex 3ec7b8ab83..a01d388c39 100644--- a/packages/react-sdk/src/tree/webstudio-component.tsx+++ b/packages/react-sdk/src/tree/webstudio-component.tsx@@ -1,4 +1,4 @@-import { Fragment } from "react";+import { Fragment, forwardRef } from "react";import type { Instance } from "@webstudio-is/project-build";import type { Components } from "../components/components-utils";import { useInstanceProps } from "../props";@@ -26,20 +26,18 @@ export const renderWebstudioComponentChildren = (});};-type WebstudioComponentProps = {+export type WebstudioComponentProps = {instance: Instance;instanceSelector: Instance["id"][];children: Array<JSX.Element | string>;components: Components;};-export const WebstudioComponent = ({- instance,- instanceSelector,- children,- components,- ...rest-}: WebstudioComponentProps) => {+// eslint-disable-next-line react/display-name+export const WebstudioComponent = forwardRef<+ HTMLElement,+ WebstudioComponentProps+>(({ instance, instanceSelector, children, components, ...rest }, ref) => {const { [showAttribute]: show = true, ...instanceProps } = useInstanceProps(instance.id);@@ -57,13 +55,42 @@ export const WebstudioComponent = ({return <></>;}return (- <Component {...props}>+ <Component {...props} ref={ref}>{renderWebstudioComponentChildren(children)}</Component>);+});++export const idAttribute = "data-ws-id" as const;+export const selectorIdAttribute = "data-ws-selector" as const;+export const componentAttribute = "data-ws-component" as const;+export const showAttribute = "data-ws-show" as const;+export const collapsedAttribute = "data-ws-collapsed" as const;++export type WebstudioAttributes = {+ [idAttribute]?: string | undefined;+ [selectorIdAttribute]?: string | undefined;+ [componentAttribute]?: string | undefined;+ [showAttribute]?: string | undefined;+ [collapsedAttribute]?: string | undefined;};-export const idAttribute = "data-ws-id";-export const componentAttribute = "data-ws-component";-export const showAttribute = "data-ws-show";-export const collapsedAttribute = "data-ws-collapsed";+export const splitPropsWithWebstudioAttributes = <+ P extends WebstudioAttributes+>({+ [idAttribute]: idAttributeValue,+ [componentAttribute]: componentAttributeValue,+ [showAttribute]: showAttributeValue,+ [collapsedAttribute]: collapsedAttributeValue,+ [selectorIdAttribute]: parentIdAttributeValue,+ ...props+}: P): [WebstudioAttributes, Omit<P, keyof WebstudioAttributes>] => [+ {+ [idAttribute]: idAttributeValue,+ [componentAttribute]: componentAttributeValue,+ [showAttribute]: showAttributeValue,+ [collapsedAttribute]: collapsedAttributeValue,+ [selectorIdAttribute]: parentIdAttributeValue,+ },+ props,+];diff --git a/packages/sdk-components-react/package.json b/packages/sdk-components-react/package.jsonindex 1acadccaa4..39a5710d75 100644--- a/packages/sdk-components-react/package.json+++ b/packages/sdk-components-react/package.json@@ -47,6 +47,7 @@"react-dom": "^18.2.0"},"dependencies": {+ "@radix-ui/react-tooltip": "^1.0.6","@react-aria/utils": "^3.13.3","@webstudio-is/css-vars": "workspace:^","@webstudio-is/generate-arg-types": "workspace:^",diff --git a/packages/sdk-components-react/src/__generated__/radix-tooltip.props.ts b/packages/sdk-components-react/src/__generated__/radix-tooltip.props.tsnew file mode 100644index 0000000000..f72a14ff84--- /dev/null+++ b/packages/sdk-components-react/src/__generated__/radix-tooltip.props.ts@@ -0,0 +1,492 @@+import type { PropMeta } from "@webstudio-is/generate-arg-types";++export const propsTooltip: Record<string, PropMeta> = {+ defaultOpen: { required: false, control: "boolean", type: "boolean" },+ delayDuration: {+ description:+ "The duration from when the pointer enters the trigger until the tooltip gets opened. This will\noverride the prop with the same name passed to Provider.\n@defaultValue 700",+ required: false,+ control: "number",+ type: "number",+ },+ disableHoverableContent: {+ description:+ "When `true`, trying to hover the content will result in the tooltip closing as the pointer leaves the trigger.\n@defaultValue false",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ isOpen: {+ required: true,+ control: "radio",+ type: "string",+ options: ["open", "initial", "closed"],+ },+ open: { required: false, control: "boolean", type: "boolean" },+};+export const propsTooltipTrigger: Record<string, PropMeta> = {};+export const propsTooltipContent: Record<string, PropMeta> = {+ about: { required: false, control: "text", type: "string" },+ accessKey: { required: false, control: "text", type: "string" },+ align: {+ required: false,+ control: "radio",+ type: "string",+ options: ["center", "start", "end"],+ },+ alignOffset: { required: false, control: "number", type: "number" },+ "aria-activedescendant": {+ description:+ "Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-atomic": {+ description:+ "Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-autocomplete": {+ description:+ "Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be\npresented if they are made.",+ required: false,+ control: "select",+ type: "string",+ options: ["list", "none", "inline", "both"],+ },+ "aria-busy": {+ description:+ "Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-checked": {+ description:+ 'Indicates the current "checked" state of checkboxes, radio buttons, and other widgets.\n@see aria-pressed\n@see aria-selected.',+ required: false,+ control: "text",+ type: "string",+ },+ "aria-colcount": {+ description:+ "Defines the total number of columns in a table, grid, or treegrid.\n@see aria-colindex.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-colindex": {+ description:+ "Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.\n@see aria-colcount\n@see aria-colspan.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-colspan": {+ description:+ "Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.\n@see aria-colindex\n@see aria-rowspan.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-controls": {+ description:+ "Identifies the element (or elements) whose contents or presence are controlled by the current element.\n@see aria-owns.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-current": {+ description:+ "Indicates the element that represents the current item within a container or set of related elements.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-describedby": {+ description:+ "Identifies the element (or elements) that describes the object.\n@see aria-labelledby",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-details": {+ description:+ "Identifies the element that provides a detailed, extended description for the object.\n@see aria-describedby.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-disabled": {+ description:+ "Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.\n@see aria-hidden\n@see aria-readonly.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-dropeffect": {+ description:+ "Indicates what functions can be performed when a dragged object is released on the drop target.\n@deprecated in ARIA 1.1",+ required: false,+ control: "select",+ type: "string",+ options: ["link", "none", "copy", "execute", "move", "popup"],+ },+ "aria-errormessage": {+ description:+ "Identifies the element that provides an error message for the object.\n@see aria-invalid\n@see aria-describedby.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-expanded": {+ description:+ "Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-flowto": {+ description:+ "Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion,\nallows assistive technology to override the general default of reading in document source order.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-grabbed": {+ description:+ 'Indicates an element\'s "grabbed" state in a drag-and-drop operation.\n@deprecated in ARIA 1.1',+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-haspopup": {+ description:+ "Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-hidden": {+ description:+ "Indicates whether the element is exposed to an accessibility API.\n@see aria-disabled.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-invalid": {+ description:+ "Indicates the entered value does not conform to the format expected by the application.\n@see aria-errormessage.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-keyshortcuts": {+ description:+ "Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-label": {+ description: "A more descriptive label for accessibility purpose",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-labelledby": {+ description:+ "Identifies the element (or elements) that labels the current element.\n@see aria-describedby.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-level": {+ description:+ "Defines the hierarchical level of an element within a structure.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-live": {+ description:+ "Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.",+ required: false,+ control: "radio",+ type: "string",+ options: ["off", "assertive", "polite"],+ },+ "aria-modal": {+ description: "Indicates whether an element is modal when displayed.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-multiline": {+ description:+ "Indicates whether a text box accepts multiple lines of input or only a single line.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-multiselectable": {+ description:+ "Indicates that the user may select more than one item from the current selectable descendants.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-orientation": {+ description:+ "Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous.",+ required: false,+ control: "radio",+ type: "string",+ options: ["horizontal", "vertical"],+ },+ "aria-owns": {+ description:+ "Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship\nbetween DOM elements where the DOM hierarchy cannot be used to represent the relationship.\n@see aria-controls.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-placeholder": {+ description:+ "Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value.\nA hint could be a sample value or a brief description of the expected format.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-posinset": {+ description:+ "Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM.\n@see aria-setsize.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-pressed": {+ description:+ 'Indicates the current "pressed" state of toggle buttons.\n@see aria-checked\n@see aria-selected.',+ required: false,+ control: "text",+ type: "string",+ },+ "aria-readonly": {+ description:+ "Indicates that the element is not editable, but is otherwise operable.\n@see aria-disabled.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-relevant": {+ description:+ "Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified.\n@see aria-atomic.",+ required: false,+ control: "select",+ type: "string",+ options: [+ "text",+ "additions",+ "additions removals",+ "additions text",+ "all",+ "removals",+ "removals additions",+ "removals text",+ "text additions",+ "text removals",+ ],+ },+ "aria-required": {+ description:+ "Indicates that user input is required on the element before a form may be submitted.",+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-roledescription": {+ description:+ "Defines a human-readable, author-localized description for the role of an element.",+ required: false,+ control: "text",+ type: "string",+ },+ "aria-rowcount": {+ description:+ "Defines the total number of rows in a table, grid, or treegrid.\n@see aria-rowindex.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-rowindex": {+ description:+ "Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.\n@see aria-rowcount\n@see aria-rowspan.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-rowspan": {+ description:+ "Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.\n@see aria-rowindex\n@see aria-colspan.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-selected": {+ description:+ 'Indicates the current "selected" state of various widgets.\n@see aria-checked\n@see aria-pressed.',+ required: false,+ control: "boolean",+ type: "boolean",+ },+ "aria-setsize": {+ description:+ "Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM.\n@see aria-posinset.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-sort": {+ description:+ "Indicates if items in a table or grid are sorted in ascending or descending order.",+ required: false,+ control: "select",+ type: "string",+ options: ["none", "ascending", "descending", "other"],+ },+ "aria-valuemax": {+ description: "Defines the maximum allowed value for a range widget.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-valuemin": {+ description: "Defines the minimum allowed value for a range widget.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-valuenow": {+ description:+ "Defines the current value for a range widget.\n@see aria-valuetext.",+ required: false,+ control: "number",+ type: "number",+ },+ "aria-valuetext": {+ description:+ "Defines the human readable text alternative of aria-valuenow for a range widget.",+ required: false,+ control: "text",+ type: "string",+ },+ arrowPadding: { required: false, control: "number", type: "number" },+ asChild: { required: false, control: "boolean", type: "boolean" },+ autoCapitalize: { required: false, control: "text", type: "string" },+ autoCorrect: { required: false, control: "text", type: "string" },+ autoFocus: { required: false, control: "boolean", type: "boolean" },+ autoSave: { required: false, control: "text", type: "string" },+ avoidCollisions: { required: false, control: "boolean", type: "boolean" },+ className: { required: false, control: "text", type: "string" },+ color: { required: false, control: "color", type: "string" },+ content: { required: false, control: "text", type: "string" },+ contextMenu: { required: false, control: "text", type: "string" },+ datatype: { required: false, control: "text", type: "string" },+ defaultChecked: { required: false, control: "boolean", type: "boolean" },+ dir: { required: false, control: "text", type: "string" },+ draggable: { required: false, control: "boolean", type: "boolean" },+ hidden: { required: false, control: "boolean", type: "boolean" },+ hideWhenDetached: { required: false, control: "boolean", type: "boolean" },+ id: { required: false, control: "text", type: "string" },+ inputMode: {+ description:+ "Hints at the type of data that might be entered by the user while editing the element or its contents\n@see https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute",+ required: false,+ control: "select",+ type: "string",+ options: [+ "text",+ "none",+ "search",+ "tel",+ "url",+ "email",+ "numeric",+ "decimal",+ ],+ },+ is: {+ description:+ "Specify that a standard HTML element should behave like a defined custom built-in element\n@see https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is",+ required: false,+ control: "text",+ type: "string",+ },+ itemID: { required: false, control: "text", type: "string" },+ itemProp: { required: false, control: "text", type: "string" },+ itemRef: { required: false, control: "text", type: "string" },+ itemScope: { required: false, control: "boolean", type: "boolean" },+ itemType: { required: false, control: "text", type: "string" },+ lang: { required: false, control: "text", type: "string" },+ nonce: { required: false, control: "text", type: "string" },+ placeholder: { required: false, control: "text", type: "string" },+ prefix: { required: false, control: "text", type: "string" },+ property: { required: false, control: "text", type: "string" },+ radioGroup: { required: false, control: "text", type: "string" },+ rel: { required: false, control: "text", type: "string" },+ resource: { required: false, control: "text", type: "string" },+ results: { required: false, control: "number", type: "number" },+ rev: { required: false, control: "text", type: "string" },+ role: { required: false, control: "text", type: "string" },+ security: { required: false, control: "text", type: "string" },+ side: {+ required: false,+ control: "select",+ type: "string",+ options: ["top", "right", "bottom", "left"],+ },+ sideOffset: {+ required: false,+ control: "number",+ type: "number",+ defaultValue: 4,+ },+ slot: { required: false, control: "text", type: "string" },+ spellCheck: { required: false, control: "boolean", type: "boolean" },+ sticky: {+ required: false,+ control: "radio",+ type: "string",+ options: ["partial", "always"],+ },+ suppressContentEditableWarning: {+ required: false,+ control: "boolean",+ type: "boolean",+ },+ suppressHydrationWarning: {+ required: false,+ control: "boolean",+ type: "boolean",+ },+ tabIndex: { required: false, control: "number", type: "number" },+ title: { required: false, control: "text", type: "string" },+ translate: {+ required: false,+ control: "radio",+ type: "string",+ options: ["yes", "no"],+ },+ typeof: { required: false, control: "text", type: "string" },+ unselectable: {+ required: false,+ control: "radio",+ type: "string",+ options: ["on", "off"],+ },+ vocab: { required: false, control: "text", type: "string" },+};diff --git a/packages/sdk-components-react/src/components.ts b/packages/sdk-components-react/src/components.tsindex be3b4cd4ba..88beb0798e 100644--- a/packages/sdk-components-react/src/components.ts+++ b/packages/sdk-components-react/src/components.ts@@ -30,3 +30,4 @@ export { Vimeo } from "./vimeo";export { VimeoPreviewImage } from "./vimeo-preview-image";export { VimeoPlayButton } from "./vimeo-play-button";export { VimeoSpinner } from "./vimeo-spinner";+export { Tooltip, TooltipContent, TooltipTrigger } from "./radix-tooltip";diff --git a/packages/sdk-components-react/src/metas.ts b/packages/sdk-components-react/src/metas.tsindex 1fbb40020a..194f7267b3 100644--- a/packages/sdk-components-react/src/metas.ts+++ b/packages/sdk-components-react/src/metas.ts@@ -30,3 +30,8 @@ export { meta as Vimeo } from "./vimeo.ws";export { meta as VimeoPreviewImage } from "./vimeo-preview-image.ws";export { meta as VimeoPlayButton } from "./vimeo-play-button.ws";export { meta as VimeoSpinner } from "./vimeo-spinner.ws";+export {+ metaTooltip as Tooltip,+ metaTooltipContent as TooltipContent,+ metaTooltipTrigger as TooltipTrigger,+} from "./radix-tooltip.ws";diff --git a/packages/sdk-components-react/src/props.ts b/packages/sdk-components-react/src/props.tsindex f6c1fef4e3..18e0681512 100644--- a/packages/sdk-components-react/src/props.ts+++ b/packages/sdk-components-react/src/props.ts@@ -30,3 +30,8 @@ export { propsMeta as Vimeo } from "./vimeo.ws";export { propsMeta as VimeoPreviewImage } from "./vimeo-preview-image.ws";export { propsMeta as VimeoPlayButton } from "./vimeo-play-button.ws";export { propsMeta as VimeoSpinner } from "./vimeo-spinner.ws";+export {+ propsMetaTooltip as Tooltip,+ propsMetaTooltipContent as TooltipContent,+ propsMetaTooltipTrigger as TooltipTrigger,+} from "./radix-tooltip.ws";diff --git a/packages/sdk-components-react/src/radix-tooltip.tsx b/packages/sdk-components-react/src/radix-tooltip.tsxnew file mode 100644index 0000000000..9d0c7d9f3f--- /dev/null+++ b/packages/sdk-components-react/src/radix-tooltip.tsx@@ -0,0 +1,84 @@+/* eslint-disable react/display-name */+// We can't use .displayName until this is merged https://github.com/styleguidist/react-docgen-typescript/pull/449++import * as TooltipPrimitive from "@radix-ui/react-tooltip";+import {+ splitPropsWithWebstudioAttributes,+ type WebstudioAttributes,+} from "@webstudio-is/react-sdk";++import {+ forwardRef,+ type ElementRef,+ type ComponentPropsWithoutRef,+ Children,+ type ReactNode,+} from "react";++/**+ * We don't have support for boolean or undefined nor in UI not at Data variables,+ * instead of binding on "open" prop we bind variable on a isOpen prop to be able to show Tooltip in the builder+ **/+type BuilderTooltipProps = {+ isOpen: "initial" | "open" | "closed";+};++/**+ * Tooltip and TooltipTrigger are HTML-less components.+ * To make them work in our system, we wrap their attributes with a div that has a display: contents property.+ *+ * These divs function like fragments, with all web studio-related attributes attached to them.+ */+const DisplayContentsStyle = { display: "contents" };++export const Tooltip = forwardRef<+ ElementRef<"div">,+ WebstudioAttributes &+ ComponentPropsWithoutRef<typeof TooltipPrimitive.Root> &+ BuilderTooltipProps+>(({ open: openProp, isOpen, ...props }, ref) => {+ const [webstudioAttributes, restProps] =+ splitPropsWithWebstudioAttributes(props);++ const open =+ openProp ??+ (isOpen === "open" ? true : isOpen === "closed" ? false : undefined);++ return (+ <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>+ <TooltipPrimitive.Root open={open} {...restProps} />+ </div>+ );+});++/**+ * We're not exposing the 'asChild' property for the Trigger.+ * Instead, we're enforcing 'asChild=true' for the Trigger and making it style-less.+ * This avoids situations where the Trigger inadvertently passes all styles to its child,+ * which would prevent us from displaying styles properly in the builder.+ */+export const TooltipTrigger = forwardRef<+ ElementRef<"div">,+ WebstudioAttributes & { children: ReactNode }+>(({ children, ...props }, ref) => {+ const firstChild = Children.toArray(children)[0];+ const [webstudioAttributes, restProps] =+ splitPropsWithWebstudioAttributes(props);++ return (+ <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>+ <TooltipPrimitive.Trigger asChild={true} {...restProps}>+ {firstChild ?? <button>Add button or link</button>}+ </TooltipPrimitive.Trigger>+ </div>+ );+});++export const TooltipContent = forwardRef<+ ElementRef<typeof TooltipPrimitive.Content>,+ ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>+>(({ sideOffset = 4, ...props }, ref) => (+ <TooltipPrimitive.Portal>+ <TooltipPrimitive.Content ref={ref} sideOffset={sideOffset} {...props} />+ </TooltipPrimitive.Portal>+));diff --git a/packages/sdk-components-react/src/radix-tooltip.ws.tsx b/packages/sdk-components-react/src/radix-tooltip.ws.tsxnew file mode 100644index 0000000000..2b47d0ecf4--- /dev/null+++ b/packages/sdk-components-react/src/radix-tooltip.ws.tsx@@ -0,0 +1,105 @@+import { RadioCheckedIcon } from "@webstudio-is/icons/svg";+import {+ type WsComponentMeta,+ type WsComponentPropsMeta,+} from "@webstudio-is/react-sdk";++import {+ propsTooltip,+ propsTooltipContent,+ propsTooltipTrigger,+} from "./__generated__/radix-tooltip.props";++// @todo add [data-state] to button and link+export const metaTooltipTrigger: WsComponentMeta = {+ category: "hidden",+ invalidAncestors: [],+ type: "container",+ label: "TooltipTrigger",+ icon: RadioCheckedIcon,+ stylable: false,+};++export const metaTooltipContent: WsComponentMeta = {+ category: "hidden",+ invalidAncestors: [],+ type: "container",+ label: "TooltipContent",+ icon: RadioCheckedIcon,+};++export const metaTooltip: WsComponentMeta = {+ category: "radix",+ invalidAncestors: [],+ type: "container",+ label: "Tooltip",+ icon: RadioCheckedIcon,+ order: 15,+ template: [+ {+ type: "instance",+ component: "Tooltip",+ label: "Tooltip",+ props: [+ {+ name: "isOpen",+ // We don't have support for boolean or undefined, instead of binding on open we bind on a string+ type: "string",+ value: "initial",+ dataSourceRef: {+ type: "variable",+ name: "isOpen",+ },+ },+ ],+ children: [+ {+ type: "instance",+ component: "TooltipTrigger",+ props: [],+ children: [+ {+ type: "instance",+ component: "Button",+ children: [{ type: "text", value: "Button" }],+ },+ ],+ },+ {+ type: "instance",+ component: "TooltipContent",+ label: "Tooltip Content",+ props: [],+ children: [+ {+ type: "instance",+ component: "Box",+ props: [],+ children: [+ {+ type: "instance",+ component: "Text",+ children: [{ type: "text", value: "The text you can edit" }],+ },+ ],+ },+ ],+ },+ ],+ },+ ],+};++export const propsMetaTooltip: WsComponentPropsMeta = {+ props: propsTooltip,+ initialProps: ["isOpen", "delayDuration", "disableHoverableContent"],+};++export const propsMetaTooltipTrigger: WsComponentPropsMeta = {+ props: propsTooltipTrigger,+};++export const propsMetaTooltipContent: WsComponentPropsMeta = {+ props: propsTooltipContent,+ initialProps: ["side", "sideOffset", "align", "alignOffset"],+};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex eeb9eed889..82498c095f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -78,6 +78,9 @@ importers:'@nanostores/react':specifier: ^0.7.1version: 0.7.1([email protected])([email protected])+ '@radix-ui/primitive':+ specifier: 1.0.1+ version: 1.0.1'@radix-ui/react-select':specifier: ^1.2.2version: 1.2.2(@types/[email protected])(@types/[email protected])([email protected])([email protected])@@ -1240,6 +1243,9 @@ importers:packages/sdk-components-react:dependencies:+ '@radix-ui/react-tooltip':+ specifier: ^1.0.6+ version: 1.0.6(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@react-aria/utils':specifier: ^3.13.3version: 3.13.3([email protected])