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
Make css helper tool for collapsing prevention on canvas really smart (#1059)
Oleg Isonen29f3839456cc
diff --git a/apps/builder/app/canvas/features/wrapper-component/wrapper-component.tsx b/apps/builder/app/canvas/features/wrapper-component/wrapper-component.tsxindex 98610fa196..ed5d7377a3 100644--- a/apps/builder/app/canvas/features/wrapper-component/wrapper-component.tsx+++ b/apps/builder/app/canvas/features/wrapper-component/wrapper-component.tsx@@ -1,4 +1,4 @@-import type { MouseEvent, FormEvent } from "react";+import { MouseEvent, FormEvent, useLayoutEffect } from "react";import { Suspense, lazy, useCallback, useMemo, useRef } from "react";import { useStore } from "@nanostores/react";import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";@@ -8,6 +8,7 @@ import {renderWrapperComponentChildren,getComponent,idAttribute,+ collapsedAttribute,} from "@webstudio-is/react-sdk";import {rootInstanceContainer,@@ -43,6 +44,24 @@ const ContentEditable = ({return <Component ref={ref} {...props} contentEditable={true} />;};+const setDataCollapsed = (element?: HTMLElement) => {+ if (element === undefined) {+ return;+ }+ // When we remove this attribute, artifical helper spacers will be removed,+ // then we synchronously calculate height/width to see if element would collapse+ // then we add spacers back on the side that requires them right away.+ // The idea is to not trigger a reflow while we are calculating offsets before we know+ // if the elmenent needs spacers, because this is going to happen every time elemnt updates and+ // we don't want to trigger a reflow every time.+ element.removeAttribute(collapsedAttribute);+ const collapsedWidth = element.offsetWidth === 0 ? "w" : "";+ const collapsedHeight = element.offsetHeight === 0 ? "h" : "";+ if (collapsedHeight || collapsedWidth) {+ element.setAttribute(collapsedAttribute, collapsedWidth + collapsedHeight);+ }+};+type UserProps = Record<Prop["name"], string | number | boolean>;type WrapperComponentDevProps = {@@ -55,7 +74,7 @@ export const WrapperComponentDev = ({children,}: WrapperComponentDevProps) => {const instanceId = instance.id;-+ const instanceElementRef = useRef<HTMLElement>();const instanceStyles = useInstanceStyles(instanceId);useCssRules({ instanceId: instance.id, instanceStyles });@@ -77,7 +96,9 @@ export const WrapperComponentDev = ({return result;}, [instanceProps]);- const instanceElementRef = useRef<HTMLElement>();+ useLayoutEffect(() => {+ setDataCollapsed(instanceElementRef.current);+ });const readonlyProps =instance.component === "Input" ? { readOnly: true } : undefined;diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.tsindex 6008a6719a..0ce56f72b4 100644--- a/apps/builder/app/canvas/shared/styles.ts+++ b/apps/builder/app/canvas/shared/styles.ts@@ -4,11 +4,13 @@ import { useStore } from "@nanostores/react";import { addGlobalRules } from "@webstudio-is/project";import {assetsStore,+ isPreviewModeStore,selectedInstanceIdStore,useBreakpoints,} from "~/shared/nano-states";import type { StyleDecl } from "@webstudio-is/project-build";import {+ collapsedAttribute,getComponentMeta,getComponentNames,idAttribute,@@ -30,21 +32,46 @@ import {import { useSubscribe } from "~/shared/pubsub";const cssEngine = createCssEngine({ name: "user-styles" });--const voidElements =- "area, base, br, col, embed, hr, img, input, link, meta, source, track, wbr";+const helpersCssEngine = createCssEngine({ name: "helpers" });+const fontsAndDefaultsCssEngine = createCssEngine({+ name: "fonts-and-defaults",+});+const presetStylesEngine = createCssEngine({ name: "presetStyles" });// Helper styles on for canvas in design mode+// - Only instances that would collapse without helper should receive helper+// - Helper is removed when any CSS property is changed on that instance that would prevent collapsing, so that helper is not needed+// - Helper doesn't show on the preview or publish+// - Helper goes away if an instance inserted as a child+// - There is no need to set padding-right or padding-bottom if you just need a small div with a defined or layout-based size, as soon as div is not collapsing, helper should not apply+// - Padding will be only added on the side that would collapse otherwise+//+// For example when I add a div, it is a block element, it grows automatically full width but has 0 height, in this case spacing helper with padidng-top: 50px should apply, so that it doesn't collapse.+// If user sets `height: 100px` or does anything that would give it a height - we remove the helper padding right away, so user can actually see the height they set+//+// In other words we prevent elements from collapsing when they have 0 height or width by making them non-zero on canvas, but then we remove those paddings as soon as element doesn't collapse.const helperStyles = [// When double clicking into an element to edit text, it should not select the word.`[${idAttribute}] {user-select: none;}`,- `[${idAttribute}]:not(${voidElements}):not(body):empty {+ // Using :where allows to prevent increasing specificity, so that helper is overwritten by user styles.+ `[${idAttribute}]:where([${collapsedAttribute}]:not(body)) {outline: 1px dashed #555;outline-offset: -1px;+ }`,+ // Has no width, will collapse+ `[${idAttribute}]:where(:not(body)[${collapsedAttribute}="w"]) {+ padding-right: 50px;+ }`,+ // Has no height, will collapse+ `[${idAttribute}]:where(:not(body)[${collapsedAttribute}="h"]) {padding-top: 50px;+ }`,+ // Has no width or height, will collapse+ `[${idAttribute}]:where(:not(body)[${collapsedAttribute}="wh"]) {padding-right: 50px;+ padding-top: 50px;}`,`[${idAttribute}][contenteditable], [${idAttribute}]:focus {outline: 0;@@ -54,18 +81,35 @@ const helperStyles = [}`,];+const subscribePreviewMode = () => {+ let isRendered = false;++ const unsubscribe = isPreviewModeStore.subscribe((isPreviewMode) => {+ helpersCssEngine.setAttribute("media", isPreviewMode ? "not all" : "all");+ if (isRendered === false) {+ for (const style of helperStyles) {+ helpersCssEngine.addPlaintextRule(style);+ }+ helpersCssEngine.render();+ isRendered = true;+ }+ });++ return () => {+ helpersCssEngine.clear();+ helpersCssEngine.render();+ unsubscribe();+ isRendered = false;+ };+};+export const useManageDesignModeStyles = () => {useUpdateStyle();usePreviewStyle();useRemoveSsrStyles();+ useEffect(subscribePreviewMode, []);};-const helpersCssEngine = createCssEngine({ name: "helpers" });-const fontsAndDefaultsCssEngine = createCssEngine({- name: "fonts-and-defaults",-});-const presetStylesEngine = createCssEngine({ name: "presetStyles" });-export const GlobalStyles = () => {const [breakpoints] = useBreakpoints();const assets = useStore(assetsStore);@@ -76,13 +120,6 @@ export const GlobalStyles = () => {}}, [breakpoints]);- useIsomorphicLayoutEffect(() => {- for (const style of helperStyles) {- helpersCssEngine.addPlaintextRule(style);- }- helpersCssEngine.render();- }, []);-useIsomorphicLayoutEffect(() => {fontsAndDefaultsCssEngine.clear();addGlobalRules(fontsAndDefaultsCssEngine, { assets });diff --git a/packages/css-engine/src/core/css-engine.ts b/packages/css-engine/src/core/css-engine.tsindex 4a8ee1c664..774ff4a724 100644--- a/packages/css-engine/src/core/css-engine.ts+++ b/packages/css-engine/src/core/css-engine.ts@@ -73,6 +73,12 @@ export class CssEngine {unmount() {this.#element.unmount();}+ setAttribute(name: string, value: string) {+ this.#element.setAttribute(name, value);+ }+ getAttribute(name: string) {+ return this.#element.getAttribute(name);+ }get cssText() {if (this.#isDirty === false) {return this.#cssText;diff --git a/packages/css-engine/src/core/style-element.ts b/packages/css-engine/src/core/style-element.tsindex 9c4c32d143..450335991d 100644--- a/packages/css-engine/src/core/style-element.ts+++ b/packages/css-engine/src/core/style-element.ts@@ -25,4 +25,14 @@ export class StyleElement {this.#element.textContent = cssText;}}+ setAttribute(name: string, value: string) {+ if (this.#element) {+ this.#element.setAttribute(name, value);+ }+ }+ getAttribute(name: string) {+ if (this.#element) {+ return this.#element.getAttribute(name);+ }+ }}diff --git a/packages/react-sdk/src/tree/wrapper-component.tsx b/packages/react-sdk/src/tree/wrapper-component.tsxindex a1a1673c78..b08f6a7a26 100644--- a/packages/react-sdk/src/tree/wrapper-component.tsx+++ b/packages/react-sdk/src/tree/wrapper-component.tsx@@ -54,3 +54,4 @@ export const WrapperComponent = ({export const idAttribute = "data-ws-id";export const componentAttribute = "data-ws-component";+export const collapsedAttribute = "data-ws-collapsed";