Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Add unified scroll to textarea, allow autogrow (#2525)
Ivan Starkov2a0551b86140
diff --git a/apps/builder/app/builder/features/settings-panel/controls/select.tsx b/apps/builder/app/builder/features/settings-panel/controls/select.tsxindex c1a2333228..ffe06a877a 100644--- a/apps/builder/app/builder/features/settings-panel/controls/select.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/select.tsx@@ -14,7 +14,7 @@ export const SelectControl = ({// making sure that the current value is in the list of optionsconst options =- prop === undefined || meta.options.includes(prop.value)+ prop === undefined || meta.options.includes(prop.value) || prop.value === ""? meta.options: [prop.value, ...meta.options];diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.tsxindex 6b846d35ae..83393e2aaf 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text.tsx@@ -7,95 +7,6 @@ import {ResponsiveLayout,Label,} from "../shared";-import { useState, type ComponentProps } from "react";--const countLines = (value: string) => (value.match(/\n/g) || "").length + 1;--type UniversalInputProps = Omit<- ComponentProps<typeof TextArea>,- "onChange" | "value" | "onSubmit"-> & {- defaultRows?: number;- maxRows?: number;- value: string;- onChange: (value: string) => void;- onSubmit: () => void;-};--/**- * UniversalInput component allows to dynamically decide if we need a single-line input or a multi-line textarea.- * Problem it is solving is that we don't know from data type string if user needs a textarea or an input.- *- * Single-line mode:- * - enter saves- * - shift+enter - adds newline and saves- *- * Multiline-mode:- * - enter saves and ads newline- * - cmd+enter - saves, no newline- */-const UniversalInput = ({- value,- defaultRows,- maxRows = 10,- onChange,- onSubmit,- ...rest-}: UniversalInputProps) => {- const [rows, setRows] = useState<number>(() =>- Math.min(defaultRows || countLines(value), maxRows)- );-- const handleChange = (value: string) => {- setRows(Math.min(countLines(value), maxRows));- onChange(value);- };-- return (- <TextArea- {...rest}- css={- rows > 1- ? { resize: "vertical" }- : { resize: "none", whiteSpace: "nowrap", overflow: "hidden" }- }- value={value}- onChange={(event) => {- const { value } = event.target;- handleChange(value);- }}- onBlur={(_event) => {- handleChange(value);- onSubmit();- }}- rows={rows}- onKeyDown={(event) => {- if (event.key !== "Enter") {- return;- }- const isMultiline = rows > 1;- if (isMultiline === false) {- event.preventDefault();- }- // Insert the newline at the caret position.- if (event.shiftKey && isMultiline === false) {- const element = event.currentTarget;- const startPos = element.selectionStart;- const endPos = element.selectionEnd;- element.value =- value.substring(0, startPos) +- "\n" +- value.substring(endPos, value.length);- element.selectionStart = startPos + 1;- element.selectionEnd = startPos + 1;- handleChange(element.value);- }- // Both single-line and multi-line inputs should submit on Enter.- onSubmit();- }}- />- );-};export const TextControl = ({meta,@@ -114,10 +25,13 @@ export const TextControl = ({const isTwoColumnLayout = rows < 2;const input = (- <UniversalInput+ <TextAreaid={id}+ autoGrowvalue={localValue.value}- defaultRows={meta.rows}+ rows={meta.rows ?? 1}+ // Set maxRows to 3 when meta.rows is undefined or equal to 1, otherwise set it to rows * 2+ maxRows={Math.max(2 * (meta.rows ?? 1), 3)}onChange={localValue.set}onBlur={localValue.save}onSubmit={localValue.save}diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsxindex 92ef9ea9d4..d309ff90e5 100644--- a/apps/builder/app/builder/features/settings-panel/shared.tsx+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx@@ -215,7 +215,6 @@ export const HorizontalLayout = ({? `${theme.spacing[19]} 1fr max-content`: `${theme.spacing[19]} 1fr`,minHeight: theme.spacing[13],- justifyItems: "start",}}align="center"gap="2"diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsxindex 57e1bc0106..4a391ed208 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx@@ -215,8 +215,8 @@ const FormFields = ({name="description"disabled={disabled}value={values?.description}- onChange={(event) => {- onChange({ field: "description", value: event.target.value });+ onChange={(value) => {+ onChange({ field: "description", value });}}/></InputErrorsTooltip>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsxindex 1df9fc3d40..d2c6bac7b3 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx@@ -1,6 +1,6 @@import type { InvalidValue, RgbValue } from "@webstudio-is/css-engine";import { parseCssValue, parseBackground } from "@webstudio-is/css-data";-import { TextArea, textVariants, theme } from "@webstudio-is/design-system";+import { TextArea, textVariants } from "@webstudio-is/design-system";import { useEffect, useRef, useState } from "react";import type { ControlProps } from "../../style-sections";@@ -88,15 +88,15 @@ export const BackgroundGradient = (return (<TextArearef={textAreaRef}- css={{ minHeight: theme.spacing[14], ...textVariants.mono }}+ css={{ ...textVariants.mono }}rows={2}+ autoGrow+ maxRows={4}name="description"disabled={props.disabled}value={textAreaValue ?? ""}state={intermediateValue?.type === "invalid" ? "invalid" : undefined}- onChange={(event) => {- handleChange(event.target.value);- }}+ onChange={handleChange}onBlur={handleOnComplete}onKeyDown={(event) => {if (event.key === "Enter") {diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-content.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-content.tsxindex 5e4d80c90b..42c350cea5 100644--- a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-content.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-content.tsx@@ -98,7 +98,7 @@ export const BoxShadowContent = (props: BoxShadowContentProps) => {value={intermediateValue?.value ?? props.value ?? ""}css={{ minHeight: theme.spacing[14], ...textVariants.mono }}state={intermediateValue?.type === "invalid" ? "invalid" : undefined}- onChange={(event) => handleChange(event.target.value)}+ onChange={handleChange}onKeyDown={(event) => {if (event.key === "Enter") {handleComplete();diff --git a/packages/design-system/src/components/text-area.stories.tsx b/packages/design-system/src/components/text-area.stories.tsxindex dfbcb0dd15..027edd4c58 100644--- a/packages/design-system/src/components/text-area.stories.tsx+++ b/packages/design-system/src/components/text-area.stories.tsx@@ -1,5 +1,6 @@import { TextArea } from "./text-area";import { StorySection, StoryGrid } from "./storybook";+import { useState } from "react";export default {title: "Library/Text Area",@@ -9,45 +10,80 @@ const exampleValue ="This is an example value of a text area. It's long enough to show how it wraps.";export const Demo = () => {+ const [value, setValue] = useState(exampleValue);+return (<>- <StorySection title="Empty">+ <StorySection title="Uncontrollable"><StoryGrid css={{ width: 200 }}><TextArea placeholder="Enter value..." /></StoryGrid></StorySection>++ <StorySection title="No AutoGrow, rows=3 (Manual resize only, no height limit)">+ <StoryGrid css={{ width: 200 }}>+ <TextArea value={value} onChange={setValue} />+ </StoryGrid>+ </StorySection>++ <StorySection title="No AutoGrow, rows=3, maxRows=6 (Manual resize up to 6 rows)">+ <StoryGrid css={{ width: 200 }}>+ <TextArea value={value} onChange={setValue} maxRows={6} />+ </StoryGrid>+ </StorySection>++ <StorySection title="AutoGrow, no max (Auto-resize with no height limit.)">+ <StoryGrid css={{ width: 200 }}>+ <TextArea value={value} onChange={setValue} autoGrow />+ </StoryGrid>+ </StorySection>++ <StorySection title="AutoGrow, maxRows=10 (Auto-resize up to 10 rows.)">+ <StoryGrid css={{ width: 200 }}>+ <TextArea value={value} onChange={setValue} autoGrow maxRows={10} />+ </StoryGrid>+ </StorySection>+<StorySection title="With value"><StoryGrid css={{ width: 200 }}>- <TextArea value={exampleValue} />+ <TextArea value={value} onChange={setValue} /></StoryGrid></StorySection><StorySection title="Invalid"><StoryGrid css={{ width: 200 }}>- <TextArea value={exampleValue} state="invalid" />+ <TextArea value={value} onChange={setValue} state="invalid" /></StoryGrid></StorySection><StorySection title="Disabled"><StoryGrid css={{ width: 200 }}>- <TextArea value={exampleValue} disabled />+ <TextArea value={value} onChange={setValue} disabled /></StoryGrid></StorySection><StorySection title="Disabled invalid"><StoryGrid css={{ width: 200 }}>- <TextArea value={exampleValue} state="invalid" disabled />+ <TextArea+ value={value}+ onChange={setValue}+ state="invalid"+ disabled+ /></StoryGrid></StorySection><StorySection title="Focused (initialy)"><StoryGrid css={{ width: 200 }}>- <TextArea value={exampleValue} autoFocus />+ <TextArea value={value} onChange={setValue} autoFocus /></StoryGrid></StorySection><StorySection title="Rows test"><StoryGrid css={{ width: 200 }}>- <TextArea value={exampleValue} rows={1} />+ <TextArea value={value} onChange={setValue} rows={1} />+ <TextArea value={value} onChange={setValue} rows={5} /></StoryGrid></StorySection><StorySection title="Width test">- <TextArea value={exampleValue} css={{ width: "250px" }} />+ <StoryGrid css={{ width: 250 }}>+ <TextArea value={value} onChange={setValue} />+ </StoryGrid></StorySection></>);diff --git a/packages/design-system/src/components/text-area.tsx b/packages/design-system/src/components/text-area.tsxindex f43364687e..1edcc5a064 100644--- a/packages/design-system/src/components/text-area.tsx+++ b/packages/design-system/src/components/text-area.tsx@@ -6,14 +6,16 @@import { type ComponentProps, type Ref, forwardRef } from "react";import { type CSS, css, theme } from "../stitches.config";import { textVariants } from "./text";+import { Grid } from "./grid";+import { useControllableState } from "@radix-ui/react-use-controllable-state";+import { ScrollArea } from "./scroll-area";const LINE_HEIGHT = 16;const PADDING_TOP = 6;const PADDING_BOTTOM = 4;const BORDER = 1;-const style = css(textVariants.regular, {- lineHeight: `${LINE_HEIGHT}px`,+const gridStyle = css(textVariants.regular, {color: theme.colors.foregroundMain,borderRadius: theme.borderRadius[4],border: `${BORDER}px solid ${theme.colors.borderMain}`,@@ -23,24 +25,24 @@ const style = css(textVariants.regular, {paddingTop: PADDING_TOP,paddingBottom: PADDING_BOTTOM,boxSizing: "border-box",- width: "100%",resize: "vertical",- "&::placeholder": {- color: theme.colors.foregroundSubtle,- },- "&:disabled": {- color: theme.colors.foregroundDisabled,- background: theme.colors.backgroundInputDisabled,- },- "&:focus-visible": {+ overflow: "auto",+ width: "100%",++ "&:focus-within": {borderColor: theme.colors.borderFocus,outline: `1px solid ${theme.colors.borderFocus}`,},variants: {+ autoGrow: {+ true: {+ resize: "none",+ },+ },state: {invalid: {color: theme.colors.foregroundDestructive,- "&:not(:disabled):not(:focus-visible)": {+ "&:not(:disabled):not(:focus-within)": {borderColor: theme.colors.borderDestructiveMain,},},@@ -48,33 +50,139 @@ const style = css(textVariants.regular, {},});-type Props = ComponentProps<"textarea"> & {+const commonStyle = css(textVariants.regular, {+ border: "none",+ paddingRight: 0,+ paddingLeft: 0,+ paddingTop: 0,+ paddingBottom: 0,+ boxSizing: "border-box",+ gridArea: "1 / 1 / 2 / 2",+ background: "transparent",+ color: "inherit",+ textWrap: "wrap",+ overflowWrap: "break-word",+ whiteSpace: "pre-wrap",+ overflow: "hidden",+ resize: "none",+ outline: "none",+ "&::placeholder": {+ color: theme.colors.foregroundContrastSubtle,+ },+ "&:disabled": {+ color: theme.colors.foregroundDisabled,+ background: theme.colors.backgroundInputDisabled,+ },+});++const textAreaStyle = css(commonStyle, {});++type Props = Omit<+ ComponentProps<"textarea">,+ "value" | "defaultValue" | "onChange"+> & {css?: CSS;rows?: number;+ maxRows?: number;state?: "invalid";+ value?: string;+ defaultValue?: string;+ onChange?: (value: string) => void;+ autoGrow?: boolean;};export const TextArea = forwardRef((- { css, className, rows = 3, state, ...props }: Props,+ {+ css,+ className,+ rows = 3,+ maxRows,+ state,+ value,+ onChange,+ autoGrow,+ ...props+ }: Props,ref: Ref<HTMLTextAreaElement>) => {+ const [textValue, setTextValue] = useControllableState({+ prop: value,+ defaultProp: props.defaultValue,+ onChange,+ });+// We could use `box-sizing:content-box` to avoid dealing with paddings and border here// But then, the user of the component will not be able to set `width` reliably- const height =+ const minHeight =rows * LINE_HEIGHT + PADDING_TOP + PADDING_BOTTOM + BORDER * 2;+ const height = autoGrow ? undefined : minHeight;++ const maxHeight = maxRows+ ? maxRows * LINE_HEIGHT + PADDING_TOP + PADDING_BOTTOM + BORDER * 2+ : undefined;++ const scrollThumpPositionDelta = 4;+ const textAreaScrollThumbMargin = scrollThumpPositionDelta + 2;+return (- <textarea- spellCheck={false}- className={style({- css: { height, minHeight: height, ...css },+ <Grid+ className={gridStyle({state,- className,+ autoGrow,+ css: { height, minHeight, maxHeight },})}- ref={ref}- {...props}- />+ onClick={(event) => {+ if (event.target instanceof HTMLElement) {+ // Focus textarea on click since it can't match parent height.+ const textarea = event.target.querySelector("textarea");+ if (textarea) {+ textarea.focus();+ }+ }+ }}+ >+ <ScrollArea+ css={{+ height: "100%",+ maxHeight: maxRows ? maxRows * LINE_HEIGHT : undefined,+ marginRight: -scrollThumpPositionDelta,+ // Overwrite hack from scroll-area.tsx+ "& [data-radix-scroll-area-viewport] > div": {+ display: "grid!important",+ },+ }}+ >+ <div+ className={commonStyle({+ css: {+ marginRight: textAreaScrollThumbMargin,+ visibility: "hidden",+ ...css,+ },+ state,+ className,+ })}+ >+ {textValue}{" "}+ </div>++ <textarea+ spellCheck={false}+ className={textAreaStyle({+ css: { marginRight: textAreaScrollThumbMargin, ...css },+ state,+ className,+ })}+ onChange={(event) => setTextValue(event.target.value)}+ value={textValue}+ rows={rows}+ ref={ref}+ {...props}+ />+ </ScrollArea>+ </Grid>);});