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 modern tooltips to space control (#1877)
Ivan Starkov88c94b1d520b
diff --git a/apps/builder/app/builder/features/style-panel/sections/space/scrub.tsx b/apps/builder/app/builder/features/style-panel/sections/space/scrub.tsxindex a4aa7a5244..09b51de2bb 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/scrub.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/space/scrub.tsx@@ -148,7 +148,7 @@ const circleGroups = [["marginTop", "marginRight", "marginBottom", "marginLeft"],] as const;-const getModifiersGroup = (+export const getModifiersGroup = (property: SpaceStyleProperty,modifiers: { shiftKey: boolean; altKey: boolean }) => {diff --git a/apps/builder/app/builder/features/style-panel/sections/space/space.tsx b/apps/builder/app/builder/features/style-panel/sections/space/space.tsxindex cbf85d7271..1a8578d3c4 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/space.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/space/space.tsx@@ -17,6 +17,7 @@ import { getStyleSource } from "../../shared/style-info";import { CollapsibleSection } from "../../shared/collapsible-section";import { useKeyboardNavigation } from "./keyboard";import { useDebouncedCallback } from "use-debounce";+import type { CreateBatchUpdate } from "../../shared/use-style-data";const Cell = ({isPopoverOpen,@@ -27,6 +28,7 @@ const Cell = ({isActive,scrubStatus,currentStyle,+ createBatchUpdate,}: {isPopoverOpen: boolean;onPopoverClose: () => void;@@ -36,6 +38,7 @@ const Cell = ({isActive: boolean;scrubStatus: ReturnType<typeof useScrub>;currentStyle: RenderCategoryProps["currentStyle"];+ createBatchUpdate: CreateBatchUpdate;}) => {const styleInfo = currentStyle[property];const finalValue =@@ -57,27 +60,31 @@ const Cell = ({onChange={onChange}onClose={onPopoverClose}/>- {isActive && isPopoverOpen === false && scrubStatus.isActive === false ? (- <SpaceTooltip property={property} />- ) : null}- <ValueText- css={{- // We want value to have `default` cursor to indicate that it's clickable,- // unlike the rest of the value area that has cursor that indicates scrubbing.- // Click and scrub works everywhere anyway, but we want cursors to be different.- //- // In order to have control over cursor we're setting pointerEvents to "all" here- // because SpaceLayout sets it to "none" for cells' content.- pointerEvents: "all",- }}- value={finalValue}- isActive={isActive}- source={styleSource}- onMouseEnter={(event) =>- onHover({ property, element: event.currentTarget })- }- onMouseLeave={() => onHover(undefined)}- />+ <SpaceTooltip+ property={property}+ style={currentStyle}+ createBatchUpdate={createBatchUpdate}+ preventOpen={scrubStatus.isActive}+ >+ <ValueText+ css={{+ // We want value to have `default` cursor to indicate that it's clickable,+ // unlike the rest of the value area that has cursor that indicates scrubbing.+ // Click and scrub works everywhere anyway, but we want cursors to be different.+ //+ // In order to have control over cursor we're setting pointerEvents to "all" here+ // because SpaceLayout sets it to "none" for cells' content.+ pointerEvents: "all",+ }}+ value={finalValue}+ isActive={isActive}+ source={styleSource}+ onMouseEnter={(event) =>+ onHover({ property, element: event.currentTarget })+ }+ onMouseLeave={() => onHover(undefined)}+ />+ </SpaceTooltip></>);};@@ -179,7 +186,20 @@ export const SpaceSection = ({activeProperties = [openProperty, ...scrubStatus.properties];}+ const handleHoverUndefined = useDebouncedCallback(() => {+ setHoverTarget(undefined);+ keyboardNavigation.handleHover(undefined);+ }, 100);+const handleHover = (target: HoverTagret | undefined) => {+ if (target === undefined) {+ // Debounce the mouseleave event to prevent delays when moving between cells.+ // This resolves the issue where the tooltip content changes when repositioned (e.g., when alt/shift clicked),+ // causing rapid mouseleave and mouseenter events in the space section.+ handleHoverUndefined();+ return;+ }+ handleHoverUndefined.cancel();setHoverTarget(target);keyboardNavigation.handleHover(target?.property);};@@ -207,10 +227,10 @@ export const SpaceSection = ({onHover={handleHover}onFocus={focusProps.onFocus}onBlur={focusProps.onBlur}+ activeProperties={activeProperties}onKeyDown={keyboardNavigation.handleKeyDown}onMouseMove={keyboardNavigation.handleMouseMove}onMouseLeave={keyboardNavigation.handleMouseLeave}- activeProperties={activeProperties}renderCell={({ property }) => (<CellisPopoverOpen={openProperty === property}@@ -232,6 +252,7 @@ export const SpaceSection = ({scrubStatus={scrubStatus}isActive={activeProperty === property}currentStyle={currentStyle}+ createBatchUpdate={createBatchUpdate}/>)}/>diff --git a/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsx b/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsxindex 1a23045ff5..b14abf34c9 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsx@@ -1,65 +1,128 @@-import {- styled,- Tooltip,- useEnhancedTooltipProps,-} from "@webstudio-is/design-system";import type { SpaceStyleProperty } from "./types";-import { useDebounce } from "use-debounce";-import { useState } from "react";--// trigger is used only for positioning-const Trigger = styled("div", {- position: "absolute",- width: "100%",- height: "100%",- pointerEvents: "none",- top: 0,- left: 0,-});--const labels = {- paddingTop: "Padding Top",- paddingRight: "Padding Right",- paddingBottom: "Padding Bottom",- paddingLeft: "Padding Left",- marginTop: "Margin Top",- marginRight: "Margin Right",- marginBottom: "Margin Bottom",- marginLeft: "Margin Left",-};+import { PropertyTooltip } from "../../shared/property-name";+import type { StyleInfo } from "../../shared/style-info";+import { useState, type ReactElement } from "react";+import { useModifierKeys } from "../../shared/modifier-keys";+import { getModifiersGroup } from "./scrub";+import type { CreateBatchUpdate } from "../../shared/use-style-data";const sides = {paddingTop: "top",- paddingRight: "left",- paddingBottom: "top",- paddingLeft: "right",+ paddingRight: "top",+ paddingBottom: "bottom",+ paddingLeft: "left",marginTop: "top",marginRight: "left",- marginBottom: "top",+ marginBottom: "bottom",marginLeft: "right",} as const;+const propertyContents: {+ properties: SpaceStyleProperty[];+ label: string;+ description: string;+}[] = [+ // Padding+ {+ properties: ["paddingTop", "paddingBottom"],+ label: "Vertical Padding",+ description:+ "Defines the space between the content of an element and its top and bottom border. Can affect layout height.",+ },++ {+ properties: ["paddingLeft", "paddingRight"],+ label: "Horizontal Padding",+ description:+ "Defines the space between the content of an element and its left and right border. Can affect layout width.",+ },++ {+ properties: ["paddingTop", "paddingBottom", "paddingLeft", "paddingRight"],+ label: "Padding",+ description:+ "Defines the space between the content of an element and its border. Can affect layout size.",+ },+ // Margin+ {+ properties: ["marginTop", "marginBottom"],+ label: "Vertical Margin",+ description: "Sets the margin at the top and bottom of an element.",+ },++ {+ properties: ["marginLeft", "marginRight"],+ label: "Horizontal Margin",+ description: "Sets the margin at the left and right of an element.",+ },++ {+ properties: ["marginTop", "marginBottom", "marginLeft", "marginRight"],+ label: "Margin",+ description: "Sets the margin of an element.",+ },+];++const isSameUnorderedArrays = (+ arrA: readonly string[],+ arrB: readonly string[]+) => {+ if (arrA.length !== arrB.length) {+ return false;+ }++ const union = new Set([...arrA, ...arrB]);+ return union.size === arrA.length;+};+export const SpaceTooltip = ({property,+ style,+ children,+ createBatchUpdate,+ preventOpen,}: {property: SpaceStyleProperty;+ style: StyleInfo;+ children: ReactElement;+ createBatchUpdate: CreateBatchUpdate;+ preventOpen: boolean;}) => {- const { delayDuration } = useEnhancedTooltipProps();- const [initialOpen, setInitialOpen] = useState(false);- const [open] = useDebounce(initialOpen, delayDuration ?? 0);+ const [open, setOpen] = useState(false);- if (initialOpen === false) {- setInitialOpen(true);- }+ const modifiers = useModifierKeys();++ const properties = [...getModifiersGroup(property, modifiers)];++ const propertyContent = propertyContents.find((propertyContent) =>+ isSameUnorderedArrays(propertyContent.properties, properties)+ );++ const handleOpenChange = (value: boolean) => {+ if (preventOpen && value === true) {+ return;+ }+ setOpen(value);+ };return (- <Tooltip+ <PropertyTooltipopen={open}- content={labels[property]}+ onOpenChange={handleOpenChange}+ properties={properties}+ style={style}+ title={propertyContent?.label}+ description={propertyContent?.description}side={sides[property]}- disableHoverableContent+ onReset={() => {+ const batch = createBatchUpdate();+ for (const property of properties) {+ batch.deleteProperty(property);+ }+ batch.publish();+ }}>- <Trigger />- </Tooltip>+ <div>{children}</div>+ </PropertyTooltip>);};diff --git a/apps/builder/app/builder/features/style-panel/shared/modifier-keys.ts b/apps/builder/app/builder/features/style-panel/shared/modifier-keys.tsindex daa7c5e72e..cd1026cbae 100644--- a/apps/builder/app/builder/features/style-panel/shared/modifier-keys.ts+++ b/apps/builder/app/builder/features/style-panel/shared/modifier-keys.ts@@ -1,4 +1,5 @@import { useState, useEffect } from "react";+import { shallowEqual } from "shallow-equal";// Used for combined mouse and keyboard interactions, like scrubbing while holding ALT.// If it's just a keyboard interaction, you should already have a keyboard event at hand.@@ -11,20 +12,33 @@ export const useModifierKeys = () => {});useEffect(() => {- const handler = (event: KeyboardEvent) =>- setState({+ const handler = (event: KeyboardEvent | MouseEvent) => {+ const newState = {shiftKey: event.shiftKey,altKey: event.altKey,ctrlKey: event.ctrlKey,metaKey: event.metaKey,+ };++ setState((prev) => {+ if (shallowEqual(prev, newState)) {+ return prev;+ }++ return newState;});+ };window.addEventListener("keydown", handler);window.addEventListener("keyup", handler);+ // The use of only the keyup/keydown events may not be sufficient.+ // on a Mac, when the cmd-shift-4 (printscreen) combination is triggered, there is a possibility of losing the keyup event.+ window.addEventListener("mousemove", handler);return () => {window.removeEventListener("keydown", handler);window.removeEventListener("keyup", handler);+ window.removeEventListener("mousemove", handler);};}, []);diff --git a/apps/builder/app/builder/features/style-panel/shared/property-name.tsx b/apps/builder/app/builder/features/style-panel/shared/property-name.tsxindex 6143106fe5..1430eecdf0 100644--- a/apps/builder/app/builder/features/style-panel/shared/property-name.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/property-name.tsx@@ -10,6 +10,7 @@ import {Flex,Label,Tooltip,+ type TooltipProps,Text,ScrollArea,} from "@webstudio-is/design-system";@@ -123,34 +124,55 @@ const TooltipContent = ({const selectedBreakpoint = useStore(selectedBreakpointStore);const instances = useStore(instancesStore);const styleSources = useStore(styleSourcesStore);- let instance = useStore(selectedInstanceStore);+ const instance = useStore(selectedInstanceStore);const selectedStyleSource = useStore(selectedStyleSourceStore);- // When we have multiple properties, they must be originating from the same source, so we can just use one.- const styleValueInfo = style[properties[0]];+ const descriptionWithFallback = description ?? getDescription(properties);- if (styleValueInfo === undefined) {- return null;- }+ const breakpointSet = new Set<string>();+ const styleSourceNameSet = new Set<string>();+ const instanceSet = new Set<string>();- const descriptionWithFallback = description ?? getDescription(properties);+ for (const property of properties) {+ const styleValueInfo = style[property];- const styleSource = getStyleSource(styleValueInfo);- const sourceName = getSourceName(- styleSources,- styleValueInfo,- selectedStyleSource- );- const breakpointName = getBreakpointName(- styleValueInfo,- breakpoints,- selectedBreakpoint- );+ if (styleValueInfo === undefined) {+ continue;+ }++ const sourceName = getSourceName(+ styleSources,+ styleValueInfo,+ selectedStyleSource+ );++ if (sourceName !== undefined) {+ styleSourceNameSet.add(sourceName);+ }++ const breakpointName = getBreakpointName(+ styleValueInfo,+ breakpoints,+ selectedBreakpoint+ );++ breakpointSet.add(`${breakpointName}`);++ let instanceTitle = instance?.label ?? instance?.component;+ if (styleValueInfo.inherited && styleValueInfo.local === undefined) {+ const localInstance = instances.get(styleValueInfo.inherited.instanceId);+ instanceTitle = localInstance?.label ?? localInstance?.component;+ }- if (styleValueInfo.inherited && styleValueInfo.local === undefined) {- instance = instances.get(styleValueInfo.inherited.instanceId);+ if (instanceTitle !== undefined) {+ instanceSet.add(instanceTitle);+ }}+ const styleSourcesList = properties.map((property) =>+ getStyleSource(style[property])+ );+return (<Flex direction="column" gap="2" css={{ maxWidth: theme.spacing[28] }}><Text variant="titles">{title ?? humanizeString(properties[0])}</Text>@@ -169,7 +191,7 @@ const TooltipContent = ({</Text></ScrollArea>{descriptionWithFallback && <Text>{descriptionWithFallback}</Text>}- {sourceName && (+ {styleSourceNameSet.size > 0 && (<Flexdirection="column"gap="1"@@ -177,21 +199,36 @@ const TooltipContent = ({><Text color="moreSubtle">Value comes from</Text><Flex gap="1" wrap="wrap">- <StyleSourceBadge source="breakpoint" variant="small">- {breakpointName}- </StyleSourceBadge>- <StyleSourceBadge source="token" variant="small">- {sourceName}- </StyleSourceBadge>- {instance && (- <StyleSourceBadge source="instance" variant="small">- {instance.label || instance.component}+ {Array.from(breakpointSet).map((breakpointName) => (+ <StyleSourceBadge+ key={breakpointName}+ source="breakpoint"+ variant="small"+ >+ {breakpointName}</StyleSourceBadge>- )}+ ))}++ {Array.from(styleSourceNameSet).map((sourceName) => (+ <StyleSourceBadge key={sourceName} source="token" variant="small">+ {sourceName}+ </StyleSourceBadge>+ ))}++ {Array.from(instanceSet).map((instanceTitle) => (+ <StyleSourceBadge+ key={instanceTitle}+ source="instance"+ variant="small"+ >+ {instanceTitle}+ </StyleSourceBadge>+ ))}</Flex></Flex>)}- {(styleSource === "local" || styleSource === "overwritten") &&+ {(styleSourcesList.includes("local") ||+ styleSourcesList.includes("overwritten")) &&onReset !== undefined && (<Buttoncolor="dark"@@ -214,6 +251,9 @@ export const PropertyTooltip = ({style,onReset,children,+ open,+ onOpenChange,+ side,}: {openWithClick?: boolean;title?: string;@@ -222,12 +262,20 @@ export const PropertyTooltip = ({style: StyleInfo;onReset?: undefined | (() => void);children: ReactElement;+ open?: boolean;+ onOpenChange?: (isOpen: boolean) => void;+ side?: TooltipProps["side"];}) => {- const [isOpen, setIsOpen] = useState(false);+ const [isOpenInternal, setIsOpenInternal] = useState(open ?? false);++ const handleIsOpen = onOpenChange ?? setIsOpenInternal;+ const isOpen = open ?? isOpenInternal;+return (<Tooltipopen={isOpen}- onOpenChange={setIsOpen}+ onOpenChange={handleIsOpen}+ side={side}// prevent closing tooltip on content clickonPointerDown={(event) => event.preventDefault()}triggerProps={{@@ -238,7 +286,7 @@ export const PropertyTooltip = ({return;}if (openWithClick) {- setIsOpen(true);+ handleIsOpen(true);}},}}@@ -248,12 +296,17 @@ export const PropertyTooltip = ({description={description}properties={properties}style={style}- onReset={() => {- onReset?.();- setIsOpen(false);- }}+ onReset={+ onReset+ ? () => {+ onReset();+ handleIsOpen(false);+ }+ : undefined+ }/>}+ disableHoverableContent={onReset === undefined}>{children}</Tooltip>diff --git a/apps/builder/tsconfig.json b/apps/builder/tsconfig.jsonindex 9bfa898c6b..e1758ca218 100644--- a/apps/builder/tsconfig.json+++ b/apps/builder/tsconfig.json@@ -1,5 +1,4 @@{- // Extends can't use node's resolution rn https://github.com/dividab/tsconfig-paths/issues/209#issuecomment-1177261091"extends": "../../packages/tsconfig/remix.json","include": ["remix.env.d.ts",@@ -8,10 +7,14 @@"../../@types/**/*.d.ts"],"compilerOptions": {- "paths": { "~/*": ["app/*"] },+ "paths": {+ "~/*": ["app/*"]+ },"baseUrl": ".","rootDir": "./app","declaration": false,- "declarationDir": null+ "emitDeclarationOnly": false,+ "declarationDir": null,+ "noEmit": true}}diff --git a/packages/css-data/bin/property-value-descriptions.ts b/packages/css-data/bin/property-value-descriptions.tsindex 51177f27a0..e7456d0146 100755--- a/packages/css-data/bin/property-value-descriptions.ts+++ b/packages/css-data/bin/property-value-descriptions.ts@@ -3,6 +3,7 @@ import * as fs from "node:fs";import * as path from "node:path";import type { CreateChatCompletionResponse } from "openai";import { keywordValues } from "../src/__generated__/keyword-values";+import warnOnce from "warn-once";const propertiesPrompt = fs.readFileSync(path.join(process.cwd(), "bin", "prompts", "properties.prompt.md"),@@ -71,6 +72,12 @@ const newPropertiesNames = Object.keys(keywordValues)typeof propertiesOverrides[property] !== "string"));+let retries = 0;++const backoff = (num: number) => {+ return Math.floor(Math.pow(2, Math.min(num, 4)) * 1000);+};+for (let i = 0; i < newPropertiesNames.length; ) {const properties = newPropertiesNames.slice(i, i + batchSize);@@ -85,9 +92,6 @@ for (let i = 0; i < newPropertiesNames.length; ) {continue;}- // eslint-disable-next-line @typescript-eslint/ban-ts-comment- // @ts-ignore Fix this else it'll complain that we cannot use top-level await.-const result = await generate(propertiesPrompt.replace("{properties}",@@ -98,7 +102,13 @@ for (let i = 0; i < newPropertiesNames.length; ) {if (Array.isArray(result)) {// Retryif (result[0] === 429) {- console.log(`❌ Error: 429 ${result[1]}. Retrying...`);+ console.log(+ `❌ Error: 429 ${result[1]}. Retrying after sleep ${backoff(+ retries+ )}...`+ );+ await new Promise((resolve) => setTimeout(resolve, backoff(retries)));+ retries++;continue;}@@ -294,27 +304,30 @@ function writeFile(descriptions: Record<string, unknown>) {}async function generate(message: string): Promise<string | [number, string]> {- if (!process.env.OPENAI_KEY) {+ const { OPENAI_ORG, OPENAI_KEY } = process.env;++ if (OPENAI_KEY === undefined) {throw new Error("Missing OpenAI key (process.env.OPENAI_KEY)");}- if (- typeof process.env.OPENAI_ORG !== "string" ||- !process.env.OPENAI_ORG.startsWith("org-")- ) {- throw new Error(+ const headers: HeadersInit = {+ "Content-Type": "application/json",+ Accept: "application/json",+ Authorization: `Bearer ${process.env.OPENAI_KEY}`,+ };++ if (OPENAI_ORG?.startsWith("org-")) {+ headers["OpenAI-Organization"] = OPENAI_ORG;+ } else {+ warnOnce(+ true,"Missing OpenAI org (process.env.OPENAI_ORG) or invalid org");}const response = await fetch("https://api.openai.com/v1/chat/completions", {method: "POST",- headers: {- "Content-Type": "application/json",- Accept: "application/json",- Authorization: `Bearer ${process.env.OPENAI_KEY}`,- "OpenAI-Organization": process.env.OPENAI_ORG,- },+ headers,body: JSON.stringify({model: "gpt-3.5-turbo",messages: [{ role: "user", content: message }],diff --git a/packages/css-data/src/__generated__/property-value-descriptions.ts b/packages/css-data/src/__generated__/property-value-descriptions.tsindex 07d2544399..f116ac9125 100644--- a/packages/css-data/src/__generated__/property-value-descriptions.ts+++ b/packages/css-data/src/__generated__/property-value-descriptions.ts@@ -323,12 +323,16 @@ export const propertiesGenerated = {overscrollBehaviorY: "overscrollBehaviorY",paddingBlockEnd: "paddingBlockEnd",paddingBlockStart: "paddingBlockStart",- paddingBottom: "paddingBottom",+ paddingBottom:+ "Defines the space between the content of an element and its bottom border. Can affect layout height.",paddingInlineEnd: "paddingInlineEnd",paddingInlineStart: "paddingInlineStart",- paddingLeft: "paddingLeft",- paddingRight: "paddingRight",- paddingTop: "paddingTop",+ paddingLeft:+ "Defines the space between the content of an element and its left border. Can affect layout width.",+ paddingRight:+ "Defines the space between the content of an element and its right border. Can affect layout width.",+ paddingTop:+ "Defines the space between the content of an element and its top border. Can affect layout height.",pageBreakAfter: "pageBreakAfter",pageBreakBefore: "pageBreakBefore",pageBreakInside: "Controls whether a page break occurs inside an element.",diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.tsindex a46d4536f4..2269c46f0b 100644--- a/packages/design-system/src/index.ts+++ b/packages/design-system/src/index.ts@@ -55,7 +55,11 @@ export {SidebarTabsTrigger,} from "./components/sidebar-tabs";export { Card } from "./components/card";-export { Tooltip, InputErrorsTooltip } from "./components/tooltip";+export {+ Tooltip,+ InputErrorsTooltip,+ type TooltipProps,+} from "./components/tooltip";export {EnhancedTooltip,EnhancedTooltipProvider,diff --git a/packages/tsconfig/remix.json b/packages/tsconfig/remix.jsonindex d555ea5a81..08b32c9123 100644--- a/packages/tsconfig/remix.json+++ b/packages/tsconfig/remix.json@@ -3,7 +3,6 @@"display": "Remix","extends": "./base.json","compilerOptions": {- "noEmit": true,"jsx": "react-jsx","target": "ES2021","module": "ES2020",