mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-12-04 18:35:30 +03:00
* feat(editor): sticky notes * clamp sticky note font size * [dragInput] reject non-finite values * chore: prettier formatting after rebase Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(editor): sticky notes cleanup (plan §7.1) - hide `transparent` in the sticky stroke picker through master's `excludedColors` (#11872) instead of the branch's own `hiddenPaletteColorNames`; the swatch becomes a grid-preserving placeholder, its hotkey stays dead, and arrow-key navigation steps over it in the arrow's direction (unit + integration tests) - move the text pixel-snap change out to `dwelle/text-pixel-snap` (705e497e2): it affects every text element at every zoom and is not zoom-aware, so it lands separately - rename `STICKY_NOTE_DEFAULT_FONT_SIZE` → `STICKY_NOTE_FALLBACK_FONT_SIZE`: it is only the non-finite fallback; new sticky text seeds its ceiling from `currentItemFontSize` (decision D3) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): one sticky note layout core + resize intents (plan §7.2, 1/2) - `getStickyNoteLayout` is the single fit/grow/position calculation (pure; ceiling-anchored size grid, warm-started binary search instead of the linear descent); `updateStickyNoteLayout` applies it to a scene and runs the bound-arrow pass by default (callers forward `simultaneouslyUpdated` or opt out when they own a pass); `relayoutStickyNotes` applies it inside immutable element arrays, identity- and version-preserving - resize intents are absolute values recomputed from the gesture-start snapshot on every pointer-move (`getStickyNoteResizeIntent`): width-only gestures keep the base height, height gestures set it, proportional gestures (Shift on any handle, aspect-locked multi-select, Stats group) also scale the font ceiling, flips preserve everything; the content correction anchors at the held edge (n* → bottom, Alt → center, Shift+E/W → center). The corner pre-fit clamp and the multi-resize sentinel/veto are gone: one fit per pointer-move - arrows bound to a note follow text-driven growth, and multi-resize / Stats group update them after the content correction, not before - `fontSizeMax` is `number | null`; every read/write goes through the container-aware `getUserFontSize` / `getUserFontSizeUpdate` (a detached label with a stale ceiling neither shows nor keeps writing it); unbind clears it and returns an empty note to its base height; restore seeds or clears it after binding repair and normalizes a sticky label's stroke - paste styles lays out a restyled note and its label together in a post-pass (no phantom-container mismatch) and reads the source ceiling from the copied snapshot rather than the fitted size - `redrawTextBoundingBox` / `handleBindTextResize` delegate sticky notes up front (no wasted generic wrap); the `refreshTextDimensions` sticky arm and the wysiwyg duplicate arm are gone; `clampStickyNoteProps` becomes the identity-preserving `normalizeStickyNote` Tests: content-pinned corner drag keeps the requested base, Shift+E scales note/base/ceiling, width-only drag preserves the base of a grown note, Shift released mid-gesture restores gesture-start values, flipping a rotated grown note keeps base/ceiling/label angle, multi-resize syncs an empty note's base. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): sticky note invariants in changeProperty + regression tests (plan §7.2, 2/2) - `changeProperty` normalizes sticky notes after any property write (identity-preserving `normalizeStickyNote`), replacing the three per-action wraps in the background, sloppiness and roundness actions - tests (new `tests/stickyNotes.test.tsx` + restore): arrows bound to a note follow text-driven growth while typing; binding free text seeds the ceiling and unbinding clears it (`null`) and returns the note to its base height; pasting styles copies the user's ceiling and lays out the note together with its label; unselected notes keep object identity through property actions; a transparent background write is normalized; restore clears a stale ceiling on unbound text and seeds ceiling + visible stroke on a sticky label Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): sticky note creation feel + sticky color domain (plan §7.3) Creation - a note starts as a 0×0 draft inserted like every other tool and is previewed at its true dragged size (no jump to 40px on the first move); a gesture under the drag threshold is a click → the default 250×250 square centered on the pointer; a longer drag snaps to the 40×40 minimum only on release, growing away from the origin corner. The preview suppression flag and the pointer-move sticky arm are gone - `normalizeStickyNote` splits into style (constructor + every pass) and geometry (finalize, restore, action passes) so a draft is legal Colors — sticky notes are their own color domain (decision D2) - new `currentItemStickynoteBackgroundColor` default (yellow) next to the stroke one; both persisted/restored non-transparent; new notes and their labels seed from the sticky defaults (a label takes the note's stroke) - own top-pick slots (`colorTopPicks.stickyNoteStroke/Background`) and classic note picks; transparent excluded like bucket fill - one `resolveColorTarget` (regular / sticky / mixed, incl. the text being edited) resolved at execution time in the stroke and background actions' `perform`; the panel only sends `{ color }`, so the memoized picker's stale closure can no longer write the wrong tool's default (A1) - one `getColorUpdate` policy used by the actions, both eyedroppers (which now include bound labels, so a stroke pick colors a note's visible text — 1.12), paste styles and bind-existing-text (a transparent label bound to a note takes the note's text color — A3); the per-surface forks and `isStickyNoteStrokeColorElement` are gone Tests: click under the threshold, 20px drag previews at 20 and snaps to 40 with the origin corner fixed (both directions); closed-popup top pick after a tool switch writes the sticky default; mixed selection writes both domains; notes are created from the sticky defaults; bind normalizes a transparent label; the keyboard eyedropper colors a note's label. App-state snapshots gain the three new keys. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): font-aware minimum sticky note size The 40×40 floor let a freshly placed note grow on the very first keystroke: one line at the default 20px ceiling plus the 16px padding needs 57px. - `STICKY_NOTE_MIN_SIZE = 75` replaces the width/height pair as the data floor (normalization, layout, restore) - `getStickyNoteMinSize({ fontSize, fontFamily })` = max(75, round(ceiling × lineHeight) + 2 × padding) is the UI floor: the creation snap on release uses the current font size/family, the single resize floor uses the label's ceiling (constant floor for an empty note). Excalifont: 75 up to the L ceiling, 77 at 36px, 92 at 48px Tests: the 20px drag now snaps to 75; a 48px ceiling yields a 92px note that keeps its height on the first character. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(editor): sticky note regression matrix (plan §7.4) + two Stats fixes Tests (27 new): Alt/center resize keeps the center of a content-pinned note; proportional multi-select scales the label's ceiling, a free multi-select of an empty note uses the requested height; a proportional gesture returning to scale 1 restores everything; rotated growth keeps the top edge; the fit takes ≤ 2 measurements on a warm keystroke and ≤ 12 on a cold search from a 512 ceiling; a lowered ceiling wins over a still-fitting old size; odd/fractional ceilings stay reachable on the ceiling-anchored grid; the font-aware minimum size. Bound arrows follow the note on unbind, after a content-constrained resize and after a font-size action, and are not moved twice when resized as part of the same selection. A top pick while editing a note's label targets the label and the sticky default; the preview eyedropper colors a selected note's label; paste styles resolves a since-deleted source's ceiling from the copied snapshot; a detached label with a stale ceiling neither shows nor writes it; duplication keeps the ceiling and base height; an empty note escaped from editing stays and is removed by undo; Stats W keeps the base height and a group W edit scales the ceiling; restore normalizes both sticky defaults, keeps the new top-pick slots and refits note + label under `refreshDimensions`; unit tests for `resolveColorTarget` (regular / sticky / mixed / editing) and the default normalization. Source fixes the tests surfaced: - Stats `DragInput`: the typed-value path handed callbacks the live elements map as "original", so gesture-start values (a note's width, its label's ceiling) read as the already-applied values; it now snapshots the scene like the pointer-drag path does - Stats group resize (`MultiDimension`): a group unit lists the note's label too and scaled it as a standalone element after the note, wiping the fitted size; the note's layout owns its label Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): sticky note skeleton API, tool hint, help row, docs (plan §7.5) - `convertToExcalidrawElements` accepts `{ type: "stickynote", x, y, label?, ... }` (new `ValidStickyNote` skeleton member): the note is constructed through `newStickyNoteElement` + `normalizeStickyNoteGeometry` (250×250 default, `baseHeight` finalized, sticky color invariants), and a label is bound through the sticky fit so its `fontSize` becomes the ceiling and the note grows only if the text overflows at the minimum size (decision D7) - tool hint for the sticky note tool ("Click to place a note, or drag to size it") and the `N` shortcut row in the help dialog - dev-docs: "Sticky Notes" section in the element-skeleton page; CHANGELOG entry (PR number placeholder) Tests: skeleton defaults, invariant enforcement on given props, label binding with the ceiling and the note's text color, growth for an overflowing label. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * refactor: move the seeded PRNG (mulberry32) to @excalidraw/common Pure utility next to `randomInteger`/`reseed`; the sticky note corner jitter imports it from there. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * refactor(editor): drop the dead roughjs Drawable for sticky notes Nothing ever generated or drew it: both renderers paint a note directly from `getStickyNoteRenderPoints`, and every `ShapeCache` consumer is type-gated to the rectangle family or linear elements. It also disagreed with the rendered outline (generic corner radius, no jitter). Sticky notes now sit with text/image/frame in the `null`-shape group, which the cache treats as a valid value. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): sticky note creation-date footer Every note reserves a 32px band under its label body and paints the note's `created` date there, on canvas and in SVG export: "7 Sep" while the year is the current one, "7 Sep 2025" otherwise, nothing for an unknown timestamp (the band stays reserved so geometry never depends on data availability). The label form is chosen by width bucket, never measured, so painting stays measurement-free — server-side SVG export has no text measurer — and an absolute date means exports never go stale. - `STICKY_NOTE_FOOTER` and `STICKY_NOTE_BODY_INSET_Y` in @excalidraw/common; `getStickyNoteDateLabel` / `getStickyNoteFooter` in stickyNote.ts - the layout, `getBoundTextMaxHeight`, the text editor and both renderers share the one inset; a rotated label rotates about the note center, not the now-asymmetric body center - `getStickyNoteMinSize` returns `{ width, height }`; creation and resize clamp each axis to its own floor (a Shift drag stays square) - tests: date label, width buckets, body height, resize floor, SVG + canvas export, creation minimums Plan: sticky_notes_review_final.md §9. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): image tool into "More tools", letter shortcut badges With the sticky tool on N between text (8) and eraser (0), the numbered badge row no longer reads as a sequence. On desktop and tablet, move the image tool into the "More tools" menu (first entry, still `9`, `UIOptions.tools.image` keeps hiding it) and badge the toolbar tools with their letter shortcuts (V R D O A L P T N E) instead of numbers. The number keys keep working; tooltips and the help dialog are unchanged. The mobile toolbar keeps its image slot. - Toolbar.tsx: image item in `ExtraToolsDropdown` (trigger highlight and icon while active), `UIOptions` passed through for the gate - Tools.tsx: `keyBindingLabel` prefers the letter - tests: `UI.clickExtraTool`, image test uses it, toolbar describe in tool.test.tsx (menu placement, UIOptions gate, letter badges) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(editor): a sticky note and its label share one ink The creation-date footer paints from the note's `strokeColor`, the label from its own, and three writes let them drift: coloring the label while editing it (the wysiwyg clears the selection, so `changeProperty` targets only the edited text), binding an already-colored text (only transparent was rewritten), and paste styles from a source whose container and label carry two colors. Red text under a black date. The note's `strokeColor` is its ink — the seed for a new label and what the footer paints with — and the label always mirrors it: - `syncStickyNoteInk(elements, prevElementsMap)`: after a write, copies the side that changed onto the other; when both changed or the data drifted, the label wins (it is the text the user styled); a transparent label takes the note's color; identity-preserving when nothing changes - entrances: the stroke action (after `changeProperty`, which covers edit mode), paste styles (before the relayout), bind text (the text's color wins, transparent falls back), the skeleton path (a label that sets its own color gives it to the note), restore (label wins over a drifted note) - the stroke picker reads "Text color" for notes (`labels.textColor`) - tests for the helper and for every entrance Plan: sticky_notes_review_final.md §12. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * make footer opacity=1 * chore: fix sticky note test import order * feat(editor): drag a tool out of the toolbar to drop a default-sized element Press a tool button and drag onto the canvas: a default-sized element follows the pointer as a translucent preview and is placed where the pointer is released. Sticky notes opt in; the mechanism is generic. `App.toolDrag.ts` owns the gesture. `DRAGGABLE_TOOLS` is the registry — a tool provides `createElement(app, center)` (the element it drops, centered on the pointer, from the same `currentItem*` defaults a click uses) and an optional `onDrop` (a sticky note starts editing its label). Adding a tool is one entry. The preview exists only on the unit until the drop: not in the scene, the store or the history, so collaborators never see it and Escape, pointercancel, window blur or a release outside the canvas leave nothing behind. It is painted by the existing `NewElementCanvas`, drawn exactly as it will land, with the canvas itself made translucent (a CSS opacity on the canvas — per-draw-call alpha would darken where a shadow and a fill overlap). The button arms on pointerdown (a new `onPointerDown` hook on the toggle `IconButton`) and the drag starts once the pointer has moved `DRAGGING_THRESHOLD`, so a plain click still selects the tool. Listeners live on the owner window like the other pointer gestures. The drop is `insertNewElement` + one store capture (one undo entry), selects the element and switches to the preferred selection tool — whatever tool was active (an arrow, say) must not stay armed under the dropped element or its editor. The hit test prefers `elementFromPoint` (sees through a touch's implicit capture on the button) and falls back to the event target where it is missing (jsdom). Made public on App for the unit: `store`, `startTextEditing`, `getCurrentItemRoundness`, `getCurrentItemStrokeWidth`. Tests: drag → preview with an untouched scene and history → drop centered at the pointer with one history entry, the editor open and the selection tool active, undo removes it; Escape mid-drag leaves nothing and a late pointerup is inert; a release outside the canvas drops nothing; a plain click still selects. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(editor): default a text element's fontSizeMax to null `newTextElement` left `fontSizeMax` undefined while restore normalizes it to `null`. `Delta.distinctKeysIterator` compares with `!==`, so a restored copy of a locally created text element reported a phantom `fontSizeMax` change — today only in collab reconciliation deltas, which are not undoable, but a latent source of spurious version bumps. Normalize to `null` in the constructor, like `labelPosition`. Snapshots change accordingly (`undefined` → `null`), including the embedded scene payload in the SVG export snapshot. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(editor): drop a duplicated scheduleCapture in the sticky note finalize A paste error: the two calls in one tick set the same flag. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(editor): decide history visibility from the applied result Creating a sticky note and abandoning its editor by clicking out left two history entries: the note's creation, and one that only deleted the empty label and dropped the note's reference to it — nothing a user can see, so the first undo appeared to do nothing. (Escape left the same deletion pending instead, folded into the next entry.) The text tool's own click-create-and-abandon had the same invisible entry. History already skips entries with no visible change, but visibility was decided per property patch, before binding repair and layout ran: an `isDeleted` flip or a `boundElements` edit always counted, and anything layout moved afterwards never did. `ElementsDelta.applyTo` now decides it from the applied result. After the deltas, reordering, binding repair and text/arrow layout, the "before" and "after" of every affected element are compared: - `idsToCheck` = the changed elements plus what layout can move for them: a text's container and everything in `boundElements` (a container's label and arrows); the set is walked as it grows, so an arrow brings in its own label. - Unchanged elements are shared between the incoming map and the result and layout mutates them in place, so their "before" is a shallow copy; changed elements already have a fresh instance. The whole scene is never copied. - An element counts as visible only if it is not deleted and, for text, not empty — except an empty label carrying arrow bindings or sitting on an arrow, where it cuts the gap. `version`, `versionNonce`, `updated`, `created` are metadata and `index` is covered by the z-order check; `boundElements` is compared as `type:id` strings with references to empty labels dropped, so binding repair that rebuilds equal objects reads as unchanged. Everything else counts. A dev/test-only assertion records every element's version before layout and throws if layout bumped one outside `idsToCheck`, so a new layout dependency fails a test instead of letting undo silently skip a real change. For that to work the `return` had to leave the `finally` block: a return in `finally` overrides a thrown exception, so the existing dev/test rethrow for failures in reordering and layout never actually propagated. Production behavior is unchanged — the catch still returns with the flag forced to visible. Cost, production build, median per `applyTo`: sparse changes at parity through 50k elements; 10k visible bulk updates +13%; 10k metadata-only updates 44 → 95 ms, because proving "nothing visible" cannot stop at the first element — the case the old code answered wrongly. `applyTo` runs on undo/redo and the version slider, both user-paced. Creation and typing still undo separately, and a drop from the toolbar still records at the drop. Tests: delta-level (empty-label deletion and restoration on a rectangle and a sticky note ignored; a non-empty label, an arrow's label gap, a container resized by a restored label, arrow bindings on empty text, a label and an arrow repositioned by a container redraw all visible; excluded or already-applied properties and a metadata-only update invisible; snapshot restoration visible) and the sticky note flows (Escape, click-out, font change on an empty label, typing). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(editor): snap sticky note placement to the grid * perf(editor): ignore arrow bindings in sticky layout input check * feat(editor): center a sticky note's label in the whole note, tighten the footer A middle-aligned label was centered in the body above the creation-date footer, so it sat visibly high — half a footer above the note's center. It is now centered in the whole padded note (`height − 2·padding`), the footer ignored, and only pushed up against the body's bottom once centering would run it into the footer. The fit and the growth rule are unchanged: the note still grows at the same label height, no vertical budget is lost, and top and bottom alignment are as before. Rotation already turned the label about the note's center. The footer takes less room: its band shrinks from 32px to 20px and the date's baseline is defined from the note's bottom edge (14px) rather than from the padding, so the glyphs sit ~11px from the edge (was 17) with ~13px to the label body above (was 19). The vertical inset follows (64 → 52), and with it the font-aware minimum note sizes. Tests: a middle-aligned label is centered on the note's center at three angles; centering is clamped only once it would overlap the footer; existing sizes derive from the inset constant. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(editor): resize sticky notes proportionally by default * fix(editor): preserve resize flips and text container anchors Apply minimum sizes and proportional font scaling to dimension magnitudes, then restore their signs for shared flip geometry. Share rotation-aware positioning for text-driven height changes and pass vertical flip state through single and multiple-element resizing. Add regression coverage for mirrored resizing, proportional minimum sizes, and text growth after crossing the resize anchor. * feat(editor): lift a seeded sticky note corner at high roughness Curve one corner at roughness 2, chosen from the note seed so it stays consistent through redraws and resizes. Pull its shadow inward by half the bend while retaining the existing down-right offset. Share the generated paper and shadow paths between Canvas and SVG rendering. * fix(editor): share the default sticky note color with its quick pick * refactor(editor): rename a label's `fontSizeMax` to `baseFontSize` The field holds the font size the user picked, from which the sticky note layout derives the fitted `fontSize`. "Max" described today's fitter (it only shrinks); "base" names the intent and pairs with the note's `baseHeight`, the other user-set value the layout derives from. Renamed before the field ships, since it is persisted in scene files. The type is now required (`number | null`): the constructor and restore already always write it, and history deltas compare with strict inequality, so an omitted key against `null` would record a spurious change. Making it required lets tsc catch producers that omit it (one test fixture did). Helpers follow: `getBaseFontSize`, `getBaseFontSizeUpdate`. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(editor): slightly strengthen sticky note edges * feat(editor): color a sticky note's background while editing its label While editing a note's label the styles panel targets the label, which has no fill, so the background picker was gone and the note's color could only be changed after leaving the editor. The picker now stays available while editing, shows the note's fill, and a pick colors the note — text color and background in one editing pass. One helper, `getColorTargetElement`, decides where a color pick on an element lands (a background pick on a note's label goes to the note); the target resolver, the panel predicate, the panel value and the action all use it, so the picker also gets the sticky domain (sticky picks, no transparent, the sticky default written). Also fixes a latent bug in the background action: with nothing selected, `selectedElements.every(isLine…)` was vacuously true, so the action took the polygon branch and did nothing. Unreachable before, since no background picker was available without a selection. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix changelog * fix snaps * more snap --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1313 lines
37 KiB
TypeScript
1313 lines
37 KiB
TypeScript
import { simplify } from "points-on-curve";
|
|
import { getStroke, getStrokePoints } from "perfect-freehand";
|
|
import { LaserPointer } from "@excalidraw/laser-pointer";
|
|
|
|
import {
|
|
type GeometricShape,
|
|
getClosedCurveShape,
|
|
getCurveShape,
|
|
getEllipseShape,
|
|
getFreedrawShape,
|
|
getPolygonShape,
|
|
} from "@excalidraw/utils/shape";
|
|
|
|
import {
|
|
pointFrom,
|
|
pointDistance,
|
|
type LocalPoint,
|
|
pointRotateRads,
|
|
} from "@excalidraw/math";
|
|
import {
|
|
ROUGHNESS,
|
|
THEME,
|
|
isTransparent,
|
|
assertNever,
|
|
COLOR_PALETTE,
|
|
LINE_POLYGON_POINT_MERGE_DISTANCE,
|
|
applyDarkModeFilter,
|
|
DEFAULT_STROKE_STREAMLINE,
|
|
} from "@excalidraw/common";
|
|
|
|
import { RoughGenerator } from "roughjs/bin/generator";
|
|
|
|
import type { GlobalPoint } from "@excalidraw/math";
|
|
|
|
import type { Mutable } from "@excalidraw/common/utility-types";
|
|
|
|
import type {
|
|
AppState,
|
|
EmbedsValidationStatus,
|
|
} from "@excalidraw/excalidraw/types";
|
|
import type {
|
|
ElementShape,
|
|
ElementShapes,
|
|
SVGPathString,
|
|
} from "@excalidraw/excalidraw/scene/types";
|
|
|
|
import { elementWithCanvasCache } from "./renderElement";
|
|
|
|
import {
|
|
canBecomePolygon,
|
|
isElbowArrow,
|
|
isEmbeddableElement,
|
|
isIframeElement,
|
|
isIframeLikeElement,
|
|
isLinearElement,
|
|
} from "./typeChecks";
|
|
import { getCornerRadius, isPathALoop } from "./utils";
|
|
import { headingForPointIsHorizontal } from "./heading";
|
|
|
|
import { canChangeRoundness } from "./comparisons";
|
|
import {
|
|
elementCenterPoint,
|
|
getArrowheadPoints,
|
|
getDiamondPoints,
|
|
getElementAbsoluteCoords,
|
|
} from "./bounds";
|
|
import { shouldTestInside } from "./collision";
|
|
|
|
import type {
|
|
ExcalidrawElement,
|
|
ExcalidrawSelectionElement,
|
|
ExcalidrawLinearElement,
|
|
ExcalidrawFreeDrawElement,
|
|
ElementsMap,
|
|
ExcalidrawLineElement,
|
|
Arrowhead,
|
|
} from "./types";
|
|
|
|
import type { Drawable, Options } from "roughjs/bin/core";
|
|
import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
|
|
|
export class ShapeCache {
|
|
private static rg = new RoughGenerator();
|
|
private static cache = new WeakMap<
|
|
ExcalidrawElement,
|
|
{ shape: ElementShape; theme: AppState["theme"] }
|
|
>();
|
|
|
|
/**
|
|
* Retrieves shape from cache if available. Use this only if shape
|
|
* is optional and you have a fallback in case it's not cached.
|
|
*/
|
|
public static get = <T extends ExcalidrawElement>(
|
|
element: T,
|
|
theme: AppState["theme"] | null,
|
|
) => {
|
|
const cached = ShapeCache.cache.get(element);
|
|
if (cached && (theme === null || cached.theme === theme)) {
|
|
return cached.shape as T["type"] extends keyof ElementShapes
|
|
? ElementShapes[T["type"]] | undefined
|
|
: ElementShape | undefined;
|
|
}
|
|
return undefined;
|
|
};
|
|
|
|
public static delete = (element: ExcalidrawElement) => {
|
|
ShapeCache.cache.delete(element);
|
|
elementWithCanvasCache.delete(element);
|
|
};
|
|
|
|
public static destroy = () => {
|
|
ShapeCache.cache = new WeakMap();
|
|
};
|
|
|
|
/**
|
|
* Generates & caches shape for element if not already cached, otherwise
|
|
* returns cached shape.
|
|
*/
|
|
public static generateElementShape = <
|
|
T extends Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
|
|
>(
|
|
element: T,
|
|
renderConfig: {
|
|
isExporting: boolean;
|
|
canvasBackgroundColor: AppState["viewBackgroundColor"];
|
|
embedsValidationStatus: EmbedsValidationStatus;
|
|
theme: AppState["theme"];
|
|
} | null,
|
|
) => {
|
|
// when exporting, always regenerated to guarantee the latest shape
|
|
const cachedShape = renderConfig?.isExporting
|
|
? undefined
|
|
: ShapeCache.get(element, renderConfig ? renderConfig.theme : null);
|
|
|
|
// `null` indicates no rc shape applicable for this element type,
|
|
// but it's considered a valid cache value (= do not regenerate)
|
|
if (cachedShape !== undefined) {
|
|
return cachedShape;
|
|
}
|
|
|
|
elementWithCanvasCache.delete(element);
|
|
|
|
const shape = _generateElementShape(
|
|
element,
|
|
ShapeCache.rg,
|
|
renderConfig || {
|
|
isExporting: false,
|
|
canvasBackgroundColor: COLOR_PALETTE.white,
|
|
embedsValidationStatus: null,
|
|
theme: THEME.LIGHT,
|
|
},
|
|
) as T["type"] extends keyof ElementShapes
|
|
? ElementShapes[T["type"]]
|
|
: Drawable | null;
|
|
|
|
if (!renderConfig?.isExporting) {
|
|
ShapeCache.cache.set(element, {
|
|
shape,
|
|
theme: renderConfig?.theme || THEME.LIGHT,
|
|
});
|
|
}
|
|
|
|
return shape;
|
|
};
|
|
}
|
|
|
|
const getDashArrayDashed = (strokeWidth: number) => [8, 8 + strokeWidth];
|
|
|
|
const getDashArrayDotted = (strokeWidth: number) => [1.5, 6 + strokeWidth];
|
|
|
|
function adjustRoughness(element: ExcalidrawElement): number {
|
|
const roughness = element.roughness;
|
|
|
|
const maxSize = Math.max(element.width, element.height);
|
|
const minSize = Math.min(element.width, element.height);
|
|
|
|
// don't reduce roughness if
|
|
if (
|
|
// both sides relatively big
|
|
(minSize >= 20 && maxSize >= 50) ||
|
|
// is round & both sides above 15px
|
|
(minSize >= 15 &&
|
|
!!element.roundness &&
|
|
canChangeRoundness(element.type)) ||
|
|
// relatively long linear element
|
|
(isLinearElement(element) && maxSize >= 50)
|
|
) {
|
|
return roughness;
|
|
}
|
|
|
|
return Math.min(roughness / (maxSize < 10 ? 3 : 2), 2.5);
|
|
}
|
|
|
|
export const generateRoughOptions = (
|
|
element: ExcalidrawElement,
|
|
continuousPath = false,
|
|
isDarkMode: boolean = false,
|
|
): Options => {
|
|
const options: Options = {
|
|
seed: element.seed,
|
|
strokeLineDash:
|
|
element.strokeStyle === "dashed"
|
|
? getDashArrayDashed(element.strokeWidth)
|
|
: element.strokeStyle === "dotted"
|
|
? getDashArrayDotted(element.strokeWidth)
|
|
: undefined,
|
|
// for non-solid strokes, disable multiStroke because it tends to make
|
|
// dashes/dots overlay each other
|
|
disableMultiStroke: element.strokeStyle !== "solid",
|
|
// for non-solid strokes, increase the width a bit to make it visually
|
|
// similar to solid strokes, because we're also disabling multiStroke
|
|
strokeWidth:
|
|
element.strokeStyle !== "solid"
|
|
? element.strokeWidth + 0.5
|
|
: element.strokeWidth,
|
|
// when increasing strokeWidth, we must explicitly set fillWeight and
|
|
// hachureGap because if not specified, roughjs uses strokeWidth to
|
|
// calculate them (and we don't want the fills to be modified)
|
|
fillWeight: element.strokeWidth / 2,
|
|
hachureGap: element.strokeWidth * 4,
|
|
roughness: adjustRoughness(element),
|
|
stroke: applyDarkModeFilter(element.strokeColor, isDarkMode),
|
|
preserveVertices:
|
|
continuousPath || element.roughness < ROUGHNESS.cartoonist,
|
|
};
|
|
|
|
switch (element.type) {
|
|
case "rectangle":
|
|
case "iframe":
|
|
case "embeddable":
|
|
case "diamond":
|
|
case "ellipse": {
|
|
options.fillStyle = element.fillStyle;
|
|
options.fill = isTransparent(element.backgroundColor)
|
|
? undefined
|
|
: applyDarkModeFilter(element.backgroundColor, isDarkMode);
|
|
if (element.type === "ellipse") {
|
|
options.curveFitting = 1;
|
|
}
|
|
return options;
|
|
}
|
|
case "line":
|
|
case "freedraw": {
|
|
if (isPathALoop(element.points)) {
|
|
options.fillStyle = element.fillStyle;
|
|
options.fill =
|
|
element.backgroundColor === "transparent"
|
|
? undefined
|
|
: applyDarkModeFilter(element.backgroundColor, isDarkMode);
|
|
}
|
|
return options;
|
|
}
|
|
case "arrow":
|
|
return options;
|
|
default: {
|
|
throw new Error(`Unimplemented type ${element.type}`);
|
|
}
|
|
}
|
|
};
|
|
|
|
const modifyIframeLikeForRoughOptions = (
|
|
element: ExcalidrawElement,
|
|
isExporting: boolean,
|
|
embedsValidationStatus: EmbedsValidationStatus | null,
|
|
) => {
|
|
if (
|
|
isIframeLikeElement(element) &&
|
|
(isExporting ||
|
|
(isEmbeddableElement(element) &&
|
|
embedsValidationStatus?.get(element.id) !== true)) &&
|
|
isTransparent(element.backgroundColor) &&
|
|
isTransparent(element.strokeColor)
|
|
) {
|
|
return {
|
|
...element,
|
|
roughness: 0,
|
|
backgroundColor: "#d3d3d3",
|
|
fillStyle: "solid",
|
|
} as const;
|
|
} else if (isIframeElement(element)) {
|
|
return {
|
|
...element,
|
|
strokeColor: isTransparent(element.strokeColor)
|
|
? "#000000"
|
|
: element.strokeColor,
|
|
backgroundColor: isTransparent(element.backgroundColor)
|
|
? "#f4f4f6"
|
|
: element.backgroundColor,
|
|
};
|
|
}
|
|
return element;
|
|
};
|
|
|
|
const generateArrowheadCardinalityOne = (
|
|
generator: RoughGenerator,
|
|
arrowheadPoints: number[] | null,
|
|
lineOptions: Options,
|
|
) => {
|
|
if (arrowheadPoints === null) {
|
|
return [];
|
|
}
|
|
|
|
const [, , x3, y3, x4, y4] = arrowheadPoints;
|
|
|
|
return [generator.line(x3, y3, x4, y4, lineOptions)];
|
|
};
|
|
|
|
const generateArrowheadLinesToTip = (
|
|
generator: RoughGenerator,
|
|
arrowheadPoints: number[] | null,
|
|
lineOptions: Options,
|
|
) => {
|
|
if (arrowheadPoints === null) {
|
|
return [];
|
|
}
|
|
|
|
const [x2, y2, x3, y3, x4, y4] = arrowheadPoints;
|
|
|
|
return [
|
|
generator.line(x3, y3, x2, y2, lineOptions),
|
|
generator.line(x4, y4, x2, y2, lineOptions),
|
|
];
|
|
};
|
|
|
|
const getArrowheadLineOptions = (
|
|
element: ExcalidrawLinearElement,
|
|
options: Options,
|
|
) => {
|
|
const lineOptions = { ...options };
|
|
|
|
if (element.strokeStyle === "dotted") {
|
|
// for dotted arrows caps, reduce gap to make it more legible
|
|
const dash = getDashArrayDotted(element.strokeWidth - 1);
|
|
lineOptions.strokeLineDash = [dash[0], dash[1] - 1];
|
|
} else {
|
|
// for solid/dashed, keep solid arrow cap
|
|
delete lineOptions.strokeLineDash;
|
|
}
|
|
lineOptions.roughness = Math.min(1, lineOptions.roughness || 0);
|
|
|
|
return lineOptions;
|
|
};
|
|
|
|
const generateArrowheadOutlineCircle = (
|
|
generator: RoughGenerator,
|
|
options: Options,
|
|
strokeColor: string,
|
|
arrowheadPoints: number[] | null,
|
|
fill: string,
|
|
diameterScale = 1,
|
|
) => {
|
|
if (arrowheadPoints === null) {
|
|
return [];
|
|
}
|
|
|
|
const [x, y, diameter] = arrowheadPoints;
|
|
const circleOptions = {
|
|
...options,
|
|
fill,
|
|
fillStyle: "solid" as const,
|
|
stroke: strokeColor,
|
|
roughness: Math.min(0.5, options.roughness || 0),
|
|
};
|
|
|
|
delete circleOptions.strokeLineDash;
|
|
|
|
return [generator.circle(x, y, diameter * diameterScale, circleOptions)];
|
|
};
|
|
|
|
const getArrowheadShapes = (
|
|
element: ExcalidrawLinearElement,
|
|
shape: Drawable[],
|
|
position: "start" | "end",
|
|
arrowhead: Arrowhead,
|
|
generator: RoughGenerator,
|
|
options: Options,
|
|
canvasBackgroundColor: string,
|
|
isDarkMode: boolean,
|
|
) => {
|
|
if (arrowhead === null) {
|
|
return [];
|
|
}
|
|
|
|
const strokeColor = applyDarkModeFilter(element.strokeColor, isDarkMode);
|
|
const backgroundFillColor = applyDarkModeFilter(
|
|
canvasBackgroundColor,
|
|
isDarkMode,
|
|
);
|
|
const cardinalityOneOrManyOffset = -0.25;
|
|
const cardinalityZeroCircleScale = 0.8;
|
|
|
|
switch (arrowhead) {
|
|
case "circle":
|
|
case "circle_outline": {
|
|
return generateArrowheadOutlineCircle(
|
|
generator,
|
|
options,
|
|
strokeColor,
|
|
getArrowheadPoints(element, shape, position, arrowhead),
|
|
arrowhead === "circle_outline" ? backgroundFillColor : strokeColor,
|
|
);
|
|
}
|
|
case "triangle":
|
|
case "triangle_outline": {
|
|
const arrowheadPoints = getArrowheadPoints(
|
|
element,
|
|
shape,
|
|
position,
|
|
arrowhead,
|
|
);
|
|
|
|
if (arrowheadPoints === null) {
|
|
return [];
|
|
}
|
|
|
|
const [x, y, x2, y2, x3, y3] = arrowheadPoints;
|
|
const triangleOptions = {
|
|
...options,
|
|
fill:
|
|
arrowhead === "triangle_outline" ? backgroundFillColor : strokeColor,
|
|
fillStyle: "solid" as const,
|
|
roughness: Math.min(1, options.roughness || 0),
|
|
};
|
|
|
|
// always use solid stroke for arrowhead
|
|
delete triangleOptions.strokeLineDash;
|
|
|
|
return [
|
|
generator.polygon(
|
|
[
|
|
[x, y],
|
|
[x2, y2],
|
|
[x3, y3],
|
|
[x, y],
|
|
],
|
|
triangleOptions,
|
|
),
|
|
];
|
|
}
|
|
case "diamond":
|
|
case "diamond_outline": {
|
|
const arrowheadPoints = getArrowheadPoints(
|
|
element,
|
|
shape,
|
|
position,
|
|
arrowhead,
|
|
);
|
|
|
|
if (arrowheadPoints === null) {
|
|
return [];
|
|
}
|
|
|
|
const [x, y, x2, y2, x3, y3, x4, y4] = arrowheadPoints;
|
|
const diamondOptions = {
|
|
...options,
|
|
fill:
|
|
arrowhead === "diamond_outline" ? backgroundFillColor : strokeColor,
|
|
fillStyle: "solid" as const,
|
|
roughness: Math.min(1, options.roughness || 0),
|
|
};
|
|
|
|
// always use solid stroke for arrowhead
|
|
delete diamondOptions.strokeLineDash;
|
|
|
|
return [
|
|
generator.polygon(
|
|
[
|
|
[x, y],
|
|
[x2, y2],
|
|
[x3, y3],
|
|
[x4, y4],
|
|
[x, y],
|
|
],
|
|
diamondOptions,
|
|
),
|
|
];
|
|
}
|
|
case "cardinality_one":
|
|
return generateArrowheadCardinalityOne(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, arrowhead),
|
|
getArrowheadLineOptions(element, options),
|
|
);
|
|
case "cardinality_many":
|
|
return generateArrowheadLinesToTip(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, arrowhead),
|
|
getArrowheadLineOptions(element, options),
|
|
);
|
|
case "cardinality_one_or_many": {
|
|
const lineOptions = getArrowheadLineOptions(element, options);
|
|
|
|
return [
|
|
...generateArrowheadLinesToTip(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, "cardinality_many"),
|
|
lineOptions,
|
|
),
|
|
...generateArrowheadCardinalityOne(
|
|
generator,
|
|
getArrowheadPoints(
|
|
element,
|
|
shape,
|
|
position,
|
|
"cardinality_one",
|
|
cardinalityOneOrManyOffset,
|
|
),
|
|
lineOptions,
|
|
),
|
|
];
|
|
}
|
|
case "cardinality_exactly_one": {
|
|
const lineOptions = getArrowheadLineOptions(element, options);
|
|
|
|
return [
|
|
...generateArrowheadCardinalityOne(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, "cardinality_one", -0.5),
|
|
lineOptions,
|
|
),
|
|
...generateArrowheadCardinalityOne(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, "cardinality_one"),
|
|
lineOptions,
|
|
),
|
|
];
|
|
}
|
|
case "cardinality_zero_or_one": {
|
|
const lineOptions = getArrowheadLineOptions(element, options);
|
|
|
|
return [
|
|
...generateArrowheadOutlineCircle(
|
|
generator,
|
|
options,
|
|
strokeColor,
|
|
getArrowheadPoints(element, shape, position, "circle_outline", 1.5),
|
|
backgroundFillColor,
|
|
cardinalityZeroCircleScale,
|
|
),
|
|
...generateArrowheadCardinalityOne(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, "cardinality_one", -0.5),
|
|
lineOptions,
|
|
),
|
|
];
|
|
}
|
|
case "cardinality_zero_or_many": {
|
|
const lineOptions = getArrowheadLineOptions(element, options);
|
|
|
|
return [
|
|
...generateArrowheadLinesToTip(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, "cardinality_many"),
|
|
lineOptions,
|
|
),
|
|
...generateArrowheadOutlineCircle(
|
|
generator,
|
|
options,
|
|
strokeColor,
|
|
getArrowheadPoints(element, shape, position, "circle_outline", 1.5),
|
|
backgroundFillColor,
|
|
cardinalityZeroCircleScale,
|
|
),
|
|
];
|
|
}
|
|
case "bar":
|
|
case "arrow":
|
|
default: {
|
|
return generateArrowheadLinesToTip(
|
|
generator,
|
|
getArrowheadPoints(element, shape, position, arrowhead),
|
|
getArrowheadLineOptions(element, options),
|
|
);
|
|
}
|
|
}
|
|
};
|
|
|
|
export const generateLinearCollisionShape = (
|
|
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
|
|
elementsMap: ElementsMap,
|
|
): {
|
|
op: string;
|
|
data: number[];
|
|
}[] => {
|
|
const generator = new RoughGenerator();
|
|
const options: Options = {
|
|
seed: element.seed,
|
|
disableMultiStroke: true,
|
|
disableMultiStrokeFill: true,
|
|
roughness: 0,
|
|
preserveVertices: true,
|
|
};
|
|
const center = elementCenterPoint(element, elementsMap);
|
|
|
|
switch (element.type) {
|
|
case "line":
|
|
case "arrow": {
|
|
// points array can be empty in the beginning, so it is important to add
|
|
// initial position to it
|
|
const points = element.points.length
|
|
? element.points
|
|
: [pointFrom<LocalPoint>(0, 0)];
|
|
|
|
if (isElbowArrow(element)) {
|
|
return generator.path(generateElbowArrowShape(points, 16), options)
|
|
.sets[0].ops;
|
|
} else if (!element.roundness) {
|
|
return points.map((point, idx) => {
|
|
const p = pointRotateRads(
|
|
pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),
|
|
center,
|
|
element.angle,
|
|
);
|
|
|
|
return {
|
|
op: idx === 0 ? "move" : "lineTo",
|
|
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
};
|
|
});
|
|
}
|
|
|
|
return generator
|
|
.curve(points as unknown as RoughPoint[], options)
|
|
.sets[0].ops.slice(0, element.points.length)
|
|
.map((op, i) => {
|
|
if (i === 0) {
|
|
const p = pointRotateRads<GlobalPoint>(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[0],
|
|
element.y + op.data[1],
|
|
),
|
|
center,
|
|
element.angle,
|
|
);
|
|
|
|
return {
|
|
op: "move",
|
|
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
};
|
|
}
|
|
|
|
return {
|
|
op: "bcurveTo",
|
|
data: [
|
|
pointRotateRads(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[0],
|
|
element.y + op.data[1],
|
|
),
|
|
center,
|
|
element.angle,
|
|
),
|
|
pointRotateRads(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[2],
|
|
element.y + op.data[3],
|
|
),
|
|
center,
|
|
element.angle,
|
|
),
|
|
pointRotateRads(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[4],
|
|
element.y + op.data[5],
|
|
),
|
|
center,
|
|
element.angle,
|
|
),
|
|
]
|
|
.map((p) =>
|
|
pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
)
|
|
.flat(),
|
|
};
|
|
});
|
|
}
|
|
case "freedraw": {
|
|
if (element.points.length < 2) {
|
|
return [];
|
|
}
|
|
|
|
const simplifiedPoints = simplify(
|
|
element.points as Mutable<LocalPoint[]>,
|
|
0.75,
|
|
);
|
|
|
|
return generator
|
|
.curve(simplifiedPoints as [number, number][], options)
|
|
.sets[0].ops.slice(0, element.points.length)
|
|
.map((op, i) => {
|
|
if (i === 0) {
|
|
const p = pointRotateRads<GlobalPoint>(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[0],
|
|
element.y + op.data[1],
|
|
),
|
|
center,
|
|
element.angle,
|
|
);
|
|
|
|
return {
|
|
op: "move",
|
|
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
};
|
|
}
|
|
|
|
return {
|
|
op: "bcurveTo",
|
|
data: [
|
|
pointRotateRads(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[0],
|
|
element.y + op.data[1],
|
|
),
|
|
center,
|
|
element.angle,
|
|
),
|
|
pointRotateRads(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[2],
|
|
element.y + op.data[3],
|
|
),
|
|
center,
|
|
element.angle,
|
|
),
|
|
pointRotateRads(
|
|
pointFrom<GlobalPoint>(
|
|
element.x + op.data[4],
|
|
element.y + op.data[5],
|
|
),
|
|
center,
|
|
element.angle,
|
|
),
|
|
]
|
|
.map((p) =>
|
|
pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
)
|
|
.flat(),
|
|
};
|
|
});
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Generates the roughjs shape for given element.
|
|
*
|
|
* Low-level. Use `ShapeCache.generateElementShape` instead.
|
|
*
|
|
* @private
|
|
*/
|
|
const _generateElementShape = (
|
|
element: Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
|
|
generator: RoughGenerator,
|
|
{
|
|
isExporting,
|
|
canvasBackgroundColor,
|
|
embedsValidationStatus,
|
|
theme,
|
|
}: {
|
|
isExporting: boolean;
|
|
canvasBackgroundColor: string;
|
|
embedsValidationStatus: EmbedsValidationStatus | null;
|
|
theme?: AppState["theme"];
|
|
},
|
|
): ElementShape => {
|
|
const isDarkMode = theme === THEME.DARK;
|
|
switch (element.type) {
|
|
case "rectangle":
|
|
case "iframe":
|
|
case "embeddable": {
|
|
let shape: ElementShapes[typeof element.type];
|
|
// this is for rendering the stroke/bg of the embeddable, especially
|
|
// when the src url is not set
|
|
|
|
if (element.roundness) {
|
|
const w = element.width;
|
|
const h = element.height;
|
|
const r = getCornerRadius(Math.min(w, h), element);
|
|
shape = generator.path(
|
|
`M ${r} 0 L ${w - r} 0 Q ${w} 0, ${w} ${r} L ${w} ${
|
|
h - r
|
|
} Q ${w} ${h}, ${w - r} ${h} L ${r} ${h} Q 0 ${h}, 0 ${
|
|
h - r
|
|
} L 0 ${r} Q 0 0, ${r} 0`,
|
|
generateRoughOptions(
|
|
modifyIframeLikeForRoughOptions(
|
|
element,
|
|
isExporting,
|
|
embedsValidationStatus,
|
|
),
|
|
true,
|
|
isDarkMode,
|
|
),
|
|
);
|
|
} else {
|
|
shape = generator.rectangle(
|
|
0,
|
|
0,
|
|
element.width,
|
|
element.height,
|
|
generateRoughOptions(
|
|
modifyIframeLikeForRoughOptions(
|
|
element,
|
|
isExporting,
|
|
embedsValidationStatus,
|
|
),
|
|
false,
|
|
isDarkMode,
|
|
),
|
|
);
|
|
}
|
|
return shape;
|
|
}
|
|
case "diamond": {
|
|
let shape: ElementShapes[typeof element.type];
|
|
|
|
const [topX, topY, rightX, rightY, bottomX, bottomY, leftX, leftY] =
|
|
getDiamondPoints(element);
|
|
if (element.roundness) {
|
|
const verticalRadius = getCornerRadius(Math.abs(topX - leftX), element);
|
|
|
|
const horizontalRadius = getCornerRadius(
|
|
Math.abs(rightY - topY),
|
|
element,
|
|
);
|
|
|
|
shape = generator.path(
|
|
`M ${topX + verticalRadius} ${topY + horizontalRadius} L ${
|
|
rightX - verticalRadius
|
|
} ${rightY - horizontalRadius}
|
|
C ${rightX} ${rightY}, ${rightX} ${rightY}, ${
|
|
rightX - verticalRadius
|
|
} ${rightY + horizontalRadius}
|
|
L ${bottomX + verticalRadius} ${bottomY - horizontalRadius}
|
|
C ${bottomX} ${bottomY}, ${bottomX} ${bottomY}, ${
|
|
bottomX - verticalRadius
|
|
} ${bottomY - horizontalRadius}
|
|
L ${leftX + verticalRadius} ${leftY + horizontalRadius}
|
|
C ${leftX} ${leftY}, ${leftX} ${leftY}, ${leftX + verticalRadius} ${
|
|
leftY - horizontalRadius
|
|
}
|
|
L ${topX - verticalRadius} ${topY + horizontalRadius}
|
|
C ${topX} ${topY}, ${topX} ${topY}, ${topX + verticalRadius} ${
|
|
topY + horizontalRadius
|
|
}`,
|
|
generateRoughOptions(element, true, isDarkMode),
|
|
);
|
|
} else {
|
|
shape = generator.polygon(
|
|
[
|
|
[topX, topY],
|
|
[rightX, rightY],
|
|
[bottomX, bottomY],
|
|
[leftX, leftY],
|
|
],
|
|
generateRoughOptions(element, false, isDarkMode),
|
|
);
|
|
}
|
|
return shape;
|
|
}
|
|
case "ellipse": {
|
|
const shape: ElementShapes[typeof element.type] = generator.ellipse(
|
|
element.width / 2,
|
|
element.height / 2,
|
|
element.width,
|
|
element.height,
|
|
generateRoughOptions(element, false, isDarkMode),
|
|
);
|
|
return shape;
|
|
}
|
|
case "line":
|
|
case "arrow": {
|
|
let shape: ElementShapes[typeof element.type];
|
|
const options = generateRoughOptions(element, false, isDarkMode);
|
|
|
|
// points array can be empty in the beginning, so it is important to add
|
|
// initial position to it
|
|
const points = element.points.length
|
|
? element.points
|
|
: [pointFrom<LocalPoint>(0, 0)];
|
|
|
|
if (isElbowArrow(element)) {
|
|
// NOTE (mtolmacs): Temporary fix for extremely big arrow shapes
|
|
if (
|
|
!points.every(
|
|
(point) => Math.abs(point[0]) <= 1e6 && Math.abs(point[1]) <= 1e6,
|
|
)
|
|
) {
|
|
console.error(
|
|
`Elbow arrow with extreme point positions detected. Arrow not rendered.`,
|
|
element.id,
|
|
JSON.stringify(points),
|
|
);
|
|
shape = [];
|
|
} else {
|
|
shape = [
|
|
generator.path(
|
|
generateElbowArrowShape(points, 16),
|
|
generateRoughOptions(element, true, isDarkMode),
|
|
),
|
|
];
|
|
}
|
|
} else if (!element.roundness) {
|
|
// curve is always the first element
|
|
// this simplifies finding the curve for an element
|
|
if (options.fill) {
|
|
shape = [
|
|
generator.polygon(points as unknown as RoughPoint[], options),
|
|
];
|
|
} else {
|
|
shape = [
|
|
generator.linearPath(points as unknown as RoughPoint[], options),
|
|
];
|
|
}
|
|
} else {
|
|
shape = [generator.curve(points as unknown as RoughPoint[], options)];
|
|
}
|
|
|
|
// add lines only in arrow
|
|
if (element.type === "arrow") {
|
|
const { startArrowhead = null, endArrowhead = "arrow" } = element;
|
|
|
|
if (startArrowhead !== null) {
|
|
const shapes = getArrowheadShapes(
|
|
element,
|
|
shape,
|
|
"start",
|
|
startArrowhead,
|
|
generator,
|
|
options,
|
|
canvasBackgroundColor,
|
|
isDarkMode,
|
|
);
|
|
shape.push(...shapes);
|
|
}
|
|
|
|
if (endArrowhead !== null) {
|
|
if (endArrowhead === undefined) {
|
|
// Hey, we have an old arrow here!
|
|
}
|
|
|
|
const shapes = getArrowheadShapes(
|
|
element,
|
|
shape,
|
|
"end",
|
|
endArrowhead,
|
|
generator,
|
|
options,
|
|
canvasBackgroundColor,
|
|
isDarkMode,
|
|
);
|
|
shape.push(...shapes);
|
|
}
|
|
}
|
|
return shape;
|
|
}
|
|
case "freedraw": {
|
|
// oredered in terms of z-index [background, stroke]
|
|
const shapes: ElementShapes[typeof element.type] = [];
|
|
|
|
// (1) background fill (rc shape), optional
|
|
if (isPathALoop(element.points)) {
|
|
// generate rough polygon to fill freedraw shape
|
|
const simplifiedPoints = simplify(
|
|
element.points as Mutable<LocalPoint[]>,
|
|
0.75,
|
|
);
|
|
shapes.push(
|
|
generator.curve(simplifiedPoints as [number, number][], {
|
|
...generateRoughOptions(element, false, isDarkMode),
|
|
stroke: "none",
|
|
}),
|
|
);
|
|
}
|
|
|
|
// (2) stroke
|
|
shapes.push(getFreeDrawSvgPath(element));
|
|
|
|
return shapes;
|
|
}
|
|
// sticky notes are painted directly (canvas + SVG) from
|
|
// `getStickyNoteRenderPoints`, never through roughjs
|
|
case "stickynote":
|
|
case "frame":
|
|
case "magicframe":
|
|
case "text":
|
|
case "image": {
|
|
const shape: ElementShapes[typeof element.type] = null;
|
|
// we return (and cache) `null` to make sure we don't regenerate
|
|
// `element.canvas` on rerenders
|
|
return shape;
|
|
}
|
|
default: {
|
|
assertNever(
|
|
element,
|
|
`generateElementShape(): Unimplemented type ${(element as any)?.type}`,
|
|
);
|
|
return null;
|
|
}
|
|
}
|
|
};
|
|
|
|
const generateElbowArrowShape = (
|
|
points: readonly LocalPoint[],
|
|
radius: number,
|
|
) => {
|
|
const subpoints = [] as [number, number][];
|
|
for (let i = 1; i < points.length - 1; i += 1) {
|
|
const prev = points[i - 1];
|
|
const next = points[i + 1];
|
|
const point = points[i];
|
|
const prevIsHorizontal = headingForPointIsHorizontal(point, prev);
|
|
const nextIsHorizontal = headingForPointIsHorizontal(next, point);
|
|
const corner = Math.min(
|
|
radius,
|
|
pointDistance(points[i], next) / 2,
|
|
pointDistance(points[i], prev) / 2,
|
|
);
|
|
|
|
if (prevIsHorizontal) {
|
|
if (prev[0] < point[0]) {
|
|
// LEFT
|
|
subpoints.push([points[i][0] - corner, points[i][1]]);
|
|
} else {
|
|
// RIGHT
|
|
subpoints.push([points[i][0] + corner, points[i][1]]);
|
|
}
|
|
} else if (prev[1] < point[1]) {
|
|
// UP
|
|
subpoints.push([points[i][0], points[i][1] - corner]);
|
|
} else {
|
|
subpoints.push([points[i][0], points[i][1] + corner]);
|
|
}
|
|
|
|
subpoints.push(points[i] as [number, number]);
|
|
|
|
if (nextIsHorizontal) {
|
|
if (next[0] < point[0]) {
|
|
// LEFT
|
|
subpoints.push([points[i][0] - corner, points[i][1]]);
|
|
} else {
|
|
// RIGHT
|
|
subpoints.push([points[i][0] + corner, points[i][1]]);
|
|
}
|
|
} else if (next[1] < point[1]) {
|
|
// UP
|
|
subpoints.push([points[i][0], points[i][1] - corner]);
|
|
} else {
|
|
// DOWN
|
|
subpoints.push([points[i][0], points[i][1] + corner]);
|
|
}
|
|
}
|
|
|
|
const d = [`M ${points[0][0]} ${points[0][1]}`];
|
|
for (let i = 0; i < subpoints.length; i += 3) {
|
|
d.push(`L ${subpoints[i][0]} ${subpoints[i][1]}`);
|
|
d.push(
|
|
`Q ${subpoints[i + 1][0]} ${subpoints[i + 1][1]}, ${
|
|
subpoints[i + 2][0]
|
|
} ${subpoints[i + 2][1]}`,
|
|
);
|
|
}
|
|
d.push(`L ${points[points.length - 1][0]} ${points[points.length - 1][1]}`);
|
|
|
|
return d.join(" ");
|
|
};
|
|
|
|
/**
|
|
* get the pure geometric shape of an excalidraw elementw
|
|
* which is then used for hit detection
|
|
*/
|
|
export const getElementShape = <Point extends GlobalPoint | LocalPoint>(
|
|
element: ExcalidrawElement,
|
|
elementsMap: ElementsMap,
|
|
): GeometricShape<Point> => {
|
|
switch (element.type) {
|
|
case "rectangle":
|
|
case "stickynote":
|
|
case "diamond":
|
|
case "frame":
|
|
case "magicframe":
|
|
case "embeddable":
|
|
case "image":
|
|
case "iframe":
|
|
case "text":
|
|
case "selection":
|
|
return getPolygonShape(element);
|
|
case "arrow":
|
|
case "line": {
|
|
const roughShape = ShapeCache.generateElementShape(element, null)[0];
|
|
const [, , , , cx, cy] = getElementAbsoluteCoords(element, elementsMap);
|
|
|
|
return shouldTestInside(element)
|
|
? getClosedCurveShape<Point>(
|
|
element,
|
|
roughShape,
|
|
pointFrom<Point>(element.x, element.y),
|
|
element.angle,
|
|
pointFrom(cx, cy),
|
|
)
|
|
: getCurveShape<Point>(
|
|
roughShape,
|
|
pointFrom<Point>(element.x, element.y),
|
|
element.angle,
|
|
pointFrom(cx, cy),
|
|
);
|
|
}
|
|
|
|
case "ellipse":
|
|
return getEllipseShape(element);
|
|
|
|
case "freedraw": {
|
|
const [, , , , cx, cy] = getElementAbsoluteCoords(element, elementsMap);
|
|
return getFreedrawShape(
|
|
element,
|
|
pointFrom(cx, cy),
|
|
shouldTestInside(element),
|
|
);
|
|
}
|
|
}
|
|
};
|
|
|
|
export const toggleLinePolygonState = (
|
|
element: ExcalidrawLineElement,
|
|
nextPolygonState: boolean,
|
|
): {
|
|
polygon: ExcalidrawLineElement["polygon"];
|
|
points: ExcalidrawLineElement["points"];
|
|
} | null => {
|
|
const updatedPoints = [...element.points];
|
|
|
|
if (nextPolygonState) {
|
|
if (!canBecomePolygon(element.points)) {
|
|
return null;
|
|
}
|
|
|
|
const firstPoint = updatedPoints[0];
|
|
const lastPoint = updatedPoints[updatedPoints.length - 1];
|
|
|
|
const distance = Math.hypot(
|
|
firstPoint[0] - lastPoint[0],
|
|
firstPoint[1] - lastPoint[1],
|
|
);
|
|
|
|
if (
|
|
distance > LINE_POLYGON_POINT_MERGE_DISTANCE ||
|
|
updatedPoints.length < 4
|
|
) {
|
|
updatedPoints.push(pointFrom(firstPoint[0], firstPoint[1]));
|
|
} else {
|
|
updatedPoints[updatedPoints.length - 1] = pointFrom(
|
|
firstPoint[0],
|
|
firstPoint[1],
|
|
);
|
|
}
|
|
}
|
|
|
|
// TODO: satisfies ElementUpdate<ExcalidrawLineElement>
|
|
const ret = {
|
|
polygon: nextPolygonState,
|
|
points: updatedPoints,
|
|
};
|
|
|
|
return ret;
|
|
};
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// freedraw shape helper
|
|
// -----------------------------------------------------------------------------
|
|
|
|
// NOTE not cached (-> for SVG export)
|
|
const getFreeDrawSvgPath = (element: ExcalidrawFreeDrawElement) => {
|
|
return getSvgPathFromStroke(
|
|
getFreedrawOutlinePoints(element),
|
|
) as SVGPathString;
|
|
};
|
|
|
|
/**
|
|
* Freedraw stroke geometry tuning constants.
|
|
*
|
|
* These factors are not derived analytically — they were tuned empirically by
|
|
* visually comparing rendered strokes until they matched the desired feel.
|
|
* Treat them as magic numbers backed by visual verification.
|
|
*/
|
|
const VARIABLE_WIDTH_FREEDRAW = {
|
|
/** Stroke size relative to `strokeWidth` for pressure-sensitive strokes. */
|
|
SIZE_FACTOR: 4.25,
|
|
THINNING: 0.6,
|
|
SMOOTHING: 0.5,
|
|
} as const;
|
|
|
|
const CONSTANT_WIDTH_FREEDRAW = {
|
|
/** Stroke size relative to `strokeWidth` for uniform (laser) strokes. */
|
|
SIZE_FACTOR: 1.4,
|
|
} as const;
|
|
|
|
const getFreedrawStreamline = (element: ExcalidrawFreeDrawElement) =>
|
|
element.strokeOptions?.streamline ?? DEFAULT_STROKE_STREAMLINE;
|
|
|
|
/**
|
|
* Pressure-sensitive (variable width) freedraw outline, rendered with
|
|
* perfect-freehand. This is the original Excalidraw freedraw look.
|
|
*/
|
|
const getVariableWidthFreedrawOutline = (
|
|
element: ExcalidrawFreeDrawElement,
|
|
): [number, number][] => {
|
|
// If input points are empty (should they ever be?) return a dot
|
|
const inputPoints = element.simulatePressure
|
|
? element.points
|
|
: element.points.length
|
|
? element.points.map(
|
|
([x, y], i) => [x, y, element.pressures[i]] as [number, number, number],
|
|
)
|
|
: [[0, 0, 0.5]];
|
|
|
|
return getStroke(inputPoints as number[][], {
|
|
simulatePressure: element.simulatePressure,
|
|
size: element.strokeWidth * VARIABLE_WIDTH_FREEDRAW.SIZE_FACTOR,
|
|
thinning: VARIABLE_WIDTH_FREEDRAW.THINNING,
|
|
smoothing: VARIABLE_WIDTH_FREEDRAW.SMOOTHING,
|
|
streamline: getFreedrawStreamline(element),
|
|
easing: (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine
|
|
last: true,
|
|
}) as [number, number][];
|
|
};
|
|
|
|
const createLaserPointer = (element: ExcalidrawFreeDrawElement) =>
|
|
new LaserPointer({
|
|
size: element.strokeWidth * CONSTANT_WIDTH_FREEDRAW.SIZE_FACTOR,
|
|
streamline: getFreedrawStreamline(element),
|
|
simplify: 0,
|
|
sizeMapping: (details) => Math.max(0.1, details.pressure),
|
|
});
|
|
|
|
/**
|
|
* Uniform (constant width) freedraw outline, rendered with the laser-pointer
|
|
* geometry. Pressure is pinned to 1 so the stroke keeps a constant width.
|
|
*/
|
|
const getConstantWidthFreedrawOutline = (
|
|
element: ExcalidrawFreeDrawElement,
|
|
): [number, number][] => {
|
|
const laserPointer = createLaserPointer(element);
|
|
element.points.map(([x, y]) => laserPointer.addPoint([x, y, 1]));
|
|
|
|
return laserPointer
|
|
.getStrokeOutline()
|
|
.map(([x, y]) => [x, y] as [number, number]);
|
|
};
|
|
|
|
export const getFreedrawOutlinePoints = (
|
|
element: ExcalidrawFreeDrawElement,
|
|
): [number, number][] => {
|
|
// Unknown/absent variability falls back to the original variable rendering.
|
|
return element.strokeOptions?.variability === "constant"
|
|
? getConstantWidthFreedrawOutline(element)
|
|
: getVariableWidthFreedrawOutline(element);
|
|
};
|
|
|
|
/**
|
|
* The streamline-smoothed centerline the freedraw stroke is rendered
|
|
* around, in element-local coordinates. Boundary-sensitive consumers (e.g.
|
|
* bucket fill) should use this instead of `element.points`: raw input
|
|
* points can sit 20px+ apart and the rendered stroke is smoothed between
|
|
* them, so raw chords visibly deviate from what's on screen.
|
|
*
|
|
* Constant-width ("laser geometry") strokes technically smooth via
|
|
* `LaserPointer` instead; the perfect-freehand centerline with the same
|
|
* `streamline` is a close approximation the stroke width hides.
|
|
*/
|
|
export const getFreedrawStrokeCenterPoints = (
|
|
element: ExcalidrawFreeDrawElement,
|
|
): [number, number][] =>
|
|
getStrokePoints(element.points as unknown as number[][], {
|
|
size: element.strokeWidth * VARIABLE_WIDTH_FREEDRAW.SIZE_FACTOR,
|
|
streamline: getFreedrawStreamline(element),
|
|
last: true,
|
|
}).map((strokePoint) => strokePoint.point as [number, number]);
|
|
|
|
const med = (A: number[], B: number[]) => {
|
|
return [(A[0] + B[0]) / 2, (A[1] + B[1]) / 2];
|
|
};
|
|
|
|
// Trim SVG path data so number are each two decimal points. This
|
|
// improves SVG exports, and prevents rendering errors on points
|
|
// with long decimals.
|
|
const TO_FIXED_PRECISION = /(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g;
|
|
|
|
const getSvgPathFromStroke = (points: number[][]): string => {
|
|
if (!points.length) {
|
|
return "";
|
|
}
|
|
|
|
const max = points.length - 1;
|
|
|
|
return points
|
|
.reduce(
|
|
(acc, point, i, arr) => {
|
|
if (i === max) {
|
|
acc.push(point, med(point, arr[0]), "L", arr[0], "Z");
|
|
} else {
|
|
acc.push(point, med(point, arr[i + 1]));
|
|
}
|
|
return acc;
|
|
},
|
|
["M", points[0], "Q"],
|
|
)
|
|
.join(" ")
|
|
.replace(TO_FIXED_PRECISION, "$1");
|
|
};
|
|
|
|
// -----------------------------------------------------------------------------
|