feat(packages/excalidraw): [ui] rewrite ui regions (#11787)

* feat(packages/excalidraw): [ui] rewrite ui regions

* feat(packages/excalidraw): [ui] keep footer + status overlay within editor bounds

The top and center regions move into `.exc-region-mesh`, a sibling of
`.exc-region-bottom` inside `.exc-regions` (a `minmax(0,1fr) auto`
two-row grid). The footer band and the toast/scroll-back overlay no
longer share column tracks with the top row, so wide top-left/top-right
content can no longer push them past the editor edge, and nothing in the
footer can displace the toolbar.

The mesh's side columns keep their content floors (`minmax(auto, 1fr)`),
so the top row negotiates width as in production: toolbar exactly
centered while both sides fit, shifted aside once one side outgrows its
share, and overflowing to the right (clipped at the editor edge) only
when nothing fits. Host slots stay rigid at their intrinsic width; the
collaborator list is the one flexible piece, collapsing avatars into the
"+N" pill (flex-basis 0, so the avatar-count ResizeObserver can't feed
back into layout). The desktop top-right occupants are wrapped in the
shared `.exc-region-top-right-content` cluster.

Claude Opus 5.5 (xhigh)

* feat(packages/excalidraw): [ui] flush UI area with docked sidebar

The layer-ui wrapper (and with it the ViewportStatusFrame border, which
tracks its width) now stops at a docked sidebar's visible edge instead
of the --right-sidebar-width column it reserves — the sidebar's 8px
outer margin was a dead gap between the UI area and the sidebar. The
regions container compensates with a matching right inset so
right-aligned UI (and the status stack's center) keeps its previous
visual position.

Also moves the in-flow mobile bottom-bar status-stack rule inside the
mobile block: it must out-rank the standalone mobile stack rule (which
re-adds the absolute positioning the regions model removed from the
base rule), else the scroll-back button paints over MobileShapeActions
instead of stacking above it.

Claude Fable 5

* feat(packages/excalidraw): [ui] stack top + center regions in three columns

Replaces the 3×4 mesh with three column stacks: each column is a flex
column of its top region and the center region below it, so a center
region clears exactly its own column's top region. The mesh needed
spanning rows that absorb overhangs to express the same dependencies,
plus the invariant that only the top regions may occupy a single track.

Only the top regions size the columns: the center regions have
`contain: inline-size`, so a wide styles panel overflows toward the
canvas instead of widening its column and offsetting the toolbar. The
top-row width negotiation is unchanged (`minmax(auto,1fr) auto
minmax(auto,1fr)`), and a real column-gap replaces the toolbar's inline
margins now that there are no zero-height rows for gaps to double up in.

Behavior change: the stats panel now clears only the top-right UI — a
top-left UI taller than the top-right no longer pushes it down. The
empty center-center region is dropped, and the status stack is
absolutely positioned against `.exc-regions` instead of being a grid
item spanning both rows.

Claude Opus 5.5 (xhigh)

* fix(packages/excalidraw): [ui] bound the stats panel; RTL docked-sidebar inset

The stats panel now scrolls within its region like the styles panel,
instead of running past the footer and covering the help button in
short windows.

The inset that keeps region content clear of a docked sidebar used a
physical `right`, but the sidebar docks on the left in RTL — so the 8px
went to the free edge and the toolbar sat 4px off. It's now
`inset-inline-end`.

Claude Opus 5.5 (xhigh)

* feat(packages/excalidraw): [ui] make regions positioning contexts

Every region is now `position: relative`, so absolutely positioned host
content anchors to its own region. Excalidraw+ hangs its call tray below
the top-right UI with `absolute top-10 right-0`; without a positioned
region it anchored to `.exc-regions` instead, which lands in the same
spot in LTR only by coincidence and on the wrong side in RTL.

Claude Opus 5.5 (xhigh)

* feat(packages/excalidraw): [ui] render host top-right UI alongside defaults on phone

On phones, `renderTopRightUI` content used to replace the editor's
top-right controls (sidebar trigger, pen-mode button) — any non-nullish
return value hid them. It now renders next to them, same as on desktop
and as before the new mobile layout (#9996). excalidraw.com returns
null on phones, so it's unaffected; Excalidraw+ already patched its
fork to render both.

Claude Opus 5.5 (xhigh)

* feat: Progressive collapse

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Region API with priority-based collapse and overflow menu

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Vertical and footer region collapse, phone mapping, status stack placement

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix(packages/excalidraw): [ui] let shrink items shrink in the top-left region

The floor counts shrink items at their minWidth, but the top-left grid
track sized to the content's min-content, so a nowrap item (e.g. a host
scene name) overflowed the region under the toolbar instead of truncating.

Claude Opus 5.5 (reasoning: xhigh)

* fix(packages/excalidraw): [ui] region floors stuck at 0 or too small

- compute the floor before the budget check: a floor measured before the
  items' tunneled content rendered (0px) shrank the region to 0, which
  left no budget, so the floor was never re-measured (fresh load at a
  narrow width put the top-right UI over the toolbar)
- count gaps for displayed zero-width items (e.g. absolutely positioned
  host content), which still take a gap in the row
- user list minWidth includes the current user's pill (57px, not 36px)

Claude Opus 5.5 (reasoning: xhigh)

* fix(packages/excalidraw): [ui] compute the toolbar fold count analytically

Every foldable tool is as wide as the hand tool, so the fold count is a
closed-form function of the region's width — no fold-and-remeasure loop.
Folds land in the same frame as the resize (flushSync in the
ResizeObserver), resize down/up end in the same state, and an open "more
tools" menu no longer corrupts the cached tool widths (it ratcheted the
toolbar track until reload).

* fix(packages/excalidraw): [ui] measure the editor interface before first paint

The constructor can't measure the container, so the first render always
assumed a desktop editor with the full UI; a tablet-sized editor painted
the full toolbar and switched to the compact one on some later render.

* fix(packages/excalidraw): [ui] no layout shifts around the collaborator list

- floored top-right content can shrink to the floor, so the list no longer
  renders a frame with the avatars of its previous width (overflowing
  under the toolbar)
- the list re-renders in its ResizeObserver callback, before paint (it was
  a frame late e.g. when a host item next to it appeared)
- the list is as tall as the buttons next to it (it grew the row by 1px)

* feat(packages/excalidraw): [ui] replace region "⋯" menus with collapse="hide"

A second "⋯" next to the toolbar's own is confusing. Items now either
adapt (`render`) or go away (`hide`, with 32px to spare), on desktop and
phone. The stats panel just scrolls down to 120px, like the styles panel.

* feat(packages/excalidraw): [ui] keep region items collapsed on tablets

The compact UI below 1180px frees room, so items collapsed at a wider
editor expanded again — they came and went while resizing.

* fix(packages/excalidraw): [ui] don't clip the styles and stats panel shadows

Their region items were scroll containers on top of the panels' own
scrolling.

* feat(excalidraw-app): [ui] hide the promo while collaborating or when it doesn't fit

* fix(packages/excalidraw): [ui] keep the styles panel clear of the minimap

The minimap (from master, ported into the bottom-left region) floats above
the canvas actions, in the left column's way. Its region now stops above
it — the region's budget follows, so the panel scrolls — instead of the
hardcoded MINIMAP_RESERVED_HEIGHT the old max-height used.

* fix(packages/excalidraw): [ui] phone: "more tools" menu opens above the scroll-back button

The status stack kept its z-index inside the bottom bar (it applies to a
static flex item too), which put it above the toolbar's menu.

* fix(packages/excalidraw): [ui] RTL: follow frame inset on the docked sidebar's side

The inset was a physical `right`, but the sidebar docks on the left in
RTL: the frame was drawn over the sidebar and left a sidebar-wide strip of
canvas outside it.

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
This commit is contained in:
David LuzarandMark Tolmacs authored and GitHub committed 2026-12-02 20:22:50 +01:00
1 parent c2fe379867
commit 548eff0c3d
34 files changed
+2322 -622

No files matched your search

@@ -34,10 +34,6 @@
}
}
.excalidraw .App-menu_top .buttonList {
display: flex;
}
.excalidraw-wrapper {
height: 800px;
margin: 50px;
@@ -45,13 +41,6 @@
overflow: hidden;
}
:root[dir="ltr"]
.excalidraw
.layer-ui__wrapper
.zen-mode-transition.App-menu_bottom--transition-left {
transform: none;
}
.excalidraw .selected-shape-actions {
text-align: left;
}
@@ -82,9 +71,6 @@
padding: 0.1rem;
margin: 0 8px;
}
.layer-ui__wrapper__footer.App-menu_bottom {
align-items: stretch;
}
// till its merged in OSS
.App-toolbar-container .mobile-misc-tools-container {
position: absolute;
+31 -24
View File
@@ -1,6 +1,7 @@
import {
Excalidraw,
LiveCollaborationTrigger,
Region,
TTDDialogTrigger,
CaptureUpdateAction,
reconcileElements,
@@ -1008,30 +1009,6 @@ const ExcalidrawWrapper = () => {
autoFocus={true}
theme={editorTheme}
onThemeChange={setAppTheme}
renderTopRightUI={(isMobile) => {
if (isMobile || !collabAPI || !isCollabAvailable) {
return null;
}
return (
<div className="excalidraw-ui-top-right">
{excalidrawAPI?.getEditorInterface().formFactor === "desktop" && (
<ExcalidrawPlusPromoBanner
isSignedIn={isExcalidrawPlusSignedUser}
/>
)}
{collabError.message && <CollabError collabError={collabError} />}
<LiveCollaborationTrigger
isCollaborating={isCollaborating}
onSelect={() =>
setShareDialogState({ isOpen: true, type: "share" })
}
editorInterface={editorInterface}
/>
</div>
);
}}
onLinkOpen={(element, event) => {
if (element.link && isElementLink(element.link)) {
event.preventDefault();
@@ -1043,6 +1020,36 @@ const ExcalidrawWrapper = () => {
}
}}
>
{collabAPI && isCollabAvailable && (
<Region area="top-right">
{/* not while collaborating (the collaborator list needs the
room); first to go once it doesn't fit */}
{!isCollaborating && (
<Region.Item collapse="hide" priority={1} mobile="hide">
<ExcalidrawPlusPromoBanner
isSignedIn={isExcalidrawPlusSignedUser}
/>
</Region.Item>
)}
{collabError.message && (
<Region.Item mobile="hide">
<CollabError collabError={collabError} />
</Region.Item>
)}
<Region.Item collapse="render" priority={10} mobile="hide">
{({ collapsed }) => (
<LiveCollaborationTrigger
isCollaborating={isCollaborating}
onSelect={() =>
setShareDialogState({ isOpen: true, type: "share" })
}
editorInterface={editorInterface}
iconOnly={collapsed}
/>
)}
</Region.Item>
</Region>
)}
<AppMainMenu
onCollabDialogOpen={onCollabDialogOpen}
isCollaborating={isCollaborating}
+50
View File
@@ -120,6 +120,56 @@ Breaking. `exportToCanvas`, `exportToBlob` and `exportToSvg` (in both `@excalidr
- `onDuplicate` may return `false` to prevent the duplication as a whole (same as omitting every duplicate, without having to find them).
- `onDuplicate` receives a third argument with lookups covering just the elements taking part in the duplication, so you don't have to derive them by scanning the scene: `{ duplicateElements, originalElements, origIdToDuplicateId, duplicateIdToOrigId }` — the duplicates by id, the elements they were made from by id, and their ids mapped in both directions (`duplicateIdToOrigId` to look up a duplicate's original while modifying it, `origIdToDuplicateId` e.g. for remapping element ids you keep in `customData`). On paste and library insert the originals are the inserted elements, which aren't part of the scene. The maps are read-only.
### Region API
- Added `<Region area>` / `<Region.Item>` for placing host UI into the editor's layout regions. Render them as children of `<Excalidraw>`; `area` is one of `top-left`, `top-right`, `center-left`, `center-right`, `bottom-left`, `bottom-right` (the toolbar's `top-center` and `<Footer>`'s `bottom-center` stay closed).
- `<Region.Item>` props: `priority` (lower gives up space first, default `0`), `order` (position within the region, ascending, default `10`; editor items sit at: top-left — `renderTopLeftUI` -10, main menu 0; top-right — collaborator list 0, `renderTopRightUI` 10, sidebar trigger 100; center-left — styles panel 0, pen mode button 1; center-right — stats 0; bottom-left — zoom/undo 0; bottom-right — help 100), `collapse`, `minWidth`, `minHeight`, `mobile`, `className`. `children` may be a function of `{ collapsed }`.
- `collapse` sets how an item gives up space when its region runs out of it: `rigid` (default — keeps its size), `shrink` (top/bottom regions: takes the leftover width down to `minWidth`; the item adapts itself), `render` (switches to its collapsed variant, `({ collapsed }) => …`), `hide` (isn't shown while it doesn't fit — with 32px to spare, so optional UI goes before the row gets tight). Top regions collapse on width against their share of the toolbar row; bottom-left / bottom-right on width against half the footer band each; center regions on height, against what's left of their column above the footer. In the center regions, an item with a `minHeight` scrolls down to that height before it — or a lower priority item — collapses. On tablet-sized editors (`formFactor: "tablet"`, where the editor's own UI is compact) `render` items are always collapsed and `hide` items hidden, so that items don't come and go around that breakpoint as the editor is resized.
- When a top region outgrows its share of the row, its items collapse — lowest priority first — before the toolbar moves aside; the region's fully collapsed row is what the toolbar makes room for. A `render` item is rendered collapsed for one pre-paint pass to measure its collapsed width.
- `mobile` sets how an item shows in the phone layout (which only has a top bar): `same` (default — top-left / top-right items render expanded in the top bar; items of the other areas aren't shown, as the phone layout doesn't have those — render them e.g. in the main menu instead), `hide`. Phone top bars don't collapse items.
- The editor's own panels are region items too: the styles and stats panels scroll down to 120px on short windows.
- `bottom-center` is a CSS size container named `exc-footer`, so `<Footer>` content can adapt with `@container exc-footer (max-width: …)`.
- `renderTopLeftUI` / `renderTopRightUI` keep working as rigid items.
- `LiveCollaborationTrigger` takes an optional `iconOnly` to force its icon-only or labeled variant (e.g. from a `collapse="render"` item).
### UI layout regions (2026-07-27)
The editor UI is now laid out in 3×3 logical regions (the middle of the canvas has none), replacing the top bar (`FixedSideContainer` > `.App-menu_top`) plus absolutely-positioned footer:
```
.exc-regions
|_ .exc-region-columns
| |_ .exc-region-column-left |_ .exc-region-top-left |_ .exc-region-center-left
| |_ .exc-region-column-center |_ .exc-region-top-center
| |_ .exc-region-column-right |_ .exc-region-top-right |_ .exc-region-center-right
|_ .exc-region-bottom
|_ .exc-region-bottom-left .exc-region-bottom-center .exc-region-bottom-right
```
Regions at the same height negotiate width with each other. The top row has four regimes as the editor narrows: with room to spare the toolbar is exactly viewport-centered between equal side tracks; once one side's content outgrows its share, that side pins to its content width and the toolbar shifts aside, making exactly enough room (e.g. tablet portrait while collaborating); once both sides are at their content width, the toolbar shrinks by folding tools into its "More tools" menu; and when nothing fits even fully folded, the top row overflows to the right and is clipped at the editor edge — content never slides under its neighbors. The collaborator list is the one flexible piece: it takes whatever width is left in the top-right cluster and collapses avatars into a "+N" pill as that space shrinks. The top and center regions stack in three columns, so each center region hangs right below the top region of its own column — the styles panel below the top-left UI, the stats panel below the top-right UI — regardless of how far the toolbar or the other side reach down. Only the top regions size the columns: the center regions never widen their column or offset the toolbar. The footer band (`.exc-region-bottom`) is a separate sibling grid of the columns: nothing in the footer can displace the toolbar, an overflowing top row cannot push the footer or the toast past the editor edge, and its flexible center track prevents the footer regions from overlapping. Regions stretch across their column or cell and stay `pointer-events: none`, with only their content interactive.
#### Breaking changes
If you style or query the editor DOM:
- Removed class names: `.App-menu`, `.App-menu_top`, `.App-menu_top__left`, `.App-menu_bottom`, `.App-menu_left`, `.App-menu_right`, `.shapes-section`, `.layer-ui__wrapper__top-right` (+ `--compact`), `.layer-ui__wrapper__footer`, `.layer-ui__wrapper__footer-left` (+ `--transition-left`), `.layer-ui__wrapper__footer-right`. Target the region classes above instead — e.g. `.App-menu_top__left` → `.exc-region-top-left`, `.layer-ui__wrapper__top-right` → `.exc-region-top-right`, `.layer-ui__wrapper__footer-left` → `.exc-region-bottom-left`.
- `.FixedSideContainer` (and `.FixedSideContainer_side_top`) is now only rendered by the mobile UI. The desktop UI area is `.exc-regions`.
- The zen-mode modifier `.layer-ui__wrapper__footer-left--transition-bottom` is now `.transition-bottom`, alongside the existing `.transition-left` / `.transition-right`.
- The styles panel (`.App-menu__left`) and the stats panel (`.exc-stats`) are no longer absolutely positioned — they are in flow inside `.exc-region-center-left` / `.exc-region-center-right`.
- `<Footer>` content renders in the flexible `.exc-region-bottom-center` track between the zoom/undo controls and help button. `.footer-center` remains full-width flex content, so hosts can keep content beside the left controls, beside the right controls, or at both edges using flex alignment and auto margins.
- The host-content containers `.excalidraw-ui-top-left` / `.excalidraw-ui-top-right` were split into two concepts: `.exc-region-top-left-content` / `.exc-region-top-right-content` are the mixed rows of editor + host content (shared with the mobile top bar), and the new `.exc-region-top-left-host-slot` / `.exc-region-top-right-host-slot` wrap _only_ the host-rendered output (`renderTopLeftUI` / `renderTopRightUI`). Slots are flex rows (`gap: 0.5rem`) and hide themselves when empty, so host content no longer needs its own flex wrapper — returning a fragment is enough. Host content keeps its intrinsic width and participates in the top-row width negotiation: it can push the toolbar aside and, past that, overflow the editor edge (as before the rewrite) — it is never shrunk or clipped mid-cluster.
#### Behavior changes
- The styles panel is bounded by its region — from below the top-left UI down to the footer band, or the minimap when it's shown — and scrolls past it, instead of the hardcoded `height - 166px` max-height (less the minimap's height). Its default position is unchanged; it no longer shifts down when a host renders a tall top-right UI, and it is correctly bounded when the top-left UI is taller than the default menu button.
- The styles panel's width no longer depends on the top-left UI's width — a wide `renderTopLeftUI` (e.g. a scene-name field) previously stretched the shared left column, inflating the panel's container and swallowing canvas clicks next to it.
- The stats panel starts below the top-right UI (default position unchanged in full mode; in compact mode it aligns with the styles panel, 8px higher than before), so tall host UI in the top-right region pushes it down instead of overlapping it — while the toolbar's height and the top-left UI don't affect it.
- In compact mode, the pen-mode button centers over the styles panel rather than over the top-left UI.
- On phones, `renderTopRightUI` content renders alongside the editor's top-right controls (the default sidebar trigger, and the pen-mode button when a pen is detected), same as on desktop. Previously any host content replaced them. Render your own `<DefaultSidebar.Trigger>` to customize the trigger.
- The toast, the scroll-back-to-content button, and the `ViewportStatusFrame` badge sit in a shared full-width overlay column, centered on the canvas rather than on the footer's asymmetric middle track, ending 0.5rem above the editor's bottom edge (plus the frame border when shown) — same as the post-#11841 UI.
- With a docked sidebar, the UI area — and with it the `ViewportStatusFrame` border — now reaches the sidebar's visible edge instead of stopping 8px short of it (the sidebar's outer margin used to be a dead gap between the two). Right-aligned UI keeps its previous visual position.
- At narrow widths the top row degrades in order: the collaborator list collapses to its "+N" pill first, then the toolbar shifts off-center to make room for the side clusters, then the toolbar folds tools into its "More tools" menu, from the end (eraser, sticky note, text, freedraw, line, arrow, ellipse, diamond, rectangle; lock, hand and selection always stay), and past that the top row overflows to the right, clipped at the editor edge — while the footer band and the toast/scroll-back overlay always remain bounded by the editor. Folded tools keep their keyboard shortcuts, and when one is active the "More tools" trigger shows its icon as selected. The toolbar keeps 1rem side clearance.
### Host-controlled active tool (2026-07-14) [#11665](https://github.com/excalidraw/excalidraw/pull/11665)
- Added `activeTool` prop (`{ type: ToolType } | { type: "custom"; customType: string }`) for forcing the active editor tool (controlled). While set, user- and API-driven tool switching is ignored — `setActiveTool` refuses non-matching activations with a console warning, non-forced toolbar buttons render disabled, and the tool-lock toggle (`Q`) is inert — and the editor snaps back if internal flows reset the tool (e.g. `restore()` on scene load). The forced tool behaves as if locked — it doesn't revert to selection after use and drawn elements aren't auto-selected — without mutating `appState.activeTool.locked`, so the user's persisted padlock preference stays untouched. Unset the prop to return tool control to the editor (the current tool stays active). The forced tool must be activatable to take effect — not disabled via `UIOptions.tools`, and (while non-interactive) allowed via `interaction.enabled.tools`; otherwise the editor stays on the `selection` tool and applies the forced tool once it becomes activatable. `image` cannot be forced (its activation opens the file picker). Composes with `interaction.enabled.tools` for presentation-style hosts: force `laser` for the presenter, `selection` + `interaction={false}` for viewers.
@@ -319,6 +319,8 @@
.compact-shape-actions-island {
width: fit-content;
overflow-x: hidden;
// may shrink (and scroll) to fit its region
min-height: 0;
}
.mobile-shape-actions {
+1 -1
View File
@@ -917,7 +917,7 @@ export const ZoomActions = ({
{minimapUIEnabled && (
<div
className={clsx("minimap-toggle zen-mode-transition", {
"layer-ui__wrapper__footer-left--transition-bottom": zenModeEnabled,
"transition-bottom": zenModeEnabled,
})}
>
{actionManager.renderAction("minimap")}
+11
View File
@@ -3769,6 +3769,17 @@ class App extends React.Component<AppProps, AppState> {
this.excalidrawContainerValue.container =
this.excalidrawContainerRef.current;
// The constructor couldn't measure the container (it wasn't mounted
// yet), so the first render used the default editor interface (desktop,
// full UI). Correct it before the first paint — otherwise e.g. a
// tablet-sized editor paints the full toolbar, and switches to the
// compact one on some later render. (Skipped where the container has no
// layout, e.g. when hidden, or in jsdom.)
if (this.excalidrawContainerRef.current?.offsetWidth) {
this.refreshEditorInterface();
this.setState({});
}
if (isTestEnv() || isDevEnv()) {
const setState = this.setState.bind(this);
Object.defineProperties(window.h, {
+9 -48
View File
@@ -16,36 +16,6 @@
pointer-events: none;
z-index: var(--zIndex-layerUI);
&__top-right {
display: flex;
width: 100%;
justify-content: flex-end;
gap: 0.75rem;
pointer-events: none !important;
&--compact {
gap: 0.5rem;
}
& > * {
pointer-events: var(--ui-pointerEvents);
}
}
&__footer {
width: 100%;
&-left {
// anchors the minimap
position: relative;
}
&-right {
z-index: 100;
display: flex;
}
}
// UI hidden in zen mode fades out in place. `visibility` flips at the end
// of the fade-out (and immediately on fade-in), and makes the hidden UI
// non-interactive & unfocusable.
@@ -55,7 +25,7 @@
&.transition-left,
&.transition-right,
&.layer-ui__wrapper__footer-left--transition-bottom {
&.transition-bottom {
opacity: 0;
visibility: hidden;
@@ -72,10 +42,10 @@
position: absolute;
bottom: 0;
[dir="ltr"] & {
right: 1rem;
right: 0;
}
[dir="rtl"] & {
left: 1rem;
left: 0;
}
opacity: 0;
visibility: hidden;
@@ -108,29 +78,20 @@
}
}
.layer-ui__wrapper__footer-left,
.footer-center,
.layer-ui__wrapper__footer-right {
.footer-center {
& > * {
pointer-events: var(--ui-pointerEvents);
}
}
.layer-ui__wrapper__footer-right {
margin-top: auto;
margin-bottom: auto;
}
}
// on tablet, the pen mode button is rendered as a separate floating button
// below the compact actions menu (see LayerUI.tsx)
.App-menu_top__left > .ToolIcon__penMode {
// NOTE: not `justify-self: center` — that centers against the grid
// column's track width, which (see above) can be inflated by unrelated
// content, visibly shifting this button off from the icon stack above
// it. Nudge by hand instead, against the fixed-width compact actions
// column (see .selected-shape-actions-container--compact's min-width).
justify-self: start;
// NOTE: not `justify-self: center` — the center-left region's grid track
// is as wide as its widest item, which may be host content. Nudge by hand
// instead, against the fixed-width compact actions column (see
// .selected-shape-actions-container--compact's min-width).
.exc-region-item--pen-mode > .ToolIcon__penMode {
margin-left: calc((48px - var(--lg-button-size)) / 2);
.ToolIcon__icon {
+459 -206
View File
@@ -18,11 +18,16 @@ import { ShapeCache } from "@excalidraw/element";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import { actionToggleMinimap, actionToggleStats } from "../actions";
import {
actionShortcuts,
actionToggleMinimap,
actionToggleStats,
} from "../actions";
import { trackEvent } from "../analytics";
import { TunnelsContext, useInitializeTunnels } from "../context/tunnels";
import { UIAppStateContext } from "../context/ui-appState";
import { useAtom, useAtomValue } from "../editor-jotai";
import { useToolbarFolding } from "../hooks/useToolbarFolding";
import { t } from "../i18n";
import { getScrollToContentState, getSelectedElements } from "../scene";
@@ -32,16 +37,21 @@ import {
type ColorDefaultKey,
} from "../actions/colorTargets";
import { SelectedShapeActions, CompactShapeActions } from "./Actions";
import {
SelectedShapeActions,
CompactShapeActions,
ExitZenModeButton,
UndoRedoActions,
ZoomActions,
} from "./Actions";
import { LoadingMessage } from "./LoadingMessage";
import { MobileMenu } from "./MobileMenu";
import { PasteChartDialog } from "./PasteChartDialog";
import { Section } from "./Section";
import Stack from "./Stack";
import { UserList } from "./UserList";
import { UserList, getUserListMinWidth } from "./UserList";
import { PenModeButton } from "./PenModeButton";
import Footer from "./footer/Footer";
import { MINIMAP_RESERVED_HEIGHT } from "./Minimap/Minimap";
import { Minimap } from "./Minimap/Minimap";
import { isSidebarDockedAtom } from "./Sidebar/Sidebar";
import MainMenu from "./main-menu/MainMenu";
import { ActiveConfirmDialog } from "./ActiveConfirmDialog";
@@ -58,7 +68,9 @@ import { Stats } from "./Stats";
import ElementLinkDialog from "./ElementLinkDialog";
import { ErrorDialog } from "./ErrorDialog";
import { EyeDropper, activeEyeDropperAtom } from "./EyeDropper";
import { FixedSideContainer } from "./FixedSideContainer";
import { HelpButton } from "./HelpButton";
import { FloatingStatusStack } from "./regions/FloatingStatusStack";
import { RegionCluster } from "./regions/RegionItems";
import { HelpDialog } from "./HelpDialog";
import { ImageExportDialog } from "./ImageExportDialog";
import { Island } from "./Island";
@@ -85,6 +97,7 @@ import type {
UIAppState,
AppClassProperties,
} from "../types";
import type { RegionItemSpec } from "./regions/RegionRegistry";
interface LayerUIProps {
actionManager: ActionManager;
@@ -113,12 +126,6 @@ interface LayerUIProps {
currentUserControls?: ExcalidrawProps["currentUserControls"];
}
/**
* The space (px) the floating pen mode button of the compact UI takes up
* below the styles panel: the button (`--lg-button-size`) + the gap above.
*/
const PEN_MODE_BUTTON_RESERVED_HEIGHT = 54;
const DefaultMainMenu: React.FC<{
UIOptions: AppProps["UIOptions"];
}> = ({ UIOptions }) => {
@@ -184,6 +191,17 @@ const LayerUI = ({
const appProps = useAppProps();
const stylesPanelMode = useStylesPanelMode();
const isCompactStylesPanel = stylesPanelMode === "compact";
const regionColumnsRef = React.useRef<HTMLDivElement>(null);
const toolbarFoldedCount = useToolbarFolding(
regionColumnsRef,
// the desktop regions (and the toolbar in them) are rendered
editorInterface.formFactor !== "phone" &&
defaultUIEnabled &&
!appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector",
stylesPanelMode,
);
const tunnels = useInitializeTunnels();
const spacing = isCompactStylesPanel
@@ -250,33 +268,55 @@ const LayerUI = ({
const minimapUIEnabled = actionManager.isActionEnabled(actionToggleMinimap);
// editor items of the regions, laid out (and collapsed) together with
// host `<Region.Item>`s — see `RegionItemSpec.order` for their positions.
// They never collapse unless `extra` says so.
const editorItem = (
id: string,
order: number,
content: React.ReactNode,
extra?: Partial<RegionItemSpec>,
): RegionItemSpec => ({
id: `editor:${id}`,
order,
content,
priority: Infinity,
collapse: "rigid",
minWidth: 0,
minHeight: 0,
// the phone layout renders its own editor UI
mobile: "hide",
seq: -1,
...extra,
});
const renderCanvasActions = () => (
<div style={{ position: "relative" }}>
<div className="excalidraw-ui-top-left">
{renderTopLeftUI?.(false, appState)}
<tunnels.MainMenuTunnel.Out />
</div>
<RegionCluster
area="top-left"
className="exc-region-top-left-content"
budget="region"
floor
editorItems={[
...(renderTopLeftUI
? [
editorItem(
"host-top-left",
-10,
<div className="exc-region-top-left-host-slot">
{renderTopLeftUI(false, appState)}
</div>,
),
]
: []),
editorItem("main-menu", 0, <tunnels.MainMenuTunnel.Out />),
]}
/>
{renderWelcomeScreen && <tunnels.WelcomeScreenMenuHintTunnel.Out />}
</div>
);
const renderSelectedShapeActions = () => {
// we want to make sure this doesn't overflow so subtracting the
// approximate height of hamburgerMenu + footer
let stylesPanelMaxHeight = appState.height - 166;
// the minimap sits above the footer, in the way of this column
if (minimapUIEnabled && appState.minimapEnabled) {
stylesPanelMaxHeight -= MINIMAP_RESERVED_HEIGHT;
// ...which, in compact UI, ends with the pen mode button (see below)
if (
isCompactStylesPanel &&
appState.penDetected &&
!appState.viewModeEnabled
) {
stylesPanelMaxHeight -= PEN_MODE_BUTTON_RESERVED_HEIGHT;
}
}
return (
<Section
heading="selectedShapeActions"
@@ -290,9 +330,6 @@ const LayerUI = ({
padding={0}
data-viewport-ui="side"
data-viewport-ui-name="stylesPanel"
style={{
maxHeight: `${stylesPanelMaxHeight}px`,
}}
>
<CompactShapeActions
appState={appState}
@@ -306,9 +343,6 @@ const LayerUI = ({
<Island
className={CLASSES.SHAPE_ACTIONS_MENU}
padding={2}
style={{
maxHeight: `${stylesPanelMaxHeight}px`,
}}
data-viewport-ui="side"
data-viewport-ui-name="stylesPanel"
>
@@ -324,7 +358,16 @@ const LayerUI = ({
);
};
const renderFixedSideContainer = () => {
/**
* The editor UI is laid out in 3×3 logical regions (see `.exc-regions` in
* styles.scss for the how and why). The top and center regions stack in
* three columns; the bottom regions form a separate footer band:
*
* top-left top-center top-right
* center-left center-right
* bottom-left bottom-center bottom-right
*/
const renderUIRegions = () => {
const shouldRenderSelectedShapeActions =
defaultUIEnabled && showSelectedShapeActions(appState, elements);
@@ -335,133 +378,379 @@ const LayerUI = ({
!appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector";
const shouldRenderToolbar =
defaultUIEnabled &&
!appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector";
const shouldRenderCanvasActions =
defaultUIEnabled || (zoomUIEnabled && app.isNavigationEnabled());
const shouldRenderMinimap =
shouldRenderCanvasActions && minimapUIEnabled && appState.minimapEnabled;
return (
<FixedSideContainer side="top">
<div className="App-menu App-menu_top">
<Stack.Col
gap={spacing.menuTopGap}
className={clsx("App-menu_top__left")}
>
{renderCanvasActions()}
{defaultUIEnabled && (
<div
className={clsx("selected-shape-actions-container", {
"selected-shape-actions-container--compact":
isCompactStylesPanel,
})}
>
{shouldRenderSelectedShapeActions &&
renderSelectedShapeActions()}
</div>
)}
{/* in compact UI the pen mode button lives outside the toolbar, as
a separate floating button below the compact actions menu
(same as we render it on mobile); shown alongside the compact
actions island, i.e. when a drawing tool or elements are
selected */}
{defaultUIEnabled &&
isCompactStylesPanel &&
!appState.viewModeEnabled &&
shouldRenderSelectedShapeActions && (
<PenModeButton
checked={appState.penMode}
onChange={() => onPenModeToggle(null)}
title={t("toolBar.penMode")}
isMobile
penDetected={appState.penDetected}
/>
)}
</Stack.Col>
{defaultUIEnabled &&
!appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector" && (
<Section heading="shapes" className="shapes-section">
{(heading: React.ReactNode) => (
<div style={{ position: "relative" }}>
{renderWelcomeScreen && (
<tunnels.WelcomeScreenToolbarHintTunnel.Out />
)}
<Stack.Col gap={spacing.toolbarColGap} align="start">
<Stack.Row
gap={spacing.toolbarRowGap}
className={clsx("App-toolbar-container", {
"zen-mode": appState.zenModeEnabled,
})}
>
<Toolbar
app={app}
appState={appState}
setAppState={setAppState}
UIOptions={UIOptions}
onPenModeToggle={onPenModeToggle}
onLockToggle={onLockToggle}
heading={heading}
/>
{isCollaborating && (
<Island
style={{
marginLeft: spacing.collabMarginLeft,
alignSelf: "center",
height: "fit-content",
}}
<div
className={clsx("exc-regions", {
"exc-regions--minimap": shouldRenderMinimap,
})}
style={
{
// gap between vertically stacked regions, e.g. between the
// top-left menu and the styles panel below it
"--exc-regions-row-gap": `calc(var(--space-factor) * ${spacing.menuTopGap})`,
} as React.CSSProperties
}
>
<div className="exc-region-columns" ref={regionColumnsRef}>
<div className="exc-region-column-left">
<div className="exc-region exc-region-top-left">
{renderCanvasActions()}
</div>
<div className="exc-region exc-region-center-left">
<RegionCluster
area="center-left"
budget="column"
editorItems={[
...(shouldRenderSelectedShapeActions
? [
editorItem(
"styles-panel",
0,
<div
className={clsx(
"selected-shape-actions-container",
{
"selected-shape-actions-container--compact":
isCompactStylesPanel,
},
)}
>
<LaserPointerButton
title={t("toolBar.laser")}
checked={
appState.activeTool.type === TOOL_TYPE.laser
}
onChange={() =>
app.setActiveTool({ type: TOOL_TYPE.laser })
}
isMobile
/>
</Island>
)}
</Stack.Row>
</Stack.Col>
</div>
)}
</Section>
{renderSelectedShapeActions()}
</div>,
// scrolls (down to this height) instead of
// collapsing
{
minHeight: 120,
className: "exc-region-item--self-scrolling",
},
),
]
: []),
// in compact UI the pen mode button lives outside the
// toolbar, as a separate floating button below the compact
// actions menu (same as we render it on mobile); shown
// alongside the compact actions island, i.e. when a
// drawing tool or elements are selected
...(isCompactStylesPanel &&
!appState.viewModeEnabled &&
shouldRenderSelectedShapeActions
? [
editorItem(
"pen-mode",
1,
<PenModeButton
checked={appState.penMode}
onChange={() => onPenModeToggle(null)}
title={t("toolBar.penMode")}
isMobile
penDetected={appState.penDetected}
/>,
{ className: "exc-region-item--pen-mode" },
),
]
: []),
]}
/>
</div>
</div>
<div className="exc-region-column-center">
<div className="exc-region-top-center">
{shouldRenderToolbar && (
<Section heading="shapes">
{(heading: React.ReactNode) => (
<div style={{ position: "relative" }}>
{renderWelcomeScreen && (
<tunnels.WelcomeScreenToolbarHintTunnel.Out />
)}
<Stack.Col gap={spacing.toolbarColGap} align="start">
<Stack.Row
gap={spacing.toolbarRowGap}
className={clsx("App-toolbar-container", {
"zen-mode": appState.zenModeEnabled,
})}
>
<Toolbar
app={app}
appState={appState}
setAppState={setAppState}
UIOptions={UIOptions}
onPenModeToggle={onPenModeToggle}
onLockToggle={onLockToggle}
heading={heading}
foldedCount={toolbarFoldedCount}
/>
{isCollaborating && (
<Island
style={{
marginLeft: spacing.collabMarginLeft,
alignSelf: "center",
height: "fit-content",
}}
>
<LaserPointerButton
title={t("toolBar.laser")}
checked={
appState.activeTool.type === TOOL_TYPE.laser
}
onChange={() =>
app.setActiveTool({ type: TOOL_TYPE.laser })
}
isMobile
/>
</Island>
)}
</Stack.Row>
</Stack.Col>
</div>
)}
</Section>
)}
</div>
</div>
<div className="exc-region-column-right">
<div
className={clsx(
"exc-region exc-region-top-right zen-mode-transition",
{
"transition-right": appState.zenModeEnabled,
"exc-region-top-right--compact": isCompactStylesPanel,
},
)}
>
<RegionCluster
area="top-right"
className="exc-region-top-right-content"
budget="region"
floor
editorItems={[
...(defaultUIEnabled && appState.collaborators.size > 0
? [
editorItem(
"user-list",
0,
<UserList
collaborators={appState.collaborators}
userToFollow={
appProps.userToFollow?.socketId || null
}
currentUserControls={currentUserControls}
/>,
// collapses avatars into a "+N" pill as its
// width shrinks
{
collapse: "shrink",
minWidth: getUserListMinWidth(
appState.collaborators,
),
},
),
]
: []),
...(renderTopRightUI
? [
editorItem(
"host-top-right",
10,
<div className="exc-region-top-right-host-slot">
{renderTopRightUI(
editorInterface.formFactor === "phone",
appState,
)}
</div>,
),
]
: []),
...(!appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector" &&
// hide button when sidebar docked
(!isSidebarDocked ||
appState.openSidebar?.name !== DEFAULT_SIDEBAR.name)
? [
editorItem(
"sidebar-trigger",
100,
<tunnels.DefaultSidebarTriggerTunnel.Out />,
),
]
: []),
]}
/>
</div>
<div className="exc-region exc-region-center-right">
<RegionCluster
area="center-right"
budget="column"
editorItems={
shouldShowStats
? [
editorItem(
"stats",
0,
<Stats
app={app}
onClose={() => {
actionManager.executeAction(actionToggleStats);
}}
renderCustomStats={renderCustomStats}
/>,
// scrolls (down to this height) instead of
// collapsing
{
minHeight: 120,
className: "exc-region-item--self-scrolling",
},
),
]
: []
}
/>
</div>
</div>
</div>
<footer className="exc-region-bottom">
<div className="exc-region exc-region-bottom-left">
{shouldRenderMinimap && (
<Minimap
className={clsx("zen-mode-transition", {
"transition-bottom": appState.zenModeEnabled,
})}
/>
)}
<RegionCluster
area="bottom-left"
budget="band"
className="exc-region-row"
editorItems={
shouldRenderCanvasActions
? [
editorItem(
"canvas-actions",
0,
<Section heading="canvasActions">
{(zoomUIEnabled || minimapUIEnabled) &&
app.isNavigationEnabled() && (
<ZoomActions
actionManager={actionManager}
zoomUIEnabled={zoomUIEnabled}
minimapUIEnabled={minimapUIEnabled}
zenModeEnabled={appState.zenModeEnabled}
/>
)}
{defaultUIEnabled && !appState.viewModeEnabled && (
<UndoRedoActions
renderAction={actionManager.renderAction}
className={clsx("zen-mode-transition", {
"transition-bottom": appState.zenModeEnabled,
})}
/>
)}
</Section>,
),
]
: []
}
/>
</div>
<div className="exc-region-bottom-center">
<tunnels.FooterCenterTunnel.Out />
</div>
<div
className={clsx(
"layer-ui__wrapper__top-right zen-mode-transition",
"exc-region exc-region-bottom-right zen-mode-transition",
{
"transition-right": appState.zenModeEnabled,
"layer-ui__wrapper__top-right--compact": isCompactStylesPanel,
},
)}
>
{defaultUIEnabled && appState.collaborators.size > 0 && (
<UserList
collaborators={appState.collaborators}
userToFollow={appProps.userToFollow?.socketId || null}
currentUserControls={currentUserControls}
/>
)}
{renderTopRightUI?.(
editorInterface.formFactor === "phone",
appState,
)}
{!appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector" &&
// hide button when sidebar docked
(!isSidebarDocked ||
appState.openSidebar?.name !== DEFAULT_SIDEBAR.name) && (
<tunnels.DefaultSidebarTriggerTunnel.Out />
)}
{shouldShowStats && (
<Stats
app={app}
onClose={() => {
actionManager.executeAction(actionToggleStats);
}}
renderCustomStats={renderCustomStats}
/>
)}
<RegionCluster
area="bottom-right"
budget="band"
className="exc-region-row"
editorItems={
defaultUIEnabled || renderWelcomeScreen
? [
editorItem(
"help",
100,
<div style={{ position: "relative" }}>
{renderWelcomeScreen && (
<tunnels.WelcomeScreenHelpHintTunnel.Out />
)}
{defaultUIEnabled && (
<HelpButton
onClick={() =>
actionManager.executeAction(actionShortcuts)
}
/>
)}
</div>,
),
]
: []
}
/>
</div>
</div>
</FixedSideContainer>
</footer>
{(appState.toast ||
(scrollBackToContentUIEnabled && appState.scrolledOutside) ||
appProps.viewportStatusFrame?.label) && (
<FloatingStatusStack>
{appState.toast && (
<Toast
message={appState.toast.message}
onClose={() => setAppState({ toast: null })}
duration={appState.toast.duration}
closable={appState.toast.closable}
action={appState.toast.action}
timerKey={appState.toast}
/>
)}
{!appState.toast &&
scrollBackToContentUIEnabled &&
appState.scrolledOutside && (
<button
type="button"
className="scroll-back-to-content"
onClick={() => {
setAppState((appState) => ({
...getScrollToContentState(elements, appState),
}));
}}
>
{t("buttons.scrollBackToContent")}
</button>
)}
{appProps.viewportStatusFrame?.label && (
<ViewportStatusBadge
label={appProps.viewportStatusFrame.label}
border={appProps.viewportStatusFrame.border}
/>
)}
</FloatingStatusStack>
)}
{/* pinned to the UI area rather than docked into a region, so that it
doesn't fade out with the bottom-right region in zen mode */}
{defaultUIEnabled && (
<ExitZenModeButton
actionManager={actionManager}
showExitZenModeBtn={showExitZenModeBtn}
/>
)}
</div>
);
};
@@ -663,69 +952,33 @@ const LayerUI = ({
? {
// flush against the sidebar's own visible edge, not
// just the --right-sidebar-width column it reserves
// (which includes the sidebar's own outer margin)
right: `calc(var(--right-sidebar-width) - var(--space-factor) * 2)`,
// (which includes the sidebar's own outer margin).
// Logical: the sidebar docks on the left in RTL.
insetInlineEnd: `calc(var(--right-sidebar-width) - var(--space-factor) * 2)`,
}
: undefined
}
/>
)}
<div
className="layer-ui__wrapper"
className={clsx("layer-ui__wrapper", {
"layer-ui__wrapper--sidebar-docked": isSidebarDockedAndFits,
})}
style={
isSidebarDockedAndFits
? { width: `calc(100% - var(--right-sidebar-width))` }
? {
// flush against the sidebar's visible edge (like the
// canvas underneath), not the --right-sidebar-width
// column it reserves — the 8px difference is the
// sidebar's own outer margin, which would otherwise be
// a dead gap between the UI area and the sidebar
width: `calc(100% - (var(--right-sidebar-width) - var(--space-factor) * 2))`,
}
: {}
}
>
{renderWelcomeScreen && <tunnels.WelcomeScreenCenterTunnel.Out />}
{renderFixedSideContainer()}
<Footer
appState={appState}
actionManager={actionManager}
showExitZenModeBtn={showExitZenModeBtn}
renderWelcomeScreen={renderWelcomeScreen}
defaultUIEnabled={defaultUIEnabled}
zoomUIEnabled={zoomUIEnabled}
minimapUIEnabled={minimapUIEnabled}
/>
{(appState.toast ||
(scrollBackToContentUIEnabled && appState.scrolledOutside) ||
appProps.viewportStatusFrame?.label) && (
<div className="floating-status-stack">
{appState.toast && (
<Toast
message={appState.toast.message}
onClose={() => setAppState({ toast: null })}
duration={appState.toast.duration}
closable={appState.toast.closable}
action={appState.toast.action}
timerKey={appState.toast}
/>
)}
{!appState.toast &&
scrollBackToContentUIEnabled &&
appState.scrolledOutside && (
<button
type="button"
className="scroll-back-to-content"
onClick={() => {
setAppState((appState) => ({
...getScrollToContentState(elements, appState),
}));
}}
>
{t("buttons.scrollBackToContent")}
</button>
)}
{appProps.viewportStatusFrame?.label && (
<ViewportStatusBadge
label={appProps.viewportStatusFrame.label}
border={appProps.viewportStatusFrame.border}
/>
)}
</div>
)}
{renderUIRegions()}
</div>
{renderSidebars()}
</>
@@ -1,4 +1,9 @@
.excalidraw {
// (the styles panel's region stops above height + gap, see
// `.exc-regions--minimap` in styles.scss)
--minimap-height: 140px;
--minimap-gap: 12px;
.minimap {
--minimap-element-color: var(--color-gray-40);
// (drawn translucent, unless the viewport is small)
@@ -6,13 +11,12 @@
// floats above the canvas actions (zoom, undo/redo), without affecting
// the footer layout
// (height + gap are accounted for in MINIMAP_RESERVED_HEIGHT)
position: absolute;
bottom: calc(100% + 12px);
bottom: calc(100% + var(--minimap-gap));
inset-inline-start: 0;
box-sizing: border-box;
width: 200px;
height: 140px;
height: var(--minimap-height);
overflow: hidden;
background-color: var(--island-bg-color);
@@ -6,13 +6,6 @@ import { useApp } from "../App.context";
import "./Minimap.scss";
/**
* The vertical space (px) the UI above the minimap gives up for it: its
* height + the gap below it (see Minimap.scss), less a part of the clearance
* that UI keeps from the footer anyway — the minimap can sit closer to it.
*/
export const MINIMAP_RESERVED_HEIGHT = 138;
/**
* The minimap isn't available in editors shorter than this (px): it shares
* the left edge with the styles panel, which would be left with no room.
+27 -18
View File
@@ -8,6 +8,7 @@ import { getScrollToContentState } from "../scene";
import { SCROLLBAR_WIDTH, SCROLLBAR_MARGIN } from "../scene/scrollbars";
import { ExitViewModeButton, MobileShapeActions } from "./Actions";
import { RegionPhoneItems } from "./regions/RegionItems";
import { MobileToolbar } from "./MobileToolbar";
import { FixedSideContainer } from "./FixedSideContainer";
@@ -68,23 +69,28 @@ export const MobileMenu = ({
return null;
}
// host UI renders alongside the editor's own controls, same as on desktop
const topRightUI = (
<div className="excalidraw-ui-top-right">
{renderTopRightUI?.(true, appState) ??
(!appState.viewModeEnabled && (
<>
{defaultUIEnabled && (
<PenModeButton
checked={appState.penMode}
onChange={() => onPenModeToggle(null)}
title={t("toolBar.penMode")}
isMobile
penDetected={appState.penDetected}
/>
)}
<DefaultSidebarTriggerTunnel.Out />
</>
))}
<div className="exc-region-top-right-content">
<div className="exc-region-top-right-host-slot">
{renderTopRightUI?.(true, appState)}
</div>
{/* host `<Region.Item>`s — expanded, no collapsing on phones */}
<RegionPhoneItems area="top-right" />
{!appState.viewModeEnabled && (
<>
{defaultUIEnabled && (
<PenModeButton
checked={appState.penMode}
onChange={() => onPenModeToggle(null)}
title={t("toolBar.penMode")}
isMobile
penDetected={appState.penDetected}
/>
)}
<DefaultSidebarTriggerTunnel.Out />
</>
)}
{defaultUIEnabled &&
appState.viewModeEnabled &&
app.isInteractionEnabled() && (
@@ -94,9 +100,12 @@ export const MobileMenu = ({
);
const topLeftUI = (
<div className="excalidraw-ui-top-left">
{renderTopLeftUI?.(true, appState)}
<div className="exc-region-top-left-content">
<div className="exc-region-top-left-host-slot">
{renderTopLeftUI?.(true, appState)}
</div>
<MainMenuTunnel.Out />
<RegionPhoneItems area="top-left" />
</div>
);
@@ -1,14 +1,18 @@
.exc-stats {
width: 204px;
position: absolute;
top: 60px;
font-size: 12px;
z-index: var(--zIndex-layerUI);
pointer-events: var(--ui-pointerEvents);
:root[dir="rtl"] & {
left: 12px;
right: initial;
// bounded by its region (down to the footer band), scrolling past it
display: flex;
flex-direction: column;
max-height: 100%;
min-height: 0;
& > .Island {
min-height: 0;
overflow-y: auto;
}
h2 {
@@ -4,6 +4,8 @@
$closeButtonPadding: 0.4rem;
animation: Toast-fade-in 0.5s;
// containing block for the close button
position: relative;
min-width: 220px;
max-width: min(360px, calc(100vw - 32px));
border-radius: var(--border-radius-lg);
+3 -1
View File
@@ -50,6 +50,8 @@
margin-top: 0.375rem;
right: 0;
min-width: 11.875rem;
z-index: 1;
// above the region panels it can drop over (stats, styles panel) — the
// popper wrapper copies this z-index
z-index: var(--zIndex-ui-top);
}
}
+65 -14
View File
@@ -3,7 +3,9 @@ import { useState } from "react";
import { KEYS } from "@excalidraw/common";
import { trackEvent } from "../analytics";
import { useTunnels } from "../context/tunnels";
import { TOOLBAR_FOLD_ORDER } from "../hooks/useToolbarFolding";
import { t } from "../i18n";
import { useEditorInterface, useStylesPanelMode } from "./App.context";
@@ -32,6 +34,7 @@ import {
EraserToolButton,
FreedrawToolPopover,
FreedrawToolButton,
getToolLetter,
getToolShortcut,
HandToolButton,
LassoToolButton,
@@ -41,9 +44,12 @@ import {
SelectionToolPopover,
StickyNoteToolButton,
TextToolButton,
TOOLS,
} from "./Tools";
import { isToolButtonDisabled } from "./toolButtons";
import type { FoldableToolType } from "../hooks/useToolbarFolding";
import type {
AppClassProperties,
AppProps,
@@ -56,11 +62,14 @@ const ExtraToolsDropdown = ({
activeTool,
setAppState,
UIOptions,
foldedTools,
}: {
app: AppClassProperties;
activeTool: UIAppState["activeTool"];
setAppState: React.Component<any, AppState>["setState"];
UIOptions: AppProps["UIOptions"];
/** toolbar tools that didn't fit the toolbar, in toolbar order */
foldedTools: readonly FoldableToolType[];
}) => {
const [isExtraToolsMenuOpen, setIsExtraToolsMenuOpen] = useState(false);
const isFullStylesPanel = useStylesPanelMode() === "full";
@@ -76,12 +85,16 @@ const ExtraToolsDropdown = ({
activeTool.type === "lasso" &&
app.state.preferredSelectionTool.type !== "lasso";
const embeddableToolSelected = activeTool.type === "embeddable";
const foldedToolSelected = foldedTools.find(
(type) => activeTool.type === type,
);
return (
<DropdownMenu open={isExtraToolsMenuOpen}>
<DropdownMenu.Trigger
className={clsx("App-toolbar__extra-tools-trigger", {
"App-toolbar__extra-tools-trigger--selected":
!!foldedToolSelected ||
imageToolSelected ||
frameToolSelected ||
embeddableToolSelected ||
@@ -99,7 +112,9 @@ const ExtraToolsDropdown = ({
}}
title={t("toolBar.extraTools")}
>
{imageToolSelected
{foldedToolSelected
? TOOLS[foldedToolSelected].icon
: imageToolSelected
? ImageIcon
: frameToolSelected
? frameToolIcon
@@ -120,6 +135,25 @@ const ExtraToolsDropdown = ({
onSelect={() => setIsExtraToolsMenuOpen(false)}
className="App-toolbar__extra-tools-dropdown"
>
{foldedTools.map((type) => (
<DropdownMenu.Item
key={type}
onSelect={() => {
if (app.state.activeTool.type !== type) {
trackEvent("toolbar", type, "ui");
app.setActiveTool({ type });
}
}}
icon={<>{TOOLS[type].icon}</>}
shortcut={getToolLetter(type) || TOOLS[type].numericKey}
data-testid={`toolbar-${type}`}
selected={activeTool.type === type}
disabled={isToolButtonDisabled(app, type)}
>
{t(`toolBar.${type}`)}
</DropdownMenu.Item>
))}
{foldedTools.length > 0 && <DropdownMenu.Separator />}
{UIOptions.tools?.image !== false && (
<DropdownMenu.Item
onSelect={() => app.setActiveTool({ type: "image" })}
@@ -228,6 +262,7 @@ export const Toolbar = ({
onPenModeToggle,
onLockToggle,
heading,
foldedCount = 0,
}: {
app: AppClassProperties;
appState: UIAppState;
@@ -236,6 +271,11 @@ export const Toolbar = ({
onPenModeToggle: AppClassProperties["togglePenMode"];
onLockToggle: () => void;
heading: React.ReactNode;
/**
* how many tools (in `TOOLBAR_FOLD_ORDER`) didn't fit the toolbar's column
* and render in the extra-tools dropdown instead (see `useToolbarFolding`)
*/
foldedCount?: number;
}) => {
const editorInterface = useEditorInterface();
const isCompactStylesPanel = useStylesPanelMode() === "compact";
@@ -243,6 +283,15 @@ export const Toolbar = ({
const activeTool = appState.activeTool;
const toolProps = { app, activeTool };
const folded = new Set<FoldableToolType>(
TOOLBAR_FOLD_ORDER.slice(0, foldedCount),
);
// in toolbar order
const foldedTools = [...TOOLBAR_FOLD_ORDER]
.reverse()
.filter((type) => folded.has(type));
const shows = (type: FoldableToolType) => !folded.has(type);
return (
<Island
padding={1}
@@ -295,19 +344,20 @@ export const Toolbar = ({
) : (
<SelectionToolButton {...toolProps} />
)}
<RectangleToolButton {...toolProps} />
<DiamondToolButton {...toolProps} />
<EllipseToolButton {...toolProps} />
<ArrowToolButton {...toolProps} />
<LineToolButton {...toolProps} />
{isCompactStylesPanel ? (
<FreedrawToolPopover {...toolProps} />
) : (
<FreedrawToolButton {...toolProps} />
)}
<TextToolButton {...toolProps} />
<StickyNoteToolButton {...toolProps} />
<EraserToolButton {...toolProps} />
{shows("rectangle") && <RectangleToolButton {...toolProps} />}
{shows("diamond") && <DiamondToolButton {...toolProps} />}
{shows("ellipse") && <EllipseToolButton {...toolProps} />}
{shows("arrow") && <ArrowToolButton {...toolProps} />}
{shows("line") && <LineToolButton {...toolProps} />}
{shows("freedraw") &&
(isCompactStylesPanel ? (
<FreedrawToolPopover {...toolProps} />
) : (
<FreedrawToolButton {...toolProps} />
))}
{shows("text") && <TextToolButton {...toolProps} />}
{shows("stickynote") && <StickyNoteToolButton {...toolProps} />}
{shows("eraser") && <EraserToolButton {...toolProps} />}
<div
className="App-toolbar__divider"
@@ -319,6 +369,7 @@ export const Toolbar = ({
activeTool={activeTool}
setAppState={setAppState}
UIOptions={UIOptions}
foldedTools={foldedTools}
/>
</Stack.Row>
</Island>
@@ -20,6 +20,10 @@
.UserList__wrapper {
display: flex;
width: 100%;
// as tall as the buttons it shares a row with — the list's padding makes
// it taller than them on smaller screens (it overflows, centered), and
// the row would grow, nudging the buttons, when the list appears
height: var(--lg-button-size);
justify-content: flex-end;
align-items: center;
pointer-events: none !important;
+27 -4
View File
@@ -1,6 +1,7 @@
import { Popover } from "radix-ui";
import clsx from "clsx";
import React, { useLayoutEffect } from "react";
import { flushSync } from "react-dom";
import { isShallowEqual } from "@excalidraw/common";
@@ -35,6 +36,23 @@ const AVATAR_SLOT_WIDTH = 38;
// from ever being the item that tips the row over and wraps onto its own
// line (chevron 15px + pill's right padding 4px + pill's border 2px)
const PILL_EXTRA_WIDTH = 21;
// a single avatar (28px) + the list's padding (2 × 4px)
const SINGLE_AVATAR_WIDTH = 36;
/**
* The narrowest the list renders at: a single avatar — the current user's
* pill, if they're in the list (it's always shown).
*/
export const getUserListMinWidth = (
collaborators: ReadonlyMap<SocketId, Collaborator>,
) => {
for (const collaborator of collaborators.values()) {
if (collaborator.isCurrentUser && collaborator.username?.trim()) {
return SINGLE_AVATAR_WIDTH + PILL_EXTRA_WIDTH;
}
}
return SINGLE_AVATAR_WIDTH;
};
const ConditionalTooltipWrapper = ({
shouldWrap,
@@ -166,10 +184,15 @@ export const UserList = React.memo(
}
const resizeObserver = new ownerWindow.ResizeObserver((entries) => {
for (const entry of entries) {
const { width } = entry.contentRect;
updateWrapperWidth(width);
}
// rendered right away (the observer runs before the frame is
// painted) — otherwise the list is painted with the avatars that
// fit its previous width, for a frame
flushSync(() => {
for (const entry of entries) {
const { width } = entry.contentRect;
updateWrapperWidth(width);
}
});
});
resizeObserver.observe(userListWrapper.current);
@@ -1,109 +0,0 @@
import clsx from "clsx";
import { actionShortcuts } from "../../actions";
import { useTunnels } from "../../context/tunnels";
import { ExitZenModeButton, UndoRedoActions, ZoomActions } from "../Actions";
import { useApp } from "../App.context";
import { HelpButton } from "../HelpButton";
import { Minimap } from "../Minimap/Minimap";
import { Section } from "../Section";
import Stack from "../Stack";
import type { ActionManager } from "../../actions/manager";
import type { UIAppState } from "../../types";
const Footer = ({
appState,
actionManager,
showExitZenModeBtn,
renderWelcomeScreen,
defaultUIEnabled,
zoomUIEnabled,
minimapUIEnabled,
}: {
appState: UIAppState;
actionManager: ActionManager;
showExitZenModeBtn: boolean;
renderWelcomeScreen: boolean;
defaultUIEnabled: boolean;
zoomUIEnabled: boolean;
/** whether the minimap (when toggled on) and its toggle are rendered */
minimapUIEnabled: boolean;
}) => {
const { FooterCenterTunnel, WelcomeScreenHelpHintTunnel } = useTunnels();
const app = useApp();
return (
<footer
role="contentinfo"
className="layer-ui__wrapper__footer App-menu App-menu_bottom"
>
{/* footer-left is not faded out in zen mode: it holds the zoom controls,
which stay visible (chrome-less). Its children opt in individually. */}
{(defaultUIEnabled || (zoomUIEnabled && app.isNavigationEnabled())) && (
<div className="layer-ui__wrapper__footer-left zen-mode-transition">
{minimapUIEnabled && appState.minimapEnabled && (
<Minimap
className={clsx("zen-mode-transition", {
"layer-ui__wrapper__footer-left--transition-bottom":
appState.zenModeEnabled,
})}
/>
)}
<Stack.Col gap={2}>
<Section heading="canvasActions">
{(zoomUIEnabled || minimapUIEnabled) &&
app.isNavigationEnabled() && (
<ZoomActions
actionManager={actionManager}
zoomUIEnabled={zoomUIEnabled}
minimapUIEnabled={minimapUIEnabled}
zenModeEnabled={appState.zenModeEnabled}
/>
)}
{defaultUIEnabled && !appState.viewModeEnabled && (
<UndoRedoActions
renderAction={actionManager.renderAction}
className={clsx("zen-mode-transition", {
"layer-ui__wrapper__footer-left--transition-bottom":
appState.zenModeEnabled,
})}
/>
)}
</Section>
</Stack.Col>
</div>
)}
<FooterCenterTunnel.Out />
{(defaultUIEnabled || renderWelcomeScreen) && (
<div
className={clsx(
"layer-ui__wrapper__footer-right zen-mode-transition",
{
"transition-right": appState.zenModeEnabled,
},
)}
>
<div style={{ position: "relative" }}>
{renderWelcomeScreen && <WelcomeScreenHelpHintTunnel.Out />}
{defaultUIEnabled && (
<HelpButton
onClick={() => actionManager.executeAction(actionShortcuts)}
/>
)}
</div>
</div>
)}
{defaultUIEnabled && (
<ExitZenModeButton
actionManager={actionManager}
showExitZenModeBtn={showExitZenModeBtn}
/>
)}
</footer>
);
};
export default Footer;
Footer.displayName = "Footer";
@@ -1,8 +1,12 @@
// Host-supplied footer content owns the flexible space between the editor's
// left and right footer controls. Hosts can position their content at either
// edge (or both) with flex alignment and auto margins.
.footer-center {
pointer-events: none;
display: flex;
width: 100%;
align-items: center;
justify-content: flex-start;
margin-inline-end: 0.6rem;
@@ -12,8 +12,7 @@ const FooterCenter = ({ children }: { children?: React.ReactNode }) => {
<FooterCenterTunnel.In>
<div
className={clsx("footer-center zen-mode-transition", {
"layer-ui__wrapper__footer-left--transition-bottom":
appState.zenModeEnabled,
"transition-bottom": appState.zenModeEnabled,
})}
>
{children}
@@ -13,17 +13,25 @@ const LiveCollaborationTrigger = ({
isCollaborating,
onSelect,
editorInterface,
iconOnly,
...rest
}: {
isCollaborating: boolean;
onSelect: () => void;
editorInterface?: EditorInterface;
/**
* force the icon-only (`true`) or labeled (`false`) variant, e.g. from a
* `<Region.Item collapse="render">`; by default it's derived from the
* form factor and editor width
*/
iconOnly?: boolean;
} & React.ButtonHTMLAttributes<HTMLButtonElement>) => {
const appState = useUIAppState();
const showIconOnly =
editorInterface?.formFactor !== "desktop" ||
appState.width < MQ_MIN_WIDTH_DESKTOP;
iconOnly ??
(editorInterface?.formFactor !== "desktop" ||
appState.width < MQ_MIN_WIDTH_DESKTOP);
return (
<Button
@@ -0,0 +1,131 @@
import React, { useEffect, useLayoutEffect, useRef } from "react";
/** clearance between the stack and the footer controls beside/below it */
const GAP_PX = 8;
const INSET_VAR = "--exc-status-inset";
const BOTTOM_VAR = "--exc-status-bottom";
/**
* The desktop toast / scroll-back-to-content / viewport-status stack.
*
* It's centered on the canvas and overlays the footer band, between the
* footer's left and right controls. Those vary in width (region items), so
* it's inset symmetrically by the wider of the two — staying centered — and
* when the space between them is narrower than the stack's content, it
* moves up above the footer band instead (full width). In the band, its
* bottom entry lines up with the footer controls.
*
* Both are decided from the footer rows' widths and the stack's content
* width, neither of which depends on where the stack is.
*/
export const FloatingStatusStack = ({
children,
}: {
children: React.ReactNode;
}) => {
const stackRef = useRef<HTMLDivElement>(null);
const measureRef = useRef<() => void>(() => {});
measureRef.current = () => {
const stack = stackRef.current;
const regions = stack?.closest<HTMLElement>(".exc-regions");
if (!stack || !regions) {
return;
}
const box = regions.getBoundingClientRect();
if (!box.width) {
return;
}
const leftRow = regions.querySelector(".exc-region-bottom-left > *");
const rightRow = regions.querySelector(".exc-region-bottom-right > *");
const band = regions.querySelector(".exc-region-bottom");
const leftEdge = leftRow
? leftRow.getBoundingClientRect().right - box.left
: 0;
const rightEdge = rightRow
? box.right - rightRow.getBoundingClientRect().left
: 0;
const inset = Math.ceil(Math.max(leftEdge, rightEdge, 0) + GAP_PX);
// natural widths (the scroll-back button doesn't wrap, the toast has
// its own width bounds)
const needed = Math.max(
0,
...[...stack.children].map((child) =>
Math.max(child.scrollWidth, child.getBoundingClientRect().width),
),
);
if (!band) {
stack.style.setProperty(INSET_VAR, `${inset}px`);
stack.style.removeProperty(BOTTOM_VAR);
return;
}
const bandBox = band.getBoundingClientRect();
if (box.width - 2 * inset >= needed) {
// in the footer band: the bottom-most entry is centered on the band
// like the footer controls (bottoms aligned if it's taller), so it
// has the same distance from the editor edge as they do
const last = stack.lastElementChild;
const lastHeight = last ? last.getBoundingClientRect().height : 0;
stack.style.setProperty(INSET_VAR, `${inset}px`);
stack.style.setProperty(
BOTTOM_VAR,
`${Math.round(
box.bottom -
bandBox.bottom +
Math.max(0, (bandBox.height - lastHeight) / 2),
)}px`,
);
} else {
stack.style.setProperty(INSET_VAR, "0px");
stack.style.setProperty(
BOTTOM_VAR,
`${Math.ceil(box.bottom - bandBox.top + GAP_PX)}px`,
);
}
};
useLayoutEffect(() => {
measureRef.current();
});
useEffect(() => {
const stack = stackRef.current;
const regions = stack?.closest<HTMLElement>(".exc-regions");
const ResizeObserver = stack?.ownerDocument.defaultView?.ResizeObserver;
if (!stack || !regions || !ResizeObserver) {
return;
}
let frame = 0;
const observer = new ResizeObserver(() => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => measureRef.current());
});
observer.observe(regions);
observer.observe(stack);
for (const selector of [
".exc-region-bottom",
".exc-region-bottom-left > *",
".exc-region-bottom-right > *",
]) {
const element = regions.querySelector(selector);
if (element) {
observer.observe(element);
}
}
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
};
}, []);
return (
<div className="floating-status-stack" ref={stackRef}>
{children}
</div>
);
};
@@ -0,0 +1,99 @@
@use "../../css/variables.module" as *;
.excalidraw {
// Region items. The wrapper itself is click-through (in a stretched row or
// grid cell it may be wider than its content); its content opts back in.
// Doubled class: must beat the regions' `.exc-region-* > *` opt-in.
.exc-region-item.exc-region-item {
display: flex;
align-items: center;
flex: 0 0 auto;
pointer-events: none;
& > * {
pointer-events: var(--ui-pointerEvents);
}
}
// takes the leftover width of its row, down to its declared minimum, and
// lets its content fill it (e.g. the collaborator list measures its own
// width to pick how many avatars fit)
.exc-region-item--shrink.exc-region-item--shrink {
flex: 1 1 0;
min-width: var(--exc-region-item-min-width, 0);
& > * {
flex: 1 1 0;
min-width: 0;
}
}
// bottom regions: a row of items
.exc-region-row {
display: flex;
align-items: center;
gap: 0.5rem;
pointer-events: none;
}
// center regions: the stack is box-less, so its items are rows of the
// region's grid — the grid shares the region's height between them, down
// to each item's minimum
.exc-region-stack {
display: contents;
}
.exc-region-center-left > .exc-region-stack > * {
justify-self: start;
}
.exc-region-center-right > .exc-region-stack > * {
justify-self: end;
}
.exc-region-item--vertical.exc-region-item--vertical {
flex-direction: column;
align-items: stretch;
max-height: 100%;
}
// scrolls down to its `minHeight` (the grid shrinks it that far)
.exc-region-item--scrolls.exc-region-item--scrolls {
min-height: var(--exc-region-item-min-height);
overflow-y: auto;
& > * {
min-height: 0;
}
}
// content that bounds itself and scrolls on its own (the styles and stats
// panels): the item mustn't be a scroll container too, or it would clip
// the panel's shadow
.exc-region-item--self-scrolling.exc-region-item--self-scrolling {
overflow: visible;
}
// legacy `renderTopLeftUI` / `renderTopRightUI` slots that rendered nothing
.exc-region-item:has(> .exc-region-top-left-host-slot:empty, > .exc-region-top-right-host-slot:empty) {
display: none;
}
// Set by RegionCluster once it has measured the region's items: the
// region's own content no longer sizes its column (`contain`), the fully
// collapsed row does (`min-width`). See RegionCluster.
.exc-region[data-exc-region-floored] {
contain: inline-size;
min-width: var(--exc-region-floor);
}
// The floor counts `shrink` items at their `minWidth`, so the region's
// content must be able to get that narrow too. Its grid track would
// otherwise size to the content's min-content — a `shrink` item's current
// rendering (e.g. a `nowrap` scene name at full length, or however many
// avatars the collaborator list rendered last) — and the cluster would
// overflow the region, under the toolbar, instead of shrinking.
.exc-region[data-exc-region-floored] > * {
min-width: 0;
}
}
@@ -0,0 +1,122 @@
import React, { useContext, useId, useLayoutEffect, useRef } from "react";
import { isDevEnv } from "@excalidraw/common";
import { useTunnels } from "../../context/tunnels";
import type {
RegionArea,
RegionItemCollapse,
RegionItemContent,
RegionItemMobile,
} from "./RegionRegistry";
const RegionAreaContext = React.createContext<RegionArea | null>(null);
/**
* Places host UI into one of the editor's layout regions. Render it as a
* child of `<Excalidraw>`, with `<Region.Item>` children:
*
* ```tsx
* <Excalidraw>
* <Region area="top-right">
* <Region.Item priority={10} collapse="render">
* {({ collapsed }) => (collapsed ? <ShareIcon /> : <ShareButton />)}
* </Region.Item>
* <Region.Item priority={1} collapse="hide">
* <PromoBanner />
* </Region.Item>
* </Region>
* </Excalidraw>
* ```
*
* See `RegionItemCollapse` for how items give up space.
*/
export const Region = ({
area,
children,
}: {
area: RegionArea;
children?: React.ReactNode;
}) => (
<RegionAreaContext.Provider value={area}>
{children}
</RegionAreaContext.Provider>
);
const RegionItem = ({
priority = 0,
collapse = "rigid",
order = 10,
minWidth = 0,
minHeight = 0,
mobile = "same",
className,
children,
}: {
/** lower priority gives up space first (default 0) */
priority?: number;
/** how the item gives up space (default "rigid") */
collapse?: RegionItemCollapse;
/** position within the region, ascending (default 10) */
order?: number;
/** `collapse="shrink"`: the width (px) the item never shrinks below */
minWidth?: number;
/**
* center regions: the height (px) the item scrolls down to before it
* collapses (default 0: doesn't scroll)
*/
minHeight?: number;
/** how the item shows in the phone layout (default "same") */
mobile?: RegionItemMobile;
className?: string;
children?: RegionItemContent;
}) => {
const area = useContext(RegionAreaContext);
const { regions } = useTunnels();
const id = useId();
const seqRef = useRef<number | null>(null);
if (seqRef.current === null) {
seqRef.current = regions.nextSeq();
}
if (isDevEnv()) {
if (!area) {
console.warn("<Region.Item> must be rendered inside <Region area>");
}
if (collapse === "render" && typeof children !== "function") {
console.warn(
'<Region.Item collapse="render"> expects a function child ({ collapsed }) => ReactNode',
);
}
}
// re-registers on every render, so the region always renders the latest
// children (like a tunnel)
useLayoutEffect(() => {
if (!area) {
return;
}
regions.set({
id,
area,
priority,
collapse,
order,
minWidth,
minHeight,
mobile,
className,
content: children,
seq: seqRef.current!,
});
});
useLayoutEffect(() => () => regions.delete(id), [regions, id]);
return null;
};
RegionItem.displayName = "Region.Item";
Region.Item = RegionItem;
Region.displayName = "Region";
@@ -0,0 +1,409 @@
import clsx from "clsx";
import React, {
useEffect,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { useTunnels } from "../../context/tunnels";
import { useEditorInterface } from "../App.context";
import { renderRegionItemContent, sortRegionItems } from "./RegionRegistry";
import "./Region.scss";
import type {
RegionArea,
RegionItemEntry,
RegionItemSpec,
} from "./RegionRegistry";
type ItemState = "expanded" | "collapsed" | "hidden";
/**
* What a region's items have to fit into:
*
* - `region` the region's own width (top regions — the region spans its
* column, whose width the top-row grid negotiates)
* - `band` half the footer band's width (bottom-left / bottom-right — a
* fixed per-side budget, so the two sides never trade width)
* - `column` the height left in the region's column below its top region
* (center regions)
*/
type Budget = "region" | "band" | "column";
/** sub-pixel slack, so rounding can't flip an item back and forth */
const TOLERANCE_PX = 0.5;
/**
* `hide` items only show while the row/stack has this much room to spare:
* they're optional, so they go before things get tight, not once they are.
*/
const HIDE_BUFFER_PX = 32;
const FLOOR_VAR = "--exc-region-floor";
const FLOORED_ATTR = "data-exc-region-floored";
/** the state an item collapses to, if it collapses at all */
const getCollapsedState = (item: RegionItemSpec): ItemState | null =>
item.collapse === "render"
? "collapsed"
: item.collapse === "hide"
? "hidden"
: null;
const useRegisteredItems = (area?: RegionArea): RegionItemEntry[] => {
const { regions } = useTunnels();
const entries = useSyncExternalStore(
regions.subscribe,
regions.getSnapshot,
regions.getSnapshot,
);
return area ? entries.filter((entry) => entry.area === area) : [...entries];
};
const ItemWrapper = ({
item,
state,
vertical,
}: {
item: RegionItemSpec;
state: ItemState;
vertical?: boolean;
}) => (
<div
className={clsx(
"exc-region-item",
`exc-region-item--${item.collapse}`,
{
"exc-region-item--collapsed": state === "collapsed",
"exc-region-item--vertical": vertical,
"exc-region-item--scrolls": vertical && item.minHeight > 0,
},
item.className,
)}
data-region-item={item.id}
style={
{
"--exc-region-item-min-width":
item.collapse === "shrink" ? `${item.minWidth}px` : undefined,
"--exc-region-item-min-height":
vertical && item.minHeight > 0 ? `${item.minHeight}px` : undefined,
} as React.CSSProperties
}
>
{renderRegionItemContent(item.content, {
collapsed: state === "collapsed",
})}
</div>
);
/**
* Phone top bar: a region's `mobile="same"` items, expanded, no collapsing.
*/
export const RegionPhoneItems = ({
area,
}: {
area: "top-left" | "top-right";
}) => {
const items = sortRegionItems(
useRegisteredItems(area).filter((item) => item.mobile === "same"),
);
return (
<>
{items.map((item) => (
<ItemWrapper key={item.id} item={item} state="expanded" />
))}
</>
);
};
/**
* Renders a region's items (editor + host `<Region.Item>`s, by `order`) and
* collapses them by priority to fit the region's budget — width for a row
* (top, bottom regions), height for a stack (center regions).
*
* Each item's expanded and collapsed sizes are measured and cached (a
* `render` item is rendered collapsed for one pre-paint pass to learn its
* collapsed size). Items then collapse (`render`) or hide (`hide`) — lowest
* priority first — until the row/stack fits the budget. An item with a
* `minHeight` (center regions) counts with that height: it scrolls down to
* it first.
*
* Top regions (`floor`): the region's minimum width — what floors its
* column against the toolbar — is set to the width of the FULLY collapsed
* row, so it doesn't depend on the current collapse state and collapsing
* can't feed back into the width it reacts to.
*
* Tablet-sized editors: every item is collapsed, whatever fits. There the
* editor's own UI is compact (e.g. a narrower toolbar), which would give
* items collapsed at a wider editor the room to expand again — they'd come
* and go as the editor is resized.
*
* Inert where layout isn't measurable (zero sizes, e.g. jsdom): everything
* renders expanded.
*/
export const RegionCluster = ({
area,
editorItems,
className,
budget,
floor = false,
}: {
area: RegionArea;
editorItems: RegionItemSpec[];
/** the row/stack element's class; for center regions, the stack is
* `display: contents`, so items are the region grid's own items */
className?: string;
budget: Budget;
floor?: boolean;
}) => {
const vertical = budget === "column";
const items = sortRegionItems([...editorItems, ...useRegisteredItems(area)]);
const [states, setStates] = useState<Record<string, ItemState>>({});
const containerRef = useRef<HTMLDivElement>(null);
const sizesRef = useRef(
new Map<string, { expanded?: number; collapsed?: number }>(),
);
const alwaysCollapsed = useEditorInterface().formFactor !== "desktop";
const renderedStates = alwaysCollapsed
? Object.fromEntries(
items.map((item) => [item.id, getCollapsedState(item) ?? "expanded"]),
)
: states;
const stateOf = (id: string): ItemState => renderedStates[id] ?? "expanded";
const latest = useRef({ items, states: renderedStates, alwaysCollapsed });
latest.current = { items, states: renderedStates, alwaysCollapsed };
/** what the items must fit into, or 0 if not measurable */
const getBudget = (region: HTMLElement) => {
if (budget === "region") {
return region.getBoundingClientRect().width;
}
if (budget === "band") {
const band = region.closest<HTMLElement>(".exc-region-bottom");
return band ? band.getBoundingClientRect().width / 2 : 0;
}
// the region's column: its top region, a gap, then this region
const column = region.parentElement;
const top = region.previousElementSibling;
if (!column || !top) {
return 0;
}
return (
column.getBoundingClientRect().height -
top.getBoundingClientRect().height -
(parseFloat(getComputedStyle(column).rowGap) || 0) -
(parseFloat(getComputedStyle(region).marginBottom) || 0)
);
};
const measureRef = useRef<() => void>(() => {});
measureRef.current = () => {
const container = containerRef.current;
const region = container?.closest<HTMLElement>(".exc-region");
if (!container || !region) {
return;
}
const { items, states, alwaysCollapsed } = latest.current;
const stateOf = (id: string): ItemState => states[id] ?? "expanded";
const sizes = sizesRef.current;
const sizeOf = (element: Element) => {
const rect = element.getBoundingClientRect();
return vertical ? rect.height : rect.width;
};
// items that take part in the row/stack layout (and thus get a gap),
// even when zero-sized (e.g. content that is absolutely positioned)
const displayed = new Set<string>();
for (const element of container.querySelectorAll<HTMLElement>(
":scope > [data-region-item]",
)) {
const id = element.dataset.regionItem!;
const cached = sizes.get(id) ?? {};
cached[stateOf(id) === "collapsed" ? "collapsed" : "expanded"] =
sizeOf(element);
sizes.set(id, cached);
if (element.getClientRects().length > 0) {
displayed.add(id);
}
}
const style = getComputedStyle(vertical ? region : container);
const gap = parseFloat(vertical ? style.rowGap : style.columnGap) || 0;
const sizeIn = (item: RegionItemSpec, state: ItemState) => {
if (state === "hidden") {
return 0;
}
const cached = sizes.get(item.id);
if (state === "collapsed") {
return cached?.collapsed ?? cached?.expanded ?? 0;
}
if (!vertical && item.collapse === "shrink") {
return item.minWidth;
}
if (vertical && item.minHeight > 0) {
return Math.min(item.minHeight, cached?.expanded ?? item.minHeight);
}
return cached?.expanded ?? 0;
};
const total = (next: Record<string, ItemState>) => {
let sum = 0;
let count = 0;
for (const item of items) {
const state = next[item.id] ?? "expanded";
const size = sizeIn(item, state);
if (size > 0 || (state !== "hidden" && displayed.has(item.id))) {
sum += size;
count++;
}
}
return sum + gap * Math.max(0, count - 1);
};
const collapsedState = (item: RegionItemSpec): ItemState =>
getCollapsedState(item) ?? "expanded";
const candidates = items
.filter((item) => getCollapsedState(item))
.sort((a, b) => a.priority - b.priority || b.seq - a.seq);
// The floor doesn't depend on the budget, so it's set before the budget
// check below. Otherwise a floor measured too small (e.g. 0px, before the
// items' tunneled content rendered) shrinks the region to it, the region
// then has no budget, and the floor is never measured again.
if (floor) {
const floorPx = `${Math.ceil(
total(
Object.fromEntries(
candidates.map((item) => [item.id, collapsedState(item)]),
),
),
)}px`;
if (region.style.getPropertyValue(FLOOR_VAR) !== floorPx) {
region.style.setProperty(FLOOR_VAR, floorPx);
}
region.setAttribute(FLOORED_ATTR, "");
}
const available = getBudget(region);
if (!(available > 0) || alwaysCollapsed) {
return;
}
// learn the collapsed size of `render` items before deciding anything
const unprobed = items.filter(
(item) =>
item.collapse === "render" &&
sizes.get(item.id)?.collapsed === undefined &&
stateOf(item.id) !== "collapsed",
);
if (unprobed.length) {
setStates((prev) => ({
...prev,
...Object.fromEntries(unprobed.map((item) => [item.id, "collapsed"])),
}));
return;
}
const next: Record<string, ItemState> = {};
for (const item of candidates) {
const buffer = candidates.some(
(candidate) => candidate.collapse === "hide" && !next[candidate.id],
)
? HIDE_BUFFER_PX
: 0;
if (total(next) + buffer <= available + TOLERANCE_PX) {
break;
}
next[item.id] = collapsedState(item);
}
const changed = items.some(
(item) => stateOf(item.id) !== (next[item.id] ?? "expanded"),
);
if (changed) {
setStates(next);
}
};
// after every render: measure what's rendered now (and probe/decide)
useLayoutEffect(() => {
measureRef.current();
});
// and whenever the budget or an item resizes
useEffect(() => {
const container = containerRef.current;
const region = container?.closest<HTMLElement>(".exc-region");
const ResizeObserver = container?.ownerDocument.defaultView?.ResizeObserver;
if (!container || !region || !ResizeObserver) {
return;
}
let frame = 0;
const observer = new ResizeObserver(() => {
cancelAnimationFrame(frame);
// deferred, so that reacting to a resize can't trip the
// ResizeObserver loop limit
frame = requestAnimationFrame(() => measureRef.current());
});
observer.observe(region);
const budgetElement =
budget === "band"
? region.closest(".exc-region-bottom")
: budget === "column"
? region.parentElement
: null;
if (budgetElement) {
observer.observe(budgetElement);
}
if (budget === "column" && region.previousElementSibling) {
observer.observe(region.previousElementSibling);
}
const observed = new Set<Element>();
const observeItems = () => {
for (const element of container.querySelectorAll(
":scope > [data-region-item]",
)) {
if (!observed.has(element)) {
observed.add(element);
observer.observe(element);
}
}
};
observeItems();
const mutations = new MutationObserver(observeItems);
mutations.observe(container, { childList: true });
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
mutations.disconnect();
if (floor) {
region.removeAttribute(FLOORED_ATTR);
region.style.removeProperty(FLOOR_VAR);
}
};
}, [budget, floor]);
return (
<div
className={clsx(className, { "exc-region-stack": vertical })}
ref={containerRef}
>
{items
.filter((item) => stateOf(item.id) !== "hidden")
.map((item) => (
<ItemWrapper
key={item.id}
item={item}
state={stateOf(item.id)}
vertical={vertical}
/>
))}
</div>
);
};
@@ -0,0 +1,130 @@
import type React from "react";
/**
* Regions a host can place UI into. `top-center` (the toolbar) and
* `bottom-center` (`<Footer>`) are not open to region items.
*/
export type RegionArea =
| "top-left"
| "top-right"
| "center-left"
| "center-right"
| "bottom-left"
| "bottom-right";
/**
* How a region item gives up space when its region runs out of it — width
* in the top and bottom regions, height in the center regions:
*
* - `rigid` keeps its natural size (the default)
* - `shrink` top/bottom: takes the region's leftover width, down to
* `minWidth` — the item adapts itself (e.g. the collaborator
* list's "+N" pill). Center: like `rigid`.
* - `render` has a collapsed variant: `children` is a function receiving
* `{ collapsed }`
* - `hide` isn't shown while it doesn't fit (with some room to spare)
*
* In the center regions, an item with a `minHeight` first scrolls down to
* that height before it (or a lower priority item) collapses.
*
* On tablet-sized editors (`formFactor: "tablet"`), `render` items are
* always collapsed and `hide` items hidden.
*/
export type RegionItemCollapse = "rigid" | "shrink" | "render" | "hide";
/**
* How an item shows in the phone layout, which only has a top bar:
*
* - `same` top-left / top-right items render in the top bar (default);
* items of the other areas aren't shown — the phone layout
* doesn't have those (render them e.g. in the main menu instead)
* - `hide` isn't shown on phones
*/
export type RegionItemMobile = "same" | "hide";
export type RegionItemRenderState = {
/** `collapse="render"` items: render the collapsed variant */
collapsed: boolean;
};
export type RegionItemContent =
| React.ReactNode
| ((state: RegionItemRenderState) => React.ReactNode);
export type RegionItemSpec = {
id: string;
/**
* Lower priority gives up space first. Ties: the item registered last
* gives up space first.
*/
priority: number;
collapse: RegionItemCollapse;
/**
* Position within the region, ascending. Editor items: top-left — host
* `renderTopLeftUI` -10, main menu 0; top-right — collaborator list 0,
* host `renderTopRightUI` 10, sidebar trigger 100; center-left — styles
* panel 0, pen mode button 1; center-right — stats 0; bottom-left —
* zoom/undo 0; bottom-right — help 100. Host items default to 10.
*/
order: number;
/** `collapse="shrink"` items: the width they never shrink below */
minWidth: number;
/**
* center regions: the item scrolls down to this height (px) before
* collapsing (0: it doesn't scroll)
*/
minHeight: number;
mobile: RegionItemMobile;
className?: string;
content: RegionItemContent;
/** registration order (tie-breaker) */
seq: number;
};
export type RegionItemEntry = RegionItemSpec & { area: RegionArea };
/**
* Per-editor store of host-registered region items (`<Region.Item>`), read
* by the region renderers in LayerUI / MobileMenu.
*/
export class RegionRegistry {
private entries = new Map<string, RegionItemEntry>();
private snapshot: readonly RegionItemEntry[] = [];
private listeners = new Set<() => void>();
private seq = 0;
nextSeq = () => this.seq++;
set = (entry: RegionItemEntry) => {
this.entries.set(entry.id, entry);
this.emit();
};
delete = (id: string) => {
if (this.entries.delete(id)) {
this.emit();
}
};
subscribe = (listener: () => void) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
getSnapshot = () => this.snapshot;
private emit() {
this.snapshot = [...this.entries.values()];
this.listeners.forEach((listener) => listener());
}
}
export const renderRegionItemContent = (
content: RegionItemContent,
state: RegionItemRenderState,
) => (typeof content === "function" ? content(state) : content);
export const sortRegionItems = <T extends RegionItemSpec>(items: T[]) =>
items.sort((a, b) => a.order - b.order || a.seq - b.seq);
+5
View File
@@ -2,6 +2,8 @@ import { createIsolation } from "jotai-scope";
import React from "react";
import tunnel from "tunnel-rat";
import { RegionRegistry } from "../components/regions/RegionRegistry";
export type Tunnel = ReturnType<typeof tunnel>;
type TunnelsContextValue = {
@@ -15,6 +17,8 @@ type TunnelsContextValue = {
DefaultSidebarTabTriggersTunnel: Tunnel;
OverwriteConfirmDialogTunnel: Tunnel;
TTDDialogTriggerTunnel: Tunnel;
/** host-registered `<Region.Item>`s */
regions: RegionRegistry;
// this can be removed once we create jotai stores per each editor
// instance
tunnelsJotai: ReturnType<typeof createIsolation>;
@@ -39,6 +43,7 @@ export const useInitializeTunnels = () => {
DefaultSidebarTabTriggersTunnel: tunnel(),
OverwriteConfirmDialogTunnel: tunnel(),
TTDDialogTriggerTunnel: tunnel(),
regions: new RegionRegistry(),
tunnelsJotai,
};
}, []);
+405 -132
View File
@@ -360,13 +360,55 @@ body.excalidraw-cursor-resize * {
}
}
.excalidraw-ui-top-left,
.excalidraw-ui-top-right {
// content clusters — the editor-owned rows of a region's content (menu
// trigger, user list, …), shared between the desktop regions and the
// mobile top bar
.exc-region-top-left-content,
.exc-region-top-right-content {
display: flex;
align-items: center;
gap: 0.5rem;
}
// host-app slots — wrap ONLY the host-rendered content
// (`renderTopLeftUI` / `renderTopRightUI` output), nested inside the
// clusters/regions alongside the editor-owned content.
//
// Slots are intentionally rigid (they keep their intrinsic width): the
// slot's min-content is what floors the side column of the mesh, which is
// what makes the toolbar move aside for host UI instead of covering it
// (see the mesh doc below).
.exc-region-top-left-host-slot,
.exc-region-top-right-host-slot {
display: flex;
align-items: center;
gap: 0.5rem;
// keep host controls at their intrinsic width so they participate in the
// top-row width negotiation instead of wrapping or reflowing
& > * {
flex: 0 0 auto;
}
// don't leave a stray flex/grid gap behind when the host renders nothing
&:empty {
display: none;
}
}
// The menu trigger keeps its intrinsic size (mobile top bar; on desktop
// the cluster's children are region items, see Region.scss).
.exc-region-top-left-content
> :not(.exc-region-top-left-host-slot, .exc-region-item) {
flex: 0 0 auto;
}
// The dropdown wrapper uses `display: contents`, so its children participate
// in the cluster's flex layout directly.
.exc-region-top-left-content > .dropdown-menu-event-wrapper > * {
flex: 0 0 auto;
}
.App-toolbar-content {
display: flex;
flex-direction: column;
@@ -390,125 +432,368 @@ body.excalidraw-cursor-resize * {
}
}
.App-menu {
// ---------------------------------------------------------------------------
// UI regions
//
// The editor UI is laid out in 3×3 logical regions (the middle of the
// canvas has none):
//
// .exc-region-top-left .exc-region-top-center .exc-region-top-right
// .exc-region-center-left .exc-region-center-right
// .exc-region-bottom-left .exc-region-bottom-center .exc-region-bottom-right
//
// `.exc-regions` is a two-row grid — `minmax(0, 1fr) auto` — of:
//
// .exc-region-columns the top + center regions, as three column stacks
// .exc-region-bottom the footer band (its own independent 3-column grid)
//
// The two are deliberately kept in SEPARATE grids:
// - vertically, the band reserves its own height in normal flow and the
// columns get exactly the rest (`minmax(0,1fr)`), so center regions end
// above the footer no matter how tall either side grows;
// - horizontally, they can't size each other's tracks — nothing in the
// footer can displace the toolbar, and an overflowing top row (regime 4
// below) can't drag the footer past the editor edge (the outer column
// is `minmax(0,1fr)`, so overflow of the columns doesn't widen it).
//
// THE COLUMNS (top + center regions)
// ----------------------------------
//
// .exc-region-column-left -center -right
// ┌─────────────┬───────────────────────┬─────────────┐
// │ TOP-LEFT │ TOP-CENTER │ TOP-RIGHT │
// ├─────────────┤ (toolbar) ├─────────────┤
// │ CENTER-LEFT │ │CENTER-RIGHT │
// │ (styles) │ │ (stats) │
// └─────────────┴───────────────────────┴─────────────┘
// minmax(auto,1fr) auto minmax(auto,1fr)
//
// Each column is a vertical flex stack, so a center region starts right
// below the top region of ITS OWN column, and nothing else: a taller
// TOP-LEFT (e.g. a scene title) moves the styles panel down, a taller
// TOP-RIGHT (e.g. a call tray) moves the stats down, and the toolbar's
// height moves neither.
//
// Column widths come from the top regions only: the center regions have
// `contain: inline-size`, so their content contributes nothing to their
// column's width. A styles panel wider than its column overflows toward
// the canvas instead of widening the column and offsetting the toolbar.
//
// The toolbar column is `minmax(<fully folded>, <unfolded>)` toolbar
// widths (see `useToolbarFolding`; both are constants, independent of how
// many tools are currently folded). The side columns floor at their top
// region's min-content, then split the leftover space EQUALLY (same `1fr`
// flex factor). Those floors are what make the top row NEGOTIATE width.
// As the editor narrows there are four regimes:
//
// 1. Plenty of space — both sides fit inside their equal share, so the
// toolbar is exactly viewport-centered even when TOP-LEFT and
// TOP-RIGHT differ in width (e.g. a bare menu button vs. a user
// list + share button cluster).
// 2. One side outgrows its share — that column pins to its content's
// min-content and the toolbar shifts aside, making exactly enough
// room (e.g. tablet portrait while collaborating: call button +
// share + collapsed user list).
// 3. Both sides are at their floors — the toolbar column shrinks below
// the unfolded toolbar, and the toolbar folds tools (from the end)
// into its extra-tools dropdown to fit.
// 4. Nothing fits even fully folded — the columns hold their floors and
// the row overflows to the right, clipped at the editor edge by
// `.excalidraw`'s `overflow: hidden`. Content never slides under its
// neighbors.
//
// The side floors come from the region items (`RegionCluster`): once it
// has measured them, a top region's minimum width is its FULLY collapsed
// row — every `render` item collapsed, every `hide` item hidden, `shrink`
// items at their `minWidth`, `rigid` items as they are.
// So within regime 1 a side that outgrows its share first collapses its
// own items (lowest priority first); only its fully collapsed row pushes
// the toolbar aside (regime 2). Until measured (or where layout can't be
// measured), a top region's content min-content is its floor.
//
// DO NOT set `min-width: 0` (or `overflow` other than `visible`) anywhere
// on a top region's content chain — before the floor is measured that
// content IS the floor, and a zero minimum lets the toolbar cover it.
//
// OTHER RULES
// ------------
// - Region boxes stretch across their column and overlap empty canvas.
// Content is pushed into a corner with `place-content`, and every
// region is `pointer-events: none`, with only its content opting back
// in via the `--ui-pointerEvents` value. Never set pointer events on a
// region directly — it would swallow clicks meant for the canvas.
// - Every region is `position: relative`, so absolutely positioned host
// content (e.g. a call tray hanging below the top-right UI) anchors to
// its own region rather than to the whole UI area.
// - New UI that may be wide belongs in a center region (or the footer
// band), not in a top region, else its width negotiates with the
// toolbar.
// ---------------------------------------------------------------------------
// the wrapper is flush with a docked sidebar's visible edge; keep the
// region content at the same visual clearance from the sidebar it had
// when the wrapper stopped at the reserved column instead (this also
// keeps the stack/toast center unchanged). Logical, because the sidebar
// docks on the left in RTL.
.layer-ui__wrapper--sidebar-docked .exc-regions {
inset-inline-end: calc(
var(--editor-container-padding) + var(--space-factor) * 2
);
}
.exc-regions {
position: absolute;
inset: var(--editor-container-padding);
padding-top: var(--sat, 0);
padding-right: var(--sar, 0);
padding-bottom: var(--sab, 0);
padding-left: var(--sal, 0);
display: grid;
// r1: the columns (top + center regions) · r2: the footer band. The band
// reserves its height in-flow; the columns get the rest and can't grow
// past it.
grid-template-rows: minmax(0, 1fr) auto;
// single shared column with a ZERO minimum, so columns whose top row
// overflows (regime 4 above) can't widen it — and thus can't drag the
// footer band past the editor edge
grid-template-columns: minmax(0, 1fr);
color: var(--icon-fill-color);
}
.shapes-section {
display: flex;
justify-content: center;
pointer-events: none !important;
& > * {
pointer-events: var(--ui-pointerEvents);
}
}
.App-menu_top {
grid-template-columns: 1fr 2fr 1fr;
grid-gap: 1rem;
align-items: flex-start;
cursor: default;
pointer-events: none !important;
& > * {
pointer-events: var(--ui-pointerEvents);
}
@media (min-width: 1536px) {
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 3rem;
}
pointer-events: none;
}
.App-menu_top > .App-menu_top__left {
grid-column: 1;
justify-self: start;
// App-menu_top__left is a single-column grid, so its track width is
// driven by the widest row — including the host-provided
// renderTopLeftUI content, which can be arbitrarily wide. Its
// (stretched) grid-item wrappers must stay pointer-events:none so that
// slack isn't a dead zone over the canvas; only the actual
// (content-sized, non-stretched) interactive pieces opt back in.
// Specificity (not source order) is why this beats `.App-menu_top > *`.
.exc-region-columns {
grid-row: 1;
display: grid;
// side columns: equal flex factors so the leftover space (after the
// toolbar column) splits evenly — that's what keeps the toolbar centered
// — with `auto` minimums so each side's top region FLOORS its column:
// the toolbar moves aside for it instead of covering it. The toolbar
// track is `minmax(<fully folded>, <unfolded>)` once `useToolbarFolding`
// has measured the toolbar (`auto` until then, or where it can't measure)
grid-template-columns: minmax(auto, 1fr) var(--exc-toolbar-track, auto) minmax(
auto,
1fr
);
// clearance between the toolbar and the side columns
column-gap: 1rem;
min-height: 0;
pointer-events: none;
.selected-shape-actions-container,
.ToolIcon__penMode {
@media (min-width: 1536px) {
column-gap: 3rem;
}
}
.exc-region-column-left,
.exc-region-column-center,
.exc-region-column-right {
display: flex;
flex-direction: column;
// gap between a top region and the center region below it
row-gap: var(--exc-regions-row-gap, 1rem);
min-height: 0;
pointer-events: none;
}
// NOTE: no `min-width: 0` here — a top region's min-content is the floor
// of its column, which is what keeps the toolbar from covering it (see the
// doc above).
.exc-region-top-left,
.exc-region-top-center,
.exc-region-top-right,
.exc-region-center-left,
.exc-region-center-right {
display: grid;
position: relative;
min-height: 0;
pointer-events: none;
& > * {
pointer-events: var(--ui-pointerEvents);
}
}
// .excalidraw-ui-top-left is itself `display: flex` (block-level), so
// it *also* stretches to fill this track's width — its own box needs
// the same none-then-opt-in treatment, one level deeper, so its real
// (content-sized, unstretched) children stay clickable without
// resizing/repositioning the row itself.
.excalidraw-ui-top-left {
.exc-region-bottom,
.exc-region-bottom-left,
.exc-region-bottom-center,
.exc-region-bottom-right {
display: grid;
min-height: 0;
pointer-events: none;
}
.exc-region-bottom-left,
.exc-region-bottom-center,
.exc-region-bottom-right {
position: relative;
}
.exc-region-bottom-left,
.exc-region-bottom-right {
& > * {
pointer-events: var(--ui-pointerEvents);
}
}
// `place-content` (not `place-items`) anchors the content inside the region,
// so that the region itself can stretch across its column
.exc-region-top-left,
.exc-region-top-center,
.exc-region-top-right {
flex: 0 0 auto;
}
.exc-region-top-left {
grid-auto-flow: column;
place-content: start start;
}
// The toolbar folds tools to fit this region's width (regime 3 above); in
// regime 4 it pushes the top-right UI past the editor edge.
.exc-region-top-center {
grid-auto-flow: column;
place-content: start center;
}
.exc-region-top-right {
// single flexible track with an `auto` minimum: the content cluster
// stretches to whatever width the column resolves to (so the
// collaborator list can use the leftover space), while the cluster's
// min-content still floors the column
grid-template-columns: minmax(auto, 1fr);
place-content: start end;
& > .exc-region-top-right-content {
justify-content: flex-end;
gap: 0.75rem;
// This row spans the region so a `shrink` item (the collaborator
// list) can take the remaining width, but must not turn the otherwise
// transparent region into a full-width click target. Its children are
// region items, which opt their content back in (Region.scss).
pointer-events: none;
}
> * {
pointer-events: var(--ui-pointerEvents);
}
&--compact > .exc-region-top-right-content {
gap: 0.5rem;
}
}
.App-menu_top > .shapes-section {
grid-column: 2;
// center regions hang below their column's top region, and may shrink (and
// scroll their panel) down to the footer band. `contain: inline-size`
// keeps their content out of the column-width negotiation (see the doc
// above).
.exc-region-center-left,
.exc-region-center-right {
flex: 0 1 auto;
contain: inline-size;
row-gap: var(--exc-regions-row-gap, 1rem);
margin-bottom: 1rem;
}
.selected-shape-actions-container {
width: fit-content;
&--compact {
min-width: 48px;
}
.exc-region-center-left {
place-content: start start;
}
.App-menu_top > .layer-ui__wrapper__top-right {
grid-column: 3;
justify-self: end;
// the minimap floats above the bottom-left canvas actions, in this
// column's way: the column's center region (the styles panel) stops above
// it
.exc-regions--minimap .exc-region-center-left {
margin-bottom: calc(1rem + var(--minimap-height) + var(--minimap-gap));
}
.App-menu_bottom {
position: absolute;
bottom: 1rem;
display: flex;
justify-content: space-between;
align-items: flex-start;
cursor: default;
pointer-events: none !important;
box-sizing: border-box;
padding: 0 1rem;
.exc-region-center-right {
place-content: start end;
}
&--transition-left {
section {
width: 185px;
}
}
// The bottom band is a sibling of the columns, so none of its occupants
// can size the columns and offset the toolbar — and an overflowing top row
// can't push the band past the editor edge. Its independent inner grid
// recreates the footer contract: natural-width editor controls on either
// side and a host slot that owns all remaining space between them.
.exc-region-bottom {
grid-row: 2;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
min-width: 0;
}
section {
.exc-region-bottom-left {
grid-column: 1;
grid-auto-flow: column;
place-content: end start;
// the canvas actions (zoom, undo/redo)
.exc-region-item > section {
display: flex;
}
}
.App-menu_bottom > *:first-child {
justify-self: flex-start;
.exc-region-bottom-center {
grid-column: 2;
align-items: end;
min-width: 0;
// `<Footer>` content can respond to its own width with
// `@container exc-footer (…)`. Its width is the band's flexible track,
// never its content, so the containment doesn't change its layout.
container: exc-footer / inline-size;
}
.App-menu_bottom > *:last-child {
justify-self: flex-end;
.exc-region-bottom-right {
grid-column: 3;
grid-auto-flow: column;
place-content: end end;
}
.App-menu_left {
grid-template-rows: 1fr auto 1fr;
height: 100%;
// Status UI stays tied to the canvas center instead of the center track of
// the inner footer grid, which shifts when the side controls have different
// widths. It deliberately overlays the bottom band.
.exc-regions > .floating-status-stack {
position: absolute;
// kept clear of the footer's left/right controls — symmetrically, so it
// stays centered — or, when they leave too little room, moved above the
// footer band (see FloatingStatusStack)
left: var(--exc-status-inset, 0px);
right: var(--exc-status-inset, 0px);
// centers the stack when its max-width (see the base rule) kicks in
margin-inline: auto;
// its bottom entry lines up with the footer controls (centered on the
// footer band), or it sits above the band (see FloatingStatusStack);
// until measured, at the band's bottom edge
bottom: var(--exc-status-bottom, var(--sab, 0px));
// measured at its natural width (see FloatingStatusStack)
& > .scroll-back-to-content {
white-space: nowrap;
// same height as the footer controls it lines up with
height: var(--lg-button-size);
padding-block: 0;
}
// the toast is click-through (only its close button is interactive)
& > .Toast {
pointer-events: none;
}
}
.App-menu_right {
grid-template-rows: 1fr;
height: 100%;
// the styles panel is bounded by its region, and scrolls past it (the
// `min-height: 0`s let the panel shrink below its content height)
.selected-shape-actions-container {
display: flex;
flex-direction: column;
width: fit-content;
max-height: 100%;
min-height: 0;
&--compact {
min-width: 48px;
}
& > section {
min-height: 0;
}
}
.App-menu__left {
@@ -516,7 +801,7 @@ body.excalidraw-cursor-resize * {
padding: 0.75rem;
max-width: 12.5rem;
box-sizing: border-box;
position: absolute;
min-height: 0;
}
.dropdown-select {
@@ -573,15 +858,8 @@ body.excalidraw-cursor-resize * {
border: 1px solid var(--default-border-color);
padding: 10px 20px;
position: absolute;
left: 50%;
bottom: 30px;
transform: translateX(-50%);
box-sizing: border-box;
max-width: calc(
100% - var(--viewport-status-frame-border-width) -
var(--viewport-status-frame-border-width)
);
max-width: 100%;
pointer-events: var(--ui-pointerEvents);
font-family: inherit;
@@ -594,40 +872,19 @@ body.excalidraw-cursor-resize * {
}
}
// always rendered as a flex column of [scroll-back-to-content, badge] —
// this positions the stack itself; children are centered/spaced via flex.
// always rendered as a flex column of [toast, scroll-back-to-content,
// badge] — children are centered/spaced via flex. The desktop stack is
// placed by `.exc-regions` above; mobile positioning is applied in the
// mobile block below.
.floating-status-stack {
position: absolute;
left: var(--viewport-status-frame-border-width);
right: var(--viewport-status-frame-border-width);
bottom: calc(0.5rem + var(--viewport-status-frame-border-width));
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
pointer-events: none;
.scroll-back-to-content {
position: static;
left: auto;
bottom: auto;
transform: none;
max-width: 100%;
pointer-events: var(--ui-pointerEvents);
}
}
// on mobile, when the default bottom toolbar renders, the stack is a
// normal (in-flow) row above MobileShapeActions/the toolbar Island inside
// .App-bottom-bar instead of being independently viewport-positioned —
// self-sizing regardless of whether MobileShapeActions is showing, with
// no magic-number height math needed to clear the toolbar.
.App-bottom-bar > .floating-status-stack {
position: static;
left: auto;
right: auto;
bottom: auto;
margin-bottom: 0.5rem;
// stay inside the viewport-status frame border when a follow-mode frame
// is shown
max-width: calc(100% - 2 * var(--viewport-status-frame-border-width));
}
.help-icon {
@@ -670,10 +927,33 @@ body.excalidraw-cursor-resize * {
display: none;
}
// the base rule is grid-placed by `.exc-regions` (desktop only) — the
// standalone mobile stack (view mode / no bottom bar) is positioned
// against the viewport instead, full-width so flex centers the children
.floating-status-stack {
position: absolute;
left: var(--viewport-status-frame-border-width);
right: var(--viewport-status-frame-border-width);
bottom: calc(30px + var(--sab, 0));
z-index: var(--zIndex-ui-bottom);
}
// …but when the default bottom toolbar renders, the stack is a normal
// (in-flow) row above MobileShapeActions/the toolbar Island inside
// .App-bottom-bar instead of being independently viewport-positioned —
// self-sizing regardless of whether MobileShapeActions is showing, with
// no magic-number height math needed to clear the toolbar.
.App-bottom-bar > .floating-status-stack {
position: static;
left: auto;
right: auto;
bottom: auto;
// (applies to a flex item even when static) the bar is already
// layered; within it, the stack must stay below the toolbar's
// "more tools" menu, which opens over it
z-index: auto;
margin-bottom: 0.5rem;
}
}
.rtl-mirror {
@@ -775,13 +1055,6 @@ body.excalidraw-cursor-resize * {
pointer-events: none !important;
}
&.excalidraw--view-mode {
.App-menu {
display: flex;
justify-content: space-between;
}
}
&.excalidraw--non-interactive {
user-select: none;
@@ -0,0 +1,26 @@
import { getToolbarFoldCount, TOOLBAR_FOLD_ORDER } from "./useToolbarFolding";
describe("getToolbarFoldCount", () => {
// unfolded toolbar: 514px, each folded tool frees 38px
const count = (availableWidth: number) =>
getToolbarFoldCount(514, 38, availableWidth);
it("folds nothing while the toolbar fits", () => {
expect(count(800)).toBe(0);
expect(count(514)).toBe(0);
// sub-pixel rounding doesn't fold a tool
expect(count(513.6)).toBe(0);
});
it("folds as many tools as needed to fit", () => {
expect(count(513)).toBe(1);
expect(count(476)).toBe(1);
expect(count(475)).toBe(2);
expect(count(400)).toBe(3);
});
it("folds at most every foldable tool", () => {
expect(count(514 - 9 * 38)).toBe(TOOLBAR_FOLD_ORDER.length);
expect(count(10)).toBe(TOOLBAR_FOLD_ORDER.length);
});
});
@@ -0,0 +1,203 @@
import { useLayoutEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
import type { ToolbarToolType } from "../components/Tools";
/**
* Toolbar tools that may fold into the extra-tools dropdown when the toolbar
* doesn't fit its column, in folding order (first folds first). Hand and
* selection never fold.
*/
export const TOOLBAR_FOLD_ORDER: readonly Extract<
ToolbarToolType,
| "eraser"
| "stickynote"
| "text"
| "freedraw"
| "line"
| "arrow"
| "ellipse"
| "diamond"
| "rectangle"
>[] = [
"eraser",
"stickynote",
"text",
"freedraw",
"line",
"arrow",
"ellipse",
"diamond",
"rectangle",
];
export type FoldableToolType = typeof TOOLBAR_FOLD_ORDER[number];
/** sub-pixel slack, so rounding can't flip a tool in and out */
const TOLERANCE_PX = 0.5;
const TRACK_VAR = "--exc-toolbar-track";
/**
* How many tools (in `TOOLBAR_FOLD_ORDER`) fold so that a toolbar which is
* `fullWidth` wide unfolded fits `availableWidth`, when each folded tool
* frees `step`.
*/
export const getToolbarFoldCount = (
fullWidth: number,
step: number,
availableWidth: number,
) =>
Math.min(
TOOLBAR_FOLD_ORDER.length,
Math.max(0, Math.ceil((fullWidth - availableWidth - TOLERANCE_PX) / step)),
);
/**
* Lets the toolbar shrink to the width its column can give it, by folding
* tools into the extra-tools dropdown.
*
* Every foldable tool takes the same width in the toolbar (a tool button +
* the row gap: `step`), so how many tools fold is a closed-form function of
* the column's width (`getToolbarFoldCount`). Nothing is measured per tool
* or carried over between resizes: the same width always folds the same
* tools.
*
* The toolbar column's track is `minmax(<fully folded>, <unfolded>)`. Both
* bounds follow from the rendered toolbar (`unfolded = its width + folded
* tools × step`), so they don't change when tools fold — the column's width
* never depends on the folding state, and folding can't feed back into the
* width it reacts to. The grid then gives the toolbar up to its full width
* (the side columns still floor at their top region's content), and the
* toolbar folds exactly as many tools as needed to fit what it got. Below
* the fully folded width the top row overflows as before.
*
* A column resize is handled inside the ResizeObserver callback, so tools
* fold in the same frame (folding only resizes the toolbar, which is deeper
* than the column — no ResizeObserver loop).
*
* Inert where layout isn't measurable (no ResizeObserver, zero sizes —
* e.g. jsdom).
*
* @param layoutKey changes when a render changes the toolbar's own width
* (compact ⇄ full styles panel), so the track follows in the same commit.
* Other changes of its width (e.g. the collab laser button appearing) are
* picked up by observing it, a frame later.
*/
export const useToolbarFolding = (
columnsRef: React.RefObject<HTMLElement | null>,
enabled: boolean,
layoutKey: unknown,
) => {
const [foldedCount, setFoldedCount] = useState(0);
/** the folded count the toolbar is currently rendered with */
const renderedCountRef = useRef(foldedCount);
useLayoutEffect(() => {
renderedCountRef.current = foldedCount;
});
useLayoutEffect(() => {
const columns = columnsRef.current;
const ResizeObserver = columns?.ownerDocument.defaultView?.ResizeObserver;
const region = columns?.querySelector<HTMLElement>(
".exc-region-top-center",
);
const row = region?.querySelector<HTMLElement>(".App-toolbar-container");
if (!enabled || !columns || !ResizeObserver || !region || !row) {
setFoldedCount(0);
return;
}
/**
* The unfolded toolbar's width, the width a folded tool frees, and the
* column track they give — or null where layout isn't measurable.
*/
const measure = () => {
// never folds, and is as wide as the tools that do
const tool = row.querySelector<HTMLElement>(
'[data-testid="toolbar-hand"]',
);
const rowWidth = row.getBoundingClientRect().width;
if (!tool?.parentElement || rowWidth <= 0) {
return null;
}
const step =
tool.getBoundingClientRect().width +
(parseFloat(getComputedStyle(tool.parentElement).columnGap) || 0);
const fullWidth = rowWidth + renderedCountRef.current * step;
const minWidth = fullWidth - TOOLBAR_FOLD_ORDER.length * step;
if (step <= 0 || minWidth <= 0) {
return null;
}
return {
fullWidth,
step,
track: `minmax(${Math.ceil(minWidth)}px, ${Math.ceil(fullWidth)}px)`,
};
};
let metrics: ReturnType<typeof measure> = null;
/** @param sync re-render before returning (not allowed in an effect) */
const fold = (sync: boolean) => {
const count = metrics
? getToolbarFoldCount(
metrics.fullWidth,
metrics.step,
region.getBoundingClientRect().width,
)
: 0;
if (count === renderedCountRef.current) {
return;
}
if (sync) {
flushSync(() => setFoldedCount(count));
} else {
setFoldedCount(count);
}
};
/** sets the column track from the rendered toolbar, and folds to fit */
const update = (sync: boolean) => {
metrics = measure();
if (!metrics) {
columns.style.removeProperty(TRACK_VAR);
} else if (columns.style.getPropertyValue(TRACK_VAR) !== metrics.track) {
columns.style.setProperty(TRACK_VAR, metrics.track);
}
fold(sync);
};
let frame = 0;
const observer = new ResizeObserver((entries) => {
// the toolbar resizes when tools fold (same track), or when its own
// content changes (e.g. the collab laser button, a forced tool hiding
// the lock button)
if (
entries.some((entry) => entry.target === row) &&
measure()?.track !== metrics?.track
) {
// a new track resizes the regions, which are observed and not
// deeper than the toolbar: deferred to the next frame, so it can't
// trip the ResizeObserver loop limit
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => update(true));
return;
}
fold(true);
});
observer.observe(region);
observer.observe(row);
update(false);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
columns.style.removeProperty(TRACK_VAR);
};
}, [columnsRef, enabled, layoutKey]);
return foldedCount;
};
+7
View File
@@ -19,6 +19,7 @@ import {
} from "./components/App.context";
import { InitializeApp } from "./components/InitializeApp";
import Footer from "./components/footer/FooterCenter";
import { Region } from "./components/regions/Region";
import LiveCollaborationTrigger from "./components/live-collaboration/LiveCollaborationTrigger";
import MainMenu from "./components/main-menu/MainMenu";
import WelcomeScreen from "./components/welcome-screen/WelcomeScreen";
@@ -498,6 +499,12 @@ export { parseLibraryTokensFromUrl, useHandleLibrary } from "./data/library";
export { Sidebar } from "./components/Sidebar/Sidebar";
export { Button } from "./components/Button";
export { Footer };
export { Region };
export type {
RegionArea,
RegionItemCollapse,
RegionItemRenderState,
} from "./components/regions/RegionRegistry";
export { MainMenu };
export { Ellipsify } from "./components/Ellipsify";
export {
@@ -82,7 +82,10 @@ describe("<Excalidraw/>", () => {
</Footer>
</Excalidraw>,
));
expect(container.querySelector(".footer-center")).toMatchInlineSnapshot(
const footerCenter = container.querySelector(".footer-center");
expect(footerCenter?.parentElement).toHaveClass("exc-region-bottom-center");
expect(footerCenter?.closest("footer.exc-region-bottom")).not.toBe(null);
expect(footerCenter).toMatchInlineSnapshot(
`
<div
class="footer-center zen-mode-transition"
@@ -635,7 +635,8 @@ describe("ui={false}", () => {
expect(queryContainer(".App-toolbar")).toBe(null);
expect(queryContainer(".main-menu-trigger")).toBe(null);
expect(queryContainer(".default-sidebar-trigger")).toBe(null);
expect(queryContainer(".layer-ui__wrapper__footer-left")).toBe(null);
expect(queryContainer(".zoom-actions")).toBe(null);
expect(queryContainer(".undo-redo-buttons")).toBe(null);
expect(queryContainer(".help-icon")).toBe(null);
});
@@ -732,6 +733,10 @@ describe("ui={{ enabled: ... }}", () => {
const scrollBackButton = queryContainer(".scroll-back-to-content");
expect(scrollBackButton).not.toBe(null);
expect(scrollBackButton!.parentElement).toHaveClass(
"floating-status-stack",
);
expect(scrollBackButton!.closest(".exc-region-bottom")).toBe(null);
fireEvent.click(scrollBackButton!);
await waitFor(() => expect(h.state.scrolledOutside).toBe(false));
});
@@ -789,10 +794,32 @@ describe("ui={false} with host UI", () => {
</Excalidraw>,
);
expect(queryContainer("[data-testid='host-top-left']")).not.toBe(null);
expect(queryContainer("[data-testid='host-top-right']")).not.toBe(null);
const hostTopLeft = queryContainer("[data-testid='host-top-left']")!;
const hostTopRight = queryContainer("[data-testid='host-top-right']")!;
expect(hostTopLeft).not.toBe(null);
expect(hostTopRight).not.toBe(null);
expect(queryContainer("[data-testid='host-footer']")).not.toBe(null);
expect(queryContainer("[aria-label='host sidebar']")).not.toBe(null);
expect(hostTopLeft.parentElement).toHaveClass(
"exc-region-top-left-host-slot",
);
expect(hostTopLeft.closest(".exc-region-top-left-content")).not.toBe(null);
expect(hostTopRight.parentElement).toHaveClass(
"exc-region-top-right-host-slot",
);
const topRightContent = hostTopRight.closest(
".exc-region-top-right-content",
);
expect(topRightContent).not.toBe(null);
expect(
topRightContent!.querySelector("[aria-label='host sidebar']"),
).not.toBe(null);
// top regions live in the side columns, the host footer in its sibling band
expect(hostTopLeft.closest(".exc-region-column-left")).not.toBe(null);
expect(hostTopRight.closest(".exc-region-column-right")).not.toBe(null);
const hostFooter = queryContainer("[data-testid='host-footer']")!;
expect(hostFooter.closest(".exc-region-columns")).toBe(null);
expect(hostFooter.closest(".exc-region-bottom")).not.toBe(null);
fireEvent.click(container.querySelector(".main-menu-trigger")!);
expect(container.textContent).toContain("host menu item");
@@ -806,6 +833,26 @@ describe("ui={false} with host UI", () => {
});
});
describe("host top-right UI on phone", () => {
it("renders alongside the default sidebar trigger", async () => {
await render(
<Excalidraw
UIOptions={{ getFormFactor: () => "phone" }}
renderTopRightUI={() => <div data-testid="host-top-right" />}
/>,
);
fireEvent.resize(window);
await waitFor(() => expect(h.app.editorInterface.formFactor).toBe("phone"));
const topRightContent = queryContainer(
"[data-testid='host-top-right']",
)!.closest(".exc-region-top-right-content");
expect(topRightContent!.querySelector(".default-sidebar-trigger")).not.toBe(
null,
);
});
});
describe("interaction={false} ui={false}", () => {
beforeEach(async () => {
mockBoundingClientRect();
+9 -28
View File
@@ -431,39 +431,20 @@ describe("minimap", () => {
fireEvent.pointerUp(minimap, { clientX: 80, clientY: 70 });
});
it("keeps the compact styles panel and the pen mode button clear of it", async () => {
const rectangle = API.createElement({ type: "rectangle" });
it("keeps the styles panel's region clear of it", async () => {
await render(
<Excalidraw
UIOptions={{ getFormFactor: () => "tablet" }}
initialData={{
elements: [rectangle],
appState: { minimapEnabled: true },
}}
/>,
);
fireEvent.resize(window);
await waitFor(() =>
expect(h.app.editorInterface.formFactor).toBe("tablet"),
);
const getPanel = () =>
document.querySelector<HTMLElement>(".compact-shape-actions-island")!;
API.setSelectedElements([rectangle]);
await waitFor(() =>
expect(getPanel().style.maxHeight).toBe(
`${h.state.height - 166 - 138}px`,
),
<Excalidraw initialData={{ appState: { minimapEnabled: true } }} />,
);
// (its region stops above it in CSS, see `.exc-regions--minimap`)
const regions = document.querySelector(".exc-regions")!;
expect(getMinimap()).not.toBe(null);
expect(regions.classList.contains("exc-regions--minimap")).toBe(true);
act(() => {
h.setState({ penDetected: true });
h.setState({ minimapEnabled: false });
});
expect(document.querySelector(".ToolIcon__penMode")).not.toBe(null);
expect(getPanel().style.maxHeight).toBe(
`${h.state.height - 166 - 138 - 54}px`,
);
expect(getMinimap()).toBe(null);
expect(regions.classList.contains("exc-regions--minimap")).toBe(false);
});
it("isn't available in editors too short for it", async () => {