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
Fix collapse (#1097)
Ivan Starkov967bf5044868
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 7fb214f19d..b77a7b9698 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -38,6 +38,7 @@ import { Navigator } from "./features/sidebar-left";import { getBuildUrl } from "~/shared/router-utils";import { useCopyPaste } from "~/shared/copy-paste";import { AssetsProvider } from "./shared/assets";+import { minWidth } from "./features/breakpoints/width-setting";registerContainers();@@ -74,7 +75,7 @@ const useNavigatorLayout = () => {// We need to render the detached state only once the setting was actually loaded from local storage.// Otherwise we may show the detached state because its the default and then hide it immediately.const [clientSettings, _, isLoaded] = useClientSettings();- return isLoaded ? clientSettings.navigatorLayout : "docked";+ return isLoaded ? clientSettings.navigatorLayout : "undocked";};const useSubscribeCanvasReady = (publish: Publish) => {@@ -333,6 +334,7 @@ export const Builder = ({css={{height: "100%",width: "100%",+ minWidth,}}/></Workspace>diff --git a/apps/builder/app/builder/features/style-panel/shared/style-info.ts b/apps/builder/app/builder/features/style-panel/shared/style-info.tsindex e00627e563..7a4f828a2c 100644--- a/apps/builder/app/builder/features/style-panel/shared/style-info.ts+++ b/apps/builder/app/builder/features/style-panel/shared/style-info.ts@@ -150,7 +150,7 @@ export const getCascadedInfo = (return cascadedStyle;};-const getPresetStyle = (+export const getPresetStyle = (instancesIndex: InstancesIndex,instanceId: undefined | Instance["id"]) => {diff --git a/apps/builder/app/builder/shared/nano-states/index.ts b/apps/builder/app/builder/shared/nano-states/index.tsindex aa2d17e0e8..048e897e48 100644--- a/apps/builder/app/builder/shared/nano-states/index.ts+++ b/apps/builder/app/builder/shared/nano-states/index.ts@@ -3,6 +3,7 @@ import { useStore } from "@nanostores/react";import type { Pages } from "@webstudio-is/project-build";import type { Project } from "@webstudio-is/project";import type { AssetContainer, DeletingAssetContainer } from "../assets";+import { minWidth } from "~/builder/features/breakpoints/width-setting";const useValue = <T>(atom: WritableAtom<T>) => {const value = useStore(atom);@@ -16,7 +17,7 @@ const isPublishDialogOpenContainer = atom<boolean>(false);export const useIsPublishDialogOpen = () =>useValue(isPublishDialogOpenContainer);-const canvasWidthContainer = atom<number>(0);+const canvasWidthContainer = atom<number>(minWidth);export const useCanvasWidth = () => useValue(canvasWidthContainer);const canvasRectContainer = atom<DOMRect | undefined>();diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 267a84593b..de532334a1 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -1,4 +1,4 @@-import { useMemo } from "react";+import { useMemo, Fragment, useEffect } from "react";import { computed } from "nanostores";import type { CanvasData } from "@webstudio-is/project";import {@@ -40,6 +40,7 @@ import { useSubscribeBuilderReady } from "./shared/use-builder-ready";import { useCopyPaste } from "~/shared/copy-paste";import { customComponents } from "./custom-components";import { useHoveredInstanceConnector } from "./hovered-instance-connector";+import { setDataCollapsed, subscribeCollapsedToPubSub } from "./collapsed";registerContainers();@@ -120,6 +121,15 @@ export const Canvas = ({useShortcuts();useSharedShortcuts();+ useEffect(() => {+ const instanceId = data.tree?.root.id;+ if (instanceId !== undefined) {+ setDataCollapsed(instanceId);+ }+ });++ useEffect(subscribeCollapsedToPubSub, []);+const elements = useElementsTree(getComponent);if (elements === undefined) {@@ -130,7 +140,8 @@ export const Canvas = ({return (<><GlobalStyles />- {elements}+ {/* Without fragment elements will be recreated in DesignMode */}+ <Fragment key="elements">{elements}</Fragment></>);}@@ -139,7 +150,7 @@ export const Canvas = ({<><GlobalStyles /><DesignMode />- {elements}+ <Fragment key="elements">{elements}</Fragment></>);};diff --git a/apps/builder/app/canvas/collapsed.ts b/apps/builder/app/canvas/collapsed.tsnew file mode 100644index 0000000000..d508bd5e0f--- /dev/null+++ b/apps/builder/app/canvas/collapsed.ts@@ -0,0 +1,226 @@+import { collapsedAttribute, idAttribute } from "@webstudio-is/react-sdk";+import {+ getCascadedBreakpointIds,+ getCascadedInfo,+ getPresetStyle,+} from "~/builder/features/style-panel/shared/style-info";+import {+ breakpointsContainer,+ instancesIndexStore,+ stylesIndexStore,+} from "~/shared/nano-states";+import { selectedBreakpointStore } from "~/shared/nano-states/breakpoints";+import { subscribe } from "~/shared/pubsub";++const instanceIdSet = new Set<string>();++let rafHandle: number;++// Do not add collapsed paddings for void elements+// https://developer.mozilla.org/en-US/docs/Glossary/Void_element+const voidHtmlElements = [+ "AREA",+ "BASE",+ "BR",+ "COL",+ "EMBED",+ "HR",+ "IMG",+ "INPUT",+ "LINK",+ "META",+ "SOURCE",+ "TRACK",+ "WBR",+];++// Do not add collapsed paddings for replaced elements as at the moment we add them they don't have real size+// https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element+const replacedHtmlElements = ["IFRAME", "VIDEO", "EMBED", "IMG"];++const skipElementsSet = new Set([...voidHtmlElements, ...replacedHtmlElements]);++const getInstanceSize = (instanceId: string) => {+ const breakpoints = breakpointsContainer.get();+ const selectedBreakpoint = selectedBreakpointStore.get();+ const { stylesByInstanceId } = stylesIndexStore.get();+ const instancesIndex = instancesIndexStore.get();+ const selectedBreakpointId = selectedBreakpoint?.id;++ if (selectedBreakpointId === undefined) {+ return {+ width: undefined,+ height: undefined,+ };+ }++ const cascadedBreakpointIds = getCascadedBreakpointIds(+ breakpoints,+ selectedBreakpointId+ );++ const presetStyle = getPresetStyle(instancesIndex, instanceId);++ const cascadedStyle = getCascadedInfo(stylesByInstanceId, instanceId, [+ ...cascadedBreakpointIds,+ selectedBreakpointId,+ ]);++ const widthStyle = cascadedStyle?.width?.value ?? presetStyle?.width;+ const heightStyle = cascadedStyle?.height?.value ?? presetStyle?.height;++ return {+ width:+ widthStyle !== undefined && widthStyle.type === "unit"+ ? widthStyle.value+ : undefined,+ height:+ heightStyle !== undefined && heightStyle.type === "unit"+ ? heightStyle.value+ : undefined,+ };+};++const recalculate = () => {+ const instanceIds = Array.from(instanceIdSet);+ instanceIdSet.clear();+ if (instanceIds.length === 0) {+ return;+ }++ /**+ * Selector to find elements common ancestors+ **/+ const elementSelector = `[${idAttribute}]${instanceIds+ .map((instanceId) => `:has([${idAttribute}="${instanceId}"])`)+ .join("")}`;++ const elements: Element[] = [];++ // Element itself or last common ancestor or body+ const baseElement =+ Array.from(document.querySelectorAll(elementSelector)).pop() ??+ document.body;+ elements.push(baseElement);++ const descendants = baseElement.querySelectorAll(`[${idAttribute}]`);+ elements.push(...descendants);++ const elementsToRecalculate: HTMLElement[] = [];+ const parentsWithAbsoluteChildren = new Map<HTMLElement, number>();++ for (const element of elements) {+ if (!(element instanceof HTMLElement)) {+ continue;+ }++ if (skipElementsSet.has(element.tagName)) {+ // Images should not collapse, and have a fallback.+ // The issue that unloaded image has 0 width and height until explicitly set,+ // so at the moment new Image added we detect it as collapsed.+ // Skip it for now.+ continue;+ }++ // Find all Leaf like elements+ // Leaf like elements are elements that have no children or all children are absolute or fixed+ if (element.childElementCount === 0) {+ elementsToRecalculate.push(element);+ }++ const elementPosition = window.getComputedStyle(element).position;++ if (element.parentElement) {+ if (elementPosition === "absolute" || elementPosition === "fixed") {+ parentsWithAbsoluteChildren.set(+ element.parentElement,+ parentsWithAbsoluteChildren.get(element.parentElement) ?? 0+ );+ } else {+ parentsWithAbsoluteChildren.set(element.parentElement, 1);+ }+ }+ }++ for (const [element, value] of parentsWithAbsoluteChildren.entries()) {+ // All children are absolute or fixed+ if (value === 0) {+ elementsToRecalculate.push(element);+ }+ }++ // Now combine all operations in batches.++ // 1. Remove all collapsed attributes+ baseElement.parentElement?.removeAttribute(collapsedAttribute);+ baseElement.removeAttribute(collapsedAttribute);+ for (const element of baseElement.querySelectorAll(+ `[${collapsedAttribute}]`+ )) {+ element.removeAttribute(collapsedAttribute);+ }++ // 2. Calculate collapsed state+ const collapsedElements = new Map<HTMLElement, string>();++ for (const element of elementsToRecalculate) {+ const elementInstanceId = element.getAttribute(idAttribute);++ if (elementInstanceId === null) {+ throw new Error(`Element ${idAttribute} has no instance id`);+ }++ const elementSize = getInstanceSize(elementInstanceId);++ const collapsedWidth =+ element.offsetWidth === 0 && elementSize.width === undefined ? "w" : "";+ const collapsedHeight =+ element.offsetHeight === 0 && elementSize.height === undefined ? "h" : "";++ if (collapsedHeight || collapsedWidth) {+ collapsedElements.set(element, collapsedWidth + collapsedHeight);+ }+ }++ // 3. Add collapsed attributes+ for (const [element, value] of collapsedElements.entries()) {+ element.setAttribute(collapsedAttribute, value);+ }+};++/**+ * When we add elements or edit element styles, a situation arises where an element can collapse.+ * I.e. get either 0 width or 0 height or both.+ * We need the user to be able to select such elements anyway.+ * We try to find the minimum set of elements that will prevent any of the canvas elements from collapsing.+ * For such elements we set collapsedAttribute and then style helpers add padding to+ * prevent collapsing.+ **/+export const setDataCollapsed = (instanceId: string) => {+ instanceIdSet.add(instanceId);++ cancelAnimationFrame(rafHandle);++ rafHandle = requestAnimationFrame(() => {+ recalculate();+ });+};++/**+ * For optimisation reasons try to extract instanceId of changed elements from pubsub+ * In that case we just check the subtree of parent/common ancestor of changed elements to find collapsed elements+ **/+export const subscribeCollapsedToPubSub = () =>+ subscribe("sendStoreChanges", ({ source, changes }) => {+ for (const change of changes) {+ if (change.namespace === "styleSourceSelections") {+ for (const patch of change.patches) {+ const instanceId = patch.value?.instanceId;++ if (typeof instanceId === "string") {+ setDataCollapsed(instanceId);+ }+ }+ }+ }+ });diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex ec0c62c899..5146e517d1 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -7,7 +7,6 @@ import type { Instance, Prop } from "@webstudio-is/project-build";import {renderWebstudioComponentChildren,idAttribute,- collapsedAttribute,} from "@webstudio-is/react-sdk";import type { GetComponent } from "@webstudio-is/react-sdk";import {@@ -20,7 +19,6 @@ import {import { createInstancesIndex } from "~/shared/tree-utils";import { useCssRules } from "~/canvas/shared/styles";import { SelectedInstanceConnector } from "./selected-instance-connector";-import { useIsomorphicLayoutEffect } from "react-use";const TextEditor = lazy(() => import("../text-editor"));@@ -45,24 +43,6 @@ 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"], Prop["value"]>;type WebstudioComponentDevProps = {@@ -99,10 +79,6 @@ export const WebstudioComponentDev = ({return result;}, [instanceProps]);- useIsomorphicLayoutEffect(() => {- 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 8577d52a16..a7bf85601c 100644--- a/apps/builder/app/canvas/shared/styles.ts+++ b/apps/builder/app/canvas/shared/styles.ts@@ -50,7 +50,7 @@ const presetStylesEngine = createCssEngine({ name: "presetStyles" });// 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 = [+export const helperStyles = [// When double clicking into an element to edit text, it should not select the word.`[${idAttribute}] {user-select: none;@@ -58,7 +58,7 @@ const helperStyles = [// 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;+ outline-offset: -0.5px;}`,// Has no width, will collapse`[${idAttribute}]:where(:not(body)[${collapsedAttribute}="w"]) {diff --git a/apps/builder/app/routes/s/css.ts b/apps/builder/app/routes/s/css.tsindex 2c94a0ccf3..8496b1f63c 100644--- a/apps/builder/app/routes/s/css.ts+++ b/apps/builder/app/routes/s/css.ts@@ -7,6 +7,8 @@ import { sentryException } from "~/shared/sentry";import { createContext } from "~/shared/context.server";import { loadCanvasData, loadProductionCanvasData } from "~/shared/db";import type { Tree } from "@webstudio-is/project-build";+import { createCssEngine } from "@webstudio-is/css-engine";+import { helperStyles } from "~/canvas/shared/styles";export const loader = async ({ request }: ActionArgs) => {try {@@ -48,7 +50,12 @@ export const loader = async ({ request }: ActionArgs) => {styleSourceSelections: canvasData.tree?.styleSourceSelections,});- return new Response(cssText, {+ const engine = createCssEngine({ name: "ssr" });+ for (const style of helperStyles) {+ engine.addPlaintextRule(style);+ }++ return new Response(`${cssText}\n${engine.cssText}`, {headers: {"Content-Type": "text/css",// We have no way with Remix links to know if CSS has changed (no ?cache-breaker in url)