Virtual whiteboard for sketching hand-drawn like diagrams
feat(editor): bucket fill (#11799)
David Luzar792ea3a06c60
diff --git a/packages/common/src/colors.ts b/packages/common/src/colors.tsindex f6bced8b67..e0f1d600cf 100644--- a/packages/common/src/colors.ts+++ b/packages/common/src/colors.ts@@ -202,6 +202,17 @@ export const DEFAULT_ELEMENT_BACKGROUND_PICKS = [COLOR_PALETTE.yellow[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX],] as ColorTuple;+// ORDER matters for positioning in quick picker.+// Same as element background picks, with `transparent` (a no-op fill for the+// bucket tool) swapped for white.+export const BUCKET_FILL_BACKGROUND_PICKS = [+ COLOR_PALETTE.white,+ COLOR_PALETTE.red[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX],+ COLOR_PALETTE.green[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX],+ COLOR_PALETTE.blue[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX],+ COLOR_PALETTE.yellow[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX],+] as ColorTuple;+// ORDER matters for positioning in quick pickerexport const DEFAULT_CANVAS_BACKGROUND_PICKS = [COLOR_PALETTE.white,@@ -240,6 +251,17 @@ export const DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE = {...COMMON_ELEMENT_SHADES,} as const;+/**+ * The color the bucket fill tool actually fills with: the shared+ * `currentItemBackgroundColor`, falling back to green when that is+ * transparent (the tool's picker doesn't offer transparent, but the shared+ * state can hold it from the generic shape picker).+ */+export const getBucketFillBackgroundColor = (backgroundColor: string) =>+ isTransparent(backgroundColor)+ ? COLOR_PALETTE.green[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX]+ : backgroundColor;+// color palette helpers// -----------------------------------------------------------------------------@@ -299,6 +321,17 @@ export const isTransparent = (color: string) => {return tinycolor(color).getAlpha() === 0;};+/**+ * Whether the color is fully opaque (alpha exactly 1).+ *+ * NOT the negation of `isTransparent`, which is true only at alpha 0 — a+ * partial-alpha color (`#RRGGBBAA`, `rgba(…, 0.5)`) is neither transparent+ * (it renders) nor opaque (what's beneath shows through it).+ */+export const isOpaqueColor = (color: string) => {+ return tinycolor(color).getAlpha() === 1;+};+// -----------------------------------------------------------------------------// color contract helpers// -----------------------------------------------------------------------------diff --git a/packages/common/src/constants.ts b/packages/common/src/constants.tsindex b9916b0174..a9ee944df9 100644--- a/packages/common/src/constants.ts+++ b/packages/common/src/constants.ts@@ -500,6 +500,7 @@ export const TOOL_TYPE = {embeddable: "embeddable",laser: "laser",autoshape: "autoshape",+ bucketfill: "bucketfill",} as const;export const EDITOR_LS_KEYS = {diff --git a/packages/common/src/keys.ts b/packages/common/src/keys.tsindex 1db356b7ec..ac4cabe1ff 100644--- a/packages/common/src/keys.ts+++ b/packages/common/src/keys.ts@@ -51,6 +51,7 @@ export const KEYS = {SLASH: "/",A: "a",+ B: "b",C: "c",D: "d",E: "e",diff --git a/packages/element/src/bucketFill.ts b/packages/element/src/bucketFill.tsnew file mode 100644index 0000000000..11837168b1--- /dev/null+++ b/packages/element/src/bucketFill.ts@@ -0,0 +1,1918 @@+import { pointsOnBezierCurves, simplify } from "points-on-curve";+import { curveToBezier } from "points-on-curve/lib/curve-to-bezier";++import {+ distanceToLineSegment,+ lineSegment,+ lineSegmentIntersectionPoints,+ pointDistance,+ pointFrom,+ pointRotateRads,+ polygonArea,+ polygonIncludesPoint,+ polygonIncludesPointNonZero,+ polygonSignedArea,+} from "@excalidraw/math";++import { isOpaqueColor, isTransparent } from "@excalidraw/common";++import type { Bounds } from "@excalidraw/common";+import type {+ GlobalPoint,+ LineSegment,+ LocalPoint,+ Polygon,+} from "@excalidraw/math";++import {+ doBoundsIntersect,+ elementCenterPoint,+ getBoundsFromPoints,+ getElementBounds,+ getElementLineSegments,+} from "./bounds";+import { intersectElementWithLineSegment, isPointInElement } from "./collision";+import { hasBackground } from "./comparisons";+import { distanceToElement } from "./distance";+import { getFreedrawStrokeCenterPoints } from "./shape";+import {+ isFreeDrawElement,+ isLinearElement,+ isLineElement,+ isValidPolygon,+} from "./typeChecks";+import { isPathALoop } from "./utils";++import type { Point } from "points-on-curve";++import type {+ ElementsMap,+ ExcalidrawElement,+ ExcalidrawFreeDrawElement,+ ExcalidrawLineElement,+ NonDeletedExcalidrawElement,+} from "./types";++/**+ * Pure geometry helpers for the bucket fill tool.+ *+ * Given a click point and the scene elements, this computes the closed polygon+ * (in scene/global coordinates) that fills the enclosed region under the+ * pointer. The Excalidraw app layer converts the returned `scenePoints` into a+ * local `line` polygon and inserts it.+ *+ * All fills go through a single path: a planar segment arrangement is built+ * (segments split at intersections) and the smallest bounded face containing+ * the click is selected.+ *+ * The OWNER is the topmost closed, visible element containing the click+ * point — a shape, a closed (`polygon`) line, or a looped freedraw. It is+ * not the fill's boundary per se; it anchors the fast common case: only+ * elements near the owner's bounds feed the arrangement, and the app layer+ * inherits the fill's frame/group membership from it. When no owner exists+ * (regions formed by open lines, including against other elements' outside+ * walls), candidates come from an expanding search box around the click+ * instead — the owner-less fallback. Fill-compatible paint (see+ * `isBucketFillCompatible`) never becomes an owner: clicking it restyles+ * the existing paint (app layer) or re-derives the region from the actual+ * strokes around it.+ *+ * Islands (disconnected outlines fully inside the selected region) become+ * holes: their contours are spliced into the returned ring as zero-width+ * "keyhole" bridges, so the result stays a single closed polygon that+ * renders with unpainted hole interiors. Looped-line fills are painted with+ * the even-odd rule (roughjs uses it for solid polygon/curve fills and the+ * SVG export sets `fill-rule="evenodd"` explicitly; pattern fills use+ * scanline parity, which behaves the same) — the doubled bridge edges+ * cancel under it. Holes are nonetheless spliced with opposite winding, so+ * the path stays correct under the nonzero rule too.+ */++/**+ * How big a visual gap between strokes still counts as closed, in scene px.+ *+ * This is a BRIDGING radius, not a snapping radius: gaps are closed by+ * adding short connector edges between loose stroke ends (see the bridging+ * pass in `buildFaces`), never by relocating vertices — so a generous value+ * here does not distort the filled shape.+ */+const BUCKET_FILL_GAP_TOLERANCE = 6;++/**+ * How far apart, in scene px, two fill outlines' bounds may lie and still+ * count as the same region (see `findRestylableBucketFill`). Covers the+ * pipeline's own jitter — polygon simplification (~0.75px) and node+ * canonicalization (`snapEpsilon`) — while staying under typical stroke+ * widths, so "the same region" matches what the user sees.+ */+const BUCKET_FILL_REGION_MATCH_TOLERANCE = 2;++/**+ * How deep inside a coverer, in scene px, a stroke must lie before it counts+ * as hidden (see `clipSegmentToVisible`). A fill's polygon runs along the+ * CENTERLINE of the strokes that bound it, so without a margin the fill —+ * itself a coverer — would clip its own boundary strokes on the next click+ * and adjacent regions would merge. A stroke on a coverer's edge still+ * renders its outer half; only strokes buried deeper than this stay clipped.+ * Sized like `BUCKET_FILL_REGION_MATCH_TOLERANCE`: above the pipeline's own+ * jitter (~0.75px simplification + `snapEpsilon`), below typical visible+ * stroke overlaps.+ */+const BUCKET_FILL_COVER_MARGIN = 2;++/**+ * Max deviation, in scene px, of a curved (`roundness`) line's sampled+ * boundary from its true rendered curve (see `lineElementIdealSegments`).+ * The fidelity knob for fills along curved lines: lower hugs the curve+ * tighter but feeds more segments into the arrangement — cost grows roughly+ * linearly with segment count.+ *+ * Note the final polygon is independently simplified at ~0.75px+ * (`finalizePolygon`), so values much below that add segments without+ * adding visible fidelity.+ */+const BUCKET_FILL_CURVE_MAX_DEVIATION = 0.5;++export type BucketFillOptions = {+ /**+ * geometric fidelity: vertices closer than this collapse to the same graph+ * node, and a node this close to a stroke splits it (T-junction). Keep+ * SMALL — every merge can relocate a vertex by up to this distance, so+ * this value is the upper bound on how far the filled shape may deviate+ * from the actual strokes.+ */+ snapEpsilon: number;+ /**+ * connectivity: loose stroke ends within this distance of another stroke+ * are bridged with a connector edge so the region reads as closed. Also+ * used as broad-phase padding around the owner bounds. Unlike+ * `snapEpsilon` this does not affect the shape's fidelity (bridges add+ * edges; they never move existing vertices).+ */+ gapTolerance: number;+ /** discard faces / polygons smaller than this absolute area */+ minArea: number;+ /** bail out with `too_complex` above this many input segments */+ maxBoundarySegments: number;+ /** cap on the number of generated polygon points */+ maxGeneratedPoints: number;+ /**+ * initial half-extent of the owner-less search box around the click+ * (doubles up to 3 times while the found face touches the box frontier)+ */+ fallbackSearchRadius: number;+};++export const DEFAULT_BUCKET_FILL_OPTIONS: BucketFillOptions = {+ snapEpsilon: 0.5,+ gapTolerance: BUCKET_FILL_GAP_TOLERANCE,+ minArea: 4,+ maxBoundarySegments: 2560,+ maxGeneratedPoints: 1536,+ fallbackSearchRadius: 512,+};++export type BucketFillFailureReason =+ | "no_owner"+ | "open_region"+ | "too_complex"+ | "too_small"+ | "invalid_polygon";++/**+ * Where the generated fill element belongs in the scene order, expressed+ * relative to an existing element so the caller can resolve it against+ * whatever (e.g. deleted-inclusive) array it inserts into.+ */+export type BucketFillInsertion = {+ placement: "above" | "below";+ elementId: ExcalidrawElement["id"];+};++export type BucketFillGeometryResult =+ | {+ ok: true;+ /**+ * the closed element under the click, or null for fills resolved by+ * the owner-less fallback (regions formed by open lines)+ */+ ownerId: ExcalidrawElement["id"] | null;+ boundaryElementIds: ExcalidrawElement["id"][];+ /**+ * closed polygon ring in scene coordinates. When the region contains+ * islands, this is a keyhole path: the hole contours are spliced in+ * via zero-width bridges, so it still renders as one polygon with+ * unpainted hole interiors+ */+ scenePoints: GlobalPoint[];+ insertion: BucketFillInsertion;+ }+ | {+ ok: false;+ reason: BucketFillFailureReason;+ };++// -----------------------------------------------------------------------------+// small geometry helpers+// -----------------------------------------------------------------------------++const expandBounds = ([x1, y1, x2, y2]: Bounds, pad: number): Bounds => [+ x1 - pad,+ y1 - pad,+ x2 + pad,+ y2 + pad,+];++const segmentLength = (s: LineSegment<GlobalPoint>): number =>+ pointDistance(s[0], s[1]);++/** Parametric position of `q` projected onto the line through a-b. */+const projectParam = (+ a: GlobalPoint,+ b: GlobalPoint,+ q: GlobalPoint,+): number => {+ const dx = b[0] - a[0];+ const dy = b[1] - a[1];+ const len2 = dx * dx + dy * dy;+ if (len2 === 0) {+ return 0;+ }+ return ((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / len2;+};++/**+ * Visit every grid cell (of `cellSize`) that intersects the `inflate`-expanded+ * segment a-b, walking column by column so a long diagonal segment visits the+ * cells it passes near rather than its full bounding box.+ */+const forEachCellAlongSegment = (+ a: GlobalPoint,+ b: GlobalPoint,+ inflate: number,+ cellSize: number,+ visit: (cx: number, cy: number) => void,+): void => {+ const minX = Math.min(a[0], b[0]);+ const maxX = Math.max(a[0], b[0]);+ const dx = b[0] - a[0];+ const dy = b[1] - a[1];+ const fromCx = Math.floor((minX - inflate) / cellSize);+ const toCx = Math.floor((maxX + inflate) / cellSize);+ for (let cx = fromCx; cx <= toCx; cx++) {+ // y-extent of the segment over this column's (inflated) x-interval+ let y0 = a[1];+ let y1 = b[1];+ if (dx !== 0) {+ const t0 = (Math.max(minX, cx * cellSize - inflate) - a[0]) / dx;+ const t1 = (Math.min(maxX, (cx + 1) * cellSize + inflate) - a[0]) / dx;+ y0 = a[1] + t0 * dy;+ y1 = a[1] + t1 * dy;+ }+ const fromCy = Math.floor((Math.min(y0, y1) - inflate) / cellSize);+ const toCy = Math.floor((Math.max(y0, y1) + inflate) / cellSize);+ for (let cy = fromCy; cy <= toCy; cy++) {+ visit(cx, cy);+ }+ }+};++const perpendicularDistance = (+ p: GlobalPoint,+ a: GlobalPoint,+ b: GlobalPoint,+): number => {+ const dx = b[0] - a[0];+ const dy = b[1] - a[1];+ const len = Math.hypot(dx, dy);+ if (len === 0) {+ return pointDistance(p, a);+ }+ return Math.abs((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / len;+};++const pointAtParam = (a: GlobalPoint, b: GlobalPoint, t: number): GlobalPoint =>+ pointFrom<GlobalPoint>(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t);++/** Remove the `cuts` parameter intervals from the `base` parameter intervals. */+const subtractIntervals = (+ base: [number, number][],+ cuts: [number, number][],+): [number, number][] => {+ let result = base;+ for (const [c0, c1] of cuts) {+ const next: [number, number][] = [];+ for (const [b0, b1] of result) {+ if (c1 <= b0 || c0 >= b1) {+ next.push([b0, b1]);+ continue;+ }+ if (c0 > b0) {+ next.push([b0, c0]);+ }+ if (c1 < b1) {+ next.push([c1, b1]);+ }+ }+ result = next;+ }+ return result;+};++/**+ * Boundary segments for a line element from its LOGICAL path (the element's+ * points), not its rough rendering.+ *+ * Rough rendering draws lines as two jittery passes; using those as+ * boundaries makes the fill hug the inner pass and leaves an unfilled+ * sliver between the passes. The logical path runs down the stroke's+ * centerline, so the fill straddles the sketchy stroke — exactly how+ * Excalidraw draws shape backgrounds (fill from the ideal path, rough+ * stroke on top). It also makes line endpoints genuine degree-1 graph+ * nodes, which is what the bridging pass keys on.+ *+ * Curved (`roundness`) lines deviate slightly at bends since the points are+ * the pre-smoothing polyline; the stroke width hides it.+ */+const lineElementIdealSegments = (+ element: ExcalidrawLineElement,+ elementsMap: ElementsMap,+): LineSegment<GlobalPoint>[] => {+ const center = elementCenterPoint(element, elementsMap);+ // curved (`roundness`) lines render a smooth curve fitted through the+ // points — sample that same fit (curveToBezier is what roughjs' curve op+ // uses) so the boundary follows what's actually on screen instead of+ // cutting corners along the raw polyline+ const localPoints =+ element.roundness && element.points.length > 2+ ? (pointsOnBezierCurves(+ curveToBezier(element.points as unknown as Point[]),+ // near-exact adaptive subdivision (the lib default); the sample+ // count is then bounded by the RDP pass below, which is the+ // actual fidelity knob+ 0.15,+ BUCKET_FILL_CURVE_MAX_DEVIATION,+ ) as unknown as readonly LocalPoint[])+ : element.points;+ const points = localPoints.map((point) =>+ pointRotateRads(+ pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),+ center,+ element.angle,+ ),+ );+ const segments: LineSegment<GlobalPoint>[] = [];+ for (let i = 0; i < points.length - 1; i++) {+ segments.push(lineSegment(points[i], points[i + 1]));+ }+ return segments;+};++/**+ * Boundary segments for a freedraw element from its RENDERED centerline+ * (perfect-freehand's streamline-smoothed stroke points), not its raw+ * input points.+ *+ * Raw freedraw points can sit 20px+ apart and the renderer smooths the+ * path between them, so raw chords visibly deviate from the stroke on+ * screen: fills poke out at raw vertices, slivers open along sagging+ * chords, and closures that only exist in the smoothed path (the stroke+ * crossing itself near its start) are missed entirely.+ */+const freedrawIdealSegments = (+ element: ExcalidrawFreeDrawElement,+ elementsMap: ElementsMap,+): LineSegment<GlobalPoint>[] => {+ const center = elementCenterPoint(element, elementsMap);+ const points = getFreedrawStrokeCenterPoints(element).map((point) =>+ pointRotateRads(+ pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),+ center,+ element.angle,+ ),+ );+ const segments: LineSegment<GlobalPoint>[] = [];+ for (let i = 0; i < points.length - 1; i++) {+ segments.push(lineSegment(points[i], points[i + 1]));+ }+ return segments;+};++/**+ * Clip a segment to only its visible parts: the portions covered by an opaque+ * (non-transparent background) element above the segment's source are hidden+ * and removed. Returns the visible sub-segments (possibly empty).+ *+ * A portion only counts as covered when it lies inside the coverer by at+ * least `margin` — a stroke whose centerline sits ON a coverer's edge (the+ * shape a fill bounded by that stroke takes) still renders its outer half,+ * so it must keep bounding; see `BUCKET_FILL_COVER_MARGIN`.+ */+const clipSegmentToVisible = (+ a: GlobalPoint,+ b: GlobalPoint,+ coverers: readonly ExcalidrawElement[],+ elementsMap: ElementsMap,+ eps: number,+ margin: number,+): [GlobalPoint, GlobalPoint][] => {+ let intervals: [number, number][] = [[0, 1]];+ for (const coverer of coverers) {+ if (intervals.length === 0) {+ break;+ }+ const hits = intersectElementWithLineSegment(+ coverer,+ elementsMap,+ lineSegment(a, b),+ );+ const breaks = [+ 0,+ ...hits+ .map((p) => projectParam(a, b, p))+ .filter((t) => t > 0 && t < 1)+ .sort((x, y) => x - y),+ 1,+ ];+ const covered: [number, number][] = [];+ for (let k = 0; k < breaks.length - 1; k++) {+ const t0 = breaks[k];+ const t1 = breaks[k + 1];+ if (t1 - t0 < 1e-9) {+ continue;+ }+ const mid = pointAtParam(a, b, (t0 + t1) / 2);+ if (+ isPointInElement(mid, coverer, elementsMap) &&+ distanceToElement(coverer, elementsMap, mid) > margin+ ) {+ covered.push([t0, t1]);+ }+ }+ if (covered.length) {+ intervals = subtractIntervals(intervals, covered);+ }+ }+ return intervals+ .filter(+ ([t0, t1]) =>+ pointDistance(pointAtParam(a, b, t0), pointAtParam(a, b, t1)) >= eps,+ )+ .map(([t0, t1]) => [pointAtParam(a, b, t0), pointAtParam(a, b, t1)]);+};++/**+ * Spatial-hash node store that merges points within `eps` into one node so the+ * planar graph is free of near-duplicate vertices.+ */+class NodeStore {+ nodes: GlobalPoint[] = [];++ private cells = new Map<string, number[]>();++ private cellSize: number;++ constructor(private eps: number) {+ this.cellSize = Math.max(eps, 1);+ }++ private cellKey(cx: number, cy: number): string {+ return `${cx}:${cy}`;+ }++ getOrCreate(p: GlobalPoint): number {+ const cx = Math.floor(p[0] / this.cellSize);+ const cy = Math.floor(p[1] / this.cellSize);+ for (let dx = -1; dx <= 1; dx++) {+ for (let dy = -1; dy <= 1; dy++) {+ const bucket = this.cells.get(this.cellKey(cx + dx, cy + dy));+ if (bucket) {+ for (const idx of bucket) {+ if (pointDistance(this.nodes[idx], p) <= this.eps) {+ return idx;+ }+ }+ }+ }+ }+ const idx = this.nodes.length;+ this.nodes.push(p);+ const key = this.cellKey(cx, cy);+ const bucket = this.cells.get(key);+ if (bucket) {+ bucket.push(idx);+ } else {+ this.cells.set(key, [idx]);+ }+ return idx;+ }++ /**+ * Visit the indices of all nodes within `radius` of `p`. Superset by cell+ * granularity — nodes slightly beyond `radius` may be visited too, so+ * callers must check distances themselves.+ */+ forEachInRadius(+ p: GlobalPoint,+ radius: number,+ visit: (index: number) => void,+ ): void {+ const fromCx = Math.floor((p[0] - radius) / this.cellSize);+ const toCx = Math.floor((p[0] + radius) / this.cellSize);+ const fromCy = Math.floor((p[1] - radius) / this.cellSize);+ const toCy = Math.floor((p[1] + radius) / this.cellSize);+ for (let cx = fromCx; cx <= toCx; cx++) {+ for (let cy = fromCy; cy <= toCy; cy++) {+ const bucket = this.cells.get(this.cellKey(cx, cy));+ if (bucket) {+ for (const index of bucket) {+ visit(index);+ }+ }+ }+ }+ }+}++// -----------------------------------------------------------------------------+// owner & boundary selection+// -----------------------------------------------------------------------------++/**+ * Whether the element visually paints an opaque background fill — i.e. can+ * actually hide outlines beneath it. Element types that never render their+ * `backgroundColor` (text, image, frames), see-through fill styles+ * (hachure/cross-hatch), partial element opacity, and colors with an alpha+ * channel below 1 (`#RRGGBBAA`, `rgba(…)`) all don't count — anything under+ * them shows through.+ *+ * Shared with the app layer's z-order pass so "covers" means the same thing+ * in boundary clipping and in fill insertion.+ */+export const rendersOpaqueFill = (element: ExcalidrawElement): boolean => {+ if (+ !hasBackground(element.type) ||+ element.fillStyle !== "solid" ||+ element.opacity < 100 ||+ !isOpaqueColor(element.backgroundColor)+ ) {+ return false;+ }+ // open strokes never paint their background+ if (+ (isLineElement(element) || isFreeDrawElement(element)) &&+ !isPathALoop(element.points)+ ) {+ return false;+ }+ return true;+};++/**+ * Element types whose outlines can participate in a fill — as the owner+ * (when closed) and as boundaries. Text, image, embeddable, iframe and+ * arrows are excluded in v1.+ */+const FILL_BOUNDARY_TYPES = new Set<ExcalidrawElement["type"]>([+ "rectangle",+ "diamond",+ "ellipse",+ "frame",+ "magicframe",+ "line",+ "freedraw",+]);++/** fully invisible elements never participate in a fill */+const isInvisible = (element: ExcalidrawElement): boolean =>+ element.opacity <= 0;++/**+ * Whether the element renders any pixels at all: a visible stroke (doubles+ * as the text color for text elements), a background its type actually+ * paints, or image content.+ */+const rendersAnyMark = (element: ExcalidrawElement): boolean =>+ !isInvisible(element) &&+ (element.type === "image" ||+ !isTransparent(element.strokeColor) ||+ (hasBackground(element.type) && !isTransparent(element.backgroundColor)));++/**+ * Whether the element renders as pure paint the bucket tool could have+ * produced: a closed, visible line polygon with a background and no visible+ * stroke. Recognition is by SHAPE, not by a metadata marker — any marker+ * would go stale the moment the user restyles a fill, and a hand-drawn+ * strokeless background polygon is indistinguishable from a generated fill+ * anyway. Such paint never becomes an owner and is what the app layer+ * restyles in place on re-click (see `isRestylableFill`).+ */+export const isBucketFillCompatible = (+ element: ExcalidrawElement,+): element is ExcalidrawLineElement =>+ isLineElement(element) &&+ element.polygon &&+ isValidPolygon(element.points) &&+ !isInvisible(element) &&+ !isTransparent(element.backgroundColor) &&+ isTransparent(element.strokeColor);++const isClosedOwnerCandidate = (element: ExcalidrawElement): boolean => {+ if (!FILL_BOUNDARY_TYPES.has(element.type)) {+ return false;+ }+ if (isLineElement(element)) {+ return element.polygon && isValidPolygon(element.points);+ }+ if (isFreeDrawElement(element)) {+ return isPathALoop(element.points);+ }+ return true;+};++// Boundary and coverer roles are decided by VISIBILITY, not provenance:+// generated fills participate like any other element. In practice their+// default transparent stroke keeps them out of the boundary set — but once+// the user gives a fill a visible stroke, that outline genuinely bounds+// regions on screen and must bound new fills too.+const isEligibleBoundary = (element: ExcalidrawElement): boolean =>+ !isInvisible(element) &&+ FILL_BOUNDARY_TYPES.has(element.type) &&+ // skip outlines that don't render a visible stroke+ !isTransparent(element.strokeColor);++const findOwner = (+ point: GlobalPoint,+ elements: readonly NonDeletedExcalidrawElement[],+ elementsMap: ElementsMap,+): NonDeletedExcalidrawElement | null => {+ for (let i = elements.length - 1; i >= 0; i--) {+ const element = elements[i];+ // fill-compatible paint is deliberately never an OWNER (unlike its+ // boundary / coverer roles): re-clicking a filled region should either+ // restyle the paint (app layer) or re-derive the region from the+ // actual strokes, not from the previous fill's ring — and keyhole+ // rings (zero-width bridges) make degenerate owner outlines.+ // Elements that render no pixels can't own either — an invisible+ // (transparent stroke + transparent background) shape would otherwise+ // let a click on seemingly empty canvas conjure a fill out of nowhere.+ if (!rendersAnyMark(element) || isBucketFillCompatible(element)) {+ continue;+ }+ if (!isClosedOwnerCandidate(element)) {+ continue;+ }+ if (isPointInElement(point, element, elementsMap)) {+ return element;+ }+ }+ return null;+};++// -----------------------------------------------------------------------------+// planar arrangement + face extraction+// -----------------------------------------------------------------------------++type WorkingSegment = {+ a: number;+ b: number;+ pa: GlobalPoint;+ pb: GlobalPoint;+ box: Bounds;+ elementId: string;+ splits: { node: number; t: number }[];+};++/** A segment paired with the element it was extracted from. */+type SourceSegment = {+ segment: LineSegment<GlobalPoint>;+ elementId: string;+};++/** An extracted face ring plus the ids of the elements whose outlines bound it. */+type Face = {+ ring: GlobalPoint[];+ contributors: Set<string>;+ /**+ * connected component of the arrangement graph this face belongs to —+ * faces of OTHER components lying inside a selected face are islands+ * (holes), while faces of the same component are just its subdivisions+ */+ componentId: number;+};++/**+ * Build the planar straight-line graph from the input segments (split at+ * intersections and T-junctions) and extract its face rings. Each face records+ * which source elements contributed an edge to its boundary.+ *+ * Returns `[]` when there are no usable edges (no enclosed region), or `null`+ * when the arrangement is too complex to process.+ *+ * Collinear/overlapping segments need no dedicated pass: a 1D overlap always+ * puts at least one segment's endpoint (a node) on the other segment, so the+ * T-junction pass splits them and `addEdge`'s node-pair dedupe collapses the+ * coincident pieces into one edge.+ */+const buildFaces = (+ rawSegments: SourceSegment[],+ options: BucketFillOptions,+): Face[] | null => {+ const eps = options.snapEpsilon;+ // Two distinct radii, deliberately decoupled:+ // - `eps` (snapEpsilon) governs node merging and T-junction snapping. It+ // must stay small: merging RELOCATES vertices to the first-seen position+ // and T-junctions route edges THROUGH off-stroke nodes, so this radius+ // is the upper bound on how far the filled shape can deviate from the+ // actual strokes.+ // - `gapTolerance` governs the bridging pass further down, which closes+ // visual gaps by ADDING short connector edges at loose stroke ends. It+ // can be generous (see BUCKET_FILL_GAP_TOLERANCE) without distorting+ // the shape, because bridging never moves existing vertices.+ const store = new NodeStore(eps);+ const segments: WorkingSegment[] = [];+ // first element that produced each node — used to attribute bridge edges+ const nodeElement = new Map<number, string>();++ for (const { segment, elementId } of rawSegments) {+ // NOTE: sub-epsilon segments are NOT dropped here — their endpoints merge+ // into the same node (a === b below) which collapses them while keeping+ // the outline chain connected. Dropping them instead would disconnect+ // densely subdivided curves (e.g. the tiny corner arcs a diamond has even+ // with roundness: null) and leave the region open.+ const a = store.getOrCreate(segment[0]);+ const b = store.getOrCreate(segment[1]);+ if (!nodeElement.has(a)) {+ nodeElement.set(a, elementId);+ }+ if (!nodeElement.has(b)) {+ nodeElement.set(b, elementId);+ }+ if (a === b) {+ continue;+ }+ const pa = store.nodes[a];+ const pb = store.nodes[b];+ segments.push({+ a,+ b,+ pa,+ pb,+ elementId,+ box: [+ Math.min(pa[0], pb[0]),+ Math.min(pa[1], pb[1]),+ Math.max(pa[0], pb[0]),+ Math.max(pa[1], pb[1]),+ ],+ splits: [+ { node: a, t: 0 },+ { node: b, t: 1 },+ ],+ });+ }++ const segLines = segments.map((s) => lineSegment(s.pa, s.pb));++ // transversal intersections. Broad phase: sort by bbox minX and sweep, so+ // every candidate pair is tested at most once. A segment grid is a poor fit+ // here: dense overlapping segments share many consecutive cells, and even+ // deduping the geometry test still re-enumerates every pair in every cell.+ const byMinX = segments+ .map((_, index) => index)+ .sort((a, b) => segments[a].box[0] - segments[b].box[0]);+ for (let oi = 0; oi < byMinX.length; oi++) {+ const i = byMinX[oi];+ const si = segments[i];+ const sweepMaxX = si.box[2] + eps;+ for (let oj = oi + 1; oj < byMinX.length; oj++) {+ const j = byMinX[oj];+ const sj = segments[j];+ if (sj.box[0] > sweepMaxX) {+ break;+ }+ if (!doBoundsIntersect(expandBounds(si.box, eps), sj.box)) {+ continue;+ }+ const intersection = lineSegmentIntersectionPoints(+ segLines[i],+ segLines[j],+ eps,+ );+ if (!intersection) {+ continue;+ }+ const node = store.getOrCreate(intersection);+ // intersection nodes need a source too — one may end up a loose end+ // (after visibility clipping) and get bridged, and bridge attribution+ // reads `nodeElement`+ if (!nodeElement.has(node)) {+ nodeElement.set(node, si.elementId);+ }+ si.splits.push({+ node,+ t: projectParam(si.pa, si.pb, store.nodes[node]),+ });+ sj.splits.push({+ node,+ t: projectParam(sj.pa, sj.pb, store.nodes[node]),+ });+ }+ }++ // safety: intersection splitting can inflate the node count quadratically+ // in pathological scenes; bail before the downstream passes (T-junctions,+ // edge emission, face extraction) turn a click into a multi-second freeze+ if (store.nodes.length > options.maxBoundarySegments * 4) {+ return null;+ }++ // Broad phase for the T-junction pass: insert each segment into the cells+ // along its path inflated by `eps`. Cell size scales with the scene extent+ // so even a scene-spanning segment walks a bounded number of cells.+ let sceneMinX = Infinity;+ let sceneMinY = Infinity;+ let sceneMaxX = -Infinity;+ let sceneMaxY = -Infinity;+ for (const s of segments) {+ sceneMinX = Math.min(sceneMinX, s.box[0]);+ sceneMinY = Math.min(sceneMinY, s.box[1]);+ sceneMaxX = Math.max(sceneMaxX, s.box[2]);+ sceneMaxY = Math.max(sceneMaxY, s.box[3]);+ }+ const sceneSpan = Math.max(sceneMaxX - sceneMinX, sceneMaxY - sceneMinY, 0);+ const segCellSize = Math.max(eps * 2, sceneSpan / 128);+ const segGrid = new Map<string, number[]>();+ segments.forEach((s, index) => {+ forEachCellAlongSegment(s.pa, s.pb, eps, segCellSize, (cx, cy) => {+ const key = `${cx}:${cy}`;+ const bucket = segGrid.get(key);+ if (bucket) {+ bucket.push(index);+ } else {+ segGrid.set(key, [index]);+ }+ });+ });++ // T-junctions: split any segment that passes through (within `eps` of) an+ // existing node. Deliberately tight — routing an edge through a node that+ // sits further off the stroke would visibly bend the filled shape; wider+ // gaps are closed by the bridging pass below instead.+ // Broad phase: each node tests only the segments sharing its grid cell —+ // the eps-inflated insertion guarantees any segment within `eps` of the+ // node is in the node's own cell. (The node set is stable during this+ // pass — no nodes are created here, so the grid stays complete.)+ for (let n = 0; n < store.nodes.length; n++) {+ const q = store.nodes[n];+ const bucket = segGrid.get(+ `${Math.floor(q[0] / segCellSize)}:${Math.floor(q[1] / segCellSize)}`,+ );+ if (!bucket) {+ continue;+ }+ for (const index of bucket) {+ const segment = segments[index];+ if (n === segment.a || n === segment.b) {+ continue;+ }+ const t = projectParam(segment.pa, segment.pb, q);+ if (t <= 0 || t >= 1) {+ continue;+ }+ if (distanceToLineSegment(q, segLines[index]) <= eps) {+ segment.splits.push({ node: n, t });+ }+ }+ }++ // emit atomic edges+ const edgeSet = new Set<string>();+ const adjacency = new Map<number, number[]>();+ // atomic edge -> ids of the elements whose segments produced it+ const edgeToElements = new Map<string, Set<string>>();+ const edgeKey = (u: number, v: number) => (u < v ? `${u}-${v}` : `${v}-${u}`);+ const link = (u: number, v: number) => {+ const list = adjacency.get(u);+ if (list) {+ list.push(v);+ } else {+ adjacency.set(u, [v]);+ }+ };+ const addEdge = (u: number, v: number, elementId: string) => {+ if (u === v) {+ return;+ }+ if (pointDistance(store.nodes[u], store.nodes[v]) < eps) {+ return;+ }+ const key = edgeKey(u, v);+ const owners = edgeToElements.get(key);+ if (owners) {+ owners.add(elementId);+ } else {+ edgeToElements.set(key, new Set([elementId]));+ }+ if (edgeSet.has(key)) {+ return;+ }+ edgeSet.add(key);+ link(u, v);+ link(v, u);+ };++ for (const segment of segments) {+ const byNode = new Map<number, number>();+ for (const split of segment.splits) {+ if (!byNode.has(split.node)) {+ byNode.set(split.node, split.t);+ }+ }+ const ordered = [...byNode.entries()]+ .map(([node, t]) => ({ node, t }))+ .sort((a, b) => a.t - b.t);+ for (let k = 0; k < ordered.length - 1; k++) {+ addEdge(ordered[k].node, ordered[k + 1].node, segment.elementId);+ }+ }++ if (edgeSet.size === 0) {+ // nothing usable — not an error, just no enclosed region+ return [];+ }++ // ---------------------------------------------------------------------------+ // bridging pass — close visual gaps up to `gapTolerance` so sketchy joints+ // (a stroke stopping a few px short of another) still enclose a region.+ //+ // Additive by design: each dangling stroke end gets a short connector EDGE+ // to its nearest reachable geometry — either an existing node, or a point+ // ON a nearby edge (the edge is split at the projection, which lies+ // exactly on the stroke). Existing vertices are never relocated, so unlike+ // snapping, a generous radius here cannot distort the filled shape — the+ // worst artifact is a tiny connector edge spanning the visual gap,+ // typically hidden under the stroke width.+ //+ // A dangling end is simply a degree-1 node. This relies on boundaries+ // being single-pass paths: line elements use their logical points (see+ // `lineElementIdealSegments`), freedraw its smoothed centerline (see+ // `freedrawIdealSegments`), and closed shapes their ideal outlines —+ // none of them produce the rough renderer's double-pass geometry, whose+ // ends would be degree-2.+ // ---------------------------------------------------------------------------+ const bridgeRadius = Math.max(eps, options.gapTolerance);+ const isDanglingEnd = (node: number): boolean =>+ new Set(adjacency.get(node) ?? []).size === 1;+ const looseEnds: number[] = [];+ for (const node of adjacency.keys()) {+ if (isDanglingEnd(node)) {+ looseEnds.push(node);+ }+ }+ if (looseEnds.length > 0) {+ // spatial hash of live edges, updated as bridging splits edges / adds+ // connectors. Cells are at least `bridgeRadius` wide so any edge within+ // the radius of a query point lies in the point's 3×3 cell+ // neighbourhood. Entries are never removed — edges deleted by `unlink`+ // are filtered out on lookup via `edgeSet`+ // Keep the arrangement's longest axis to roughly 128 cells. The cell size+ // remains at least `bridgeRadius`, so every edge within that radius is+ // still guaranteed to lie in the query point's 3×3 neighbourhood.+ const edgeCellSize = Math.max(bridgeRadius, sceneSpan / 128, 1);+ const edgeGrid = new Map<string, { u: number; v: number }[]>();+ const insertLiveEdge = (u: number, v: number) => {+ const edge = { u, v };+ forEachCellAlongSegment(+ store.nodes[u],+ store.nodes[v],+ 0,+ edgeCellSize,+ (cx, cy) => {+ const key = `${cx}:${cy}`;+ const bucket = edgeGrid.get(key);+ if (bucket) {+ bucket.push(edge);+ } else {+ edgeGrid.set(key, [edge]);+ }+ },+ );+ };+ for (const key of edgeSet) {+ const [u, v] = key.split("-").map(Number);+ insertLiveEdge(u, v);+ }+ const unlink = (u: number, v: number) => {+ const key = edgeKey(u, v);+ edgeSet.delete(key);+ const owners = edgeToElements.get(key);+ edgeToElements.delete(key);+ const listU = adjacency.get(u);+ const listV = adjacency.get(v);+ listU?.splice(listU.indexOf(v), 1);+ listV?.splice(listV.indexOf(u), 1);+ return owners;+ };++ for (const loose of looseEnds) {+ // skip ends already closed by an earlier bridge+ if (!isDanglingEnd(loose)) {+ continue;+ }+ const p = store.nodes[loose];+ const neighbours = adjacency.get(loose) ?? [];++ // nearest non-adjacent node within the bridge radius. Candidates+ // closer than the snap epsilon are skipped — they're effectively the+ // same point and `addEdge` refuses such degenerate edges anyway+ let bestNode = -1;+ let bestNodeDistance = Infinity;+ store.forEachInRadius(p, bridgeRadius, (n) => {+ if (n === loose || neighbours.includes(n)) {+ return;+ }+ const distance = pointDistance(p, store.nodes[n]);+ if (+ distance >= eps &&+ distance <= bridgeRadius &&+ distance < bestNodeDistance+ ) {+ bestNodeDistance = distance;+ bestNode = n;+ }+ });++ // nearest edge (not incident to the loose end) whose interior the+ // loose end projects onto, within the bridge radius+ let bestEdge: { u: number; v: number } | null = null;+ let bestEdgeDistance = Infinity;+ let bestEdgeT = 0;+ const looseCx = Math.floor(p[0] / edgeCellSize);+ const looseCy = Math.floor(p[1] / edgeCellSize);+ // an edge spans multiple cells, so it can show up in several of the 9+ // inspected buckets+ const seenEdges = new Set<string>();+ for (let dcx = -1; dcx <= 1; dcx++) {+ for (let dcy = -1; dcy <= 1; dcy++) {+ const bucket = edgeGrid.get(`${looseCx + dcx}:${looseCy + dcy}`);+ if (!bucket) {+ continue;+ }+ for (const edge of bucket) {+ const key = edgeKey(edge.u, edge.v);+ if (seenEdges.has(key)) {+ continue;+ }+ seenEdges.add(key);+ if (!edgeSet.has(key) || edge.u === loose || edge.v === loose) {+ continue;+ }+ const eu = store.nodes[edge.u];+ const ev = store.nodes[edge.v];+ const t = projectParam(eu, ev, p);+ if (t <= 0 || t >= 1) {+ continue;+ }+ const distance = distanceToLineSegment(p, lineSegment(eu, ev));+ if (distance <= bridgeRadius && distance < bestEdgeDistance) {+ bestEdgeDistance = distance;+ bestEdge = edge;+ bestEdgeT = t;+ }+ }+ }+ }++ const bridgeElement =+ // every node gets a source at creation; the fallback is defensive+ nodeElement.get(loose) ?? segments[0].elementId;+ if (bestEdge && bestEdgeDistance < bestNodeDistance) {+ // split the edge at the projection (a point ON the stroke) and+ // connect the loose end to it+ const eu = store.nodes[bestEdge.u];+ const ev = store.nodes[bestEdge.v];+ const projection = store.getOrCreate(pointAtParam(eu, ev, bestEdgeT));+ if (projection === bestEdge.u || projection === bestEdge.v) {+ // projection merged into an endpoint — plain node bridge+ addEdge(loose, projection, bridgeElement);+ insertLiveEdge(loose, projection);+ } else {+ if (!nodeElement.has(projection)) {+ nodeElement.set(+ projection,+ edgeToElements+ .get(edgeKey(bestEdge.u, bestEdge.v))+ ?.values()+ .next().value ?? bridgeElement,+ );+ }+ const owners =+ unlink(bestEdge.u, bestEdge.v) ?? new Set([bridgeElement]);+ for (const owner of owners) {+ addEdge(bestEdge.u, projection, owner);+ addEdge(projection, bestEdge.v, owner);+ }+ insertLiveEdge(bestEdge.u, projection);+ insertLiveEdge(projection, bestEdge.v);+ addEdge(loose, projection, bridgeElement);+ insertLiveEdge(loose, projection);+ }+ } else if (bestNode >= 0) {+ addEdge(loose, bestNode, bridgeElement);+ insertLiveEdge(loose, bestNode);+ }+ }+ }++ // connected components of the final graph (bridges included, so a bridged+ // island shares a component with what it bridged to and can't become a+ // hole) — used to tell true islands from same-component subdivisions+ const componentOf = new Map<number, number>();+ let componentCount = 0;+ for (const start of adjacency.keys()) {+ if (componentOf.has(start)) {+ continue;+ }+ const queue = [start];+ componentOf.set(start, componentCount);+ while (queue.length) {+ const node = queue.pop()!;+ for (const neighbour of adjacency.get(node) ?? []) {+ if (!componentOf.has(neighbour)) {+ componentOf.set(neighbour, componentCount);+ queue.push(neighbour);+ }+ }+ }+ componentCount++;+ }++ // sort outgoing half-edges by angle around each node+ const angleOf = (from: number, to: number): number =>+ Math.atan2(+ store.nodes[to][1] - store.nodes[from][1],+ store.nodes[to][0] - store.nodes[from][0],+ );+ const sortedOut = new Map<number, number[]>();+ const positionOf = new Map<number, Map<number, number>>();+ for (const [node, neighbours] of adjacency) {+ const unique = Array.from(new Set(neighbours));+ unique.sort((p, q) => angleOf(node, p) - angleOf(node, q));+ sortedOut.set(node, unique);+ const positions = new Map<number, number>();+ unique.forEach((neighbour, index) => positions.set(neighbour, index));+ positionOf.set(node, positions);+ }++ // walk half-edges into face rings+ const visited = new Set<string>();+ const faces: Face[] = [];+ const maxSteps = edgeSet.size * 2 + 4;+ for (const [node, neighbours] of adjacency) {+ for (const first of neighbours) {+ if (visited.has(`${node}->${first}`)) {+ continue;+ }+ const ring: number[] = [];+ let from = node;+ let to = first;+ let steps = 0;+ while (steps++ <= maxSteps) {+ visited.add(`${from}->${to}`);+ ring.push(from);+ const outs = sortedOut.get(to)!;+ const twinPosition = positionOf.get(to)!.get(from)!;+ // the next edge in the face is the one immediately clockwise from the+ // reverse (twin) direction+ const nextPosition = (twinPosition - 1 + outs.length) % outs.length;+ const next = outs[nextPosition];+ from = to;+ to = next;+ if (from === node && to === first) {+ break;+ }+ }+ if (ring.length >= 3) {+ const contributors = new Set<string>();+ for (let k = 0; k < ring.length; k++) {+ const owners = edgeToElements.get(+ edgeKey(ring[k], ring[(k + 1) % ring.length]),+ );+ if (owners) {+ for (const id of owners) {+ contributors.add(id);+ }+ }+ }+ faces.push({+ ring: ring.map((index) => store.nodes[index]),+ contributors,+ componentId: componentOf.get(node) ?? -1,+ });+ }+ }+ }++ return faces;+};++type FaceSelection = {+ face: Face;+ /** island contours to punch out of the face — see `selectFaceFromArrangement` */+ holes: Face[];+};++/**+ * Select the smallest bounded face that contains the click point. The single+ * unbounded face has the largest absolute area; faces sharing its orientation+ * are skipped, which leaves only true (bounded) cells.+ *+ * Also collects the face's holes: each disconnected component has exactly one+ * outer-orientation ring (its outside contour), and when that contour lies+ * inside the selected face the component is an island the flood fill must+ * flow around. Only outermost islands count — an island nested inside+ * another island already sits inside a hole.+ */+const selectFaceFromArrangement = (+ faces: Face[],+ point: GlobalPoint,+ options: BucketFillOptions,+): FaceSelection | null => {+ if (faces.length === 0) {+ return null;+ }++ // The half-edge walk ("next = the neighbour immediately clockwise of the+ // twin", in screen coordinates with y pointing down) traces every BOUNDED+ // face with negative shoelace area and every component's outside contour+ // with positive area — a structural invariant of the walk rule. Bounded vs+ // unbounded must be decided by this sign alone, NOT by comparing areas:+ // the outermost outline's interior face and outside contour trace the same+ // polygon with equal |area|, so any size-based heuristic degenerates into+ // an enumeration-order coin flip (which made hole detection depend on+ // element order/position — see the overlapping-islands regression tests).+ const outerSign = 1;+ const areaOf = new Map<Face, number>();+ for (const face of faces) {+ // negated: polygonSignedArea is CCW-positive, while the invariant above+ // is stated in the opposite (bounded-faces-negative) convention+ areaOf.set(face, -polygonSignedArea(face.ring, 0));+ }++ let best: Face | null = null;+ let bestArea = Infinity;+ for (const face of faces) {+ const area = areaOf.get(face)!;+ if (Math.sign(area) === outerSign) {+ continue;+ }+ const absArea = Math.abs(area);+ if (absArea < options.minArea) {+ continue;+ }+ if (!polygonIncludesPointNonZero(point, face.ring)) {+ continue;+ }+ if (absArea < bestArea) {+ bestArea = absArea;+ best = face;+ }+ }++ if (!best) {+ return null;+ }+ const selected = best;++ const islandCandidates = faces.filter(+ (face) =>+ face.componentId !== selected.componentId &&+ // a component's outside contour shares the unbounded face's orientation+ Math.sign(areaOf.get(face)!) === outerSign &&+ Math.abs(areaOf.get(face)!) >= options.minArea &&+ // the click face never sits inside one of its own holes (defensive —+ // the smallest-containing-face selection above already guarantees it)+ !polygonIncludesPointNonZero(point, face.ring) &&+ // components never intersect (crossings would have merged them), so a+ // single-vertex test decides containment+ polygonIncludesPointNonZero(face.ring[0], selected.ring),+ );+ const holes = islandCandidates.filter(+ (hole) =>+ !islandCandidates.some(+ (other) =>+ other !== hole &&+ polygonIncludesPointNonZero(hole.ring[0], other.ring),+ ),+ );++ return { face: selected, holes };+};++// -----------------------------------------------------------------------------+// simplification+// -----------------------------------------------------------------------------++const dedupeConsecutive = (pts: GlobalPoint[], eps: number): GlobalPoint[] => {+ const out: GlobalPoint[] = [];+ for (const p of pts) {+ if (out.length === 0 || pointDistance(out[out.length - 1], p) >= eps) {+ out.push(p);+ }+ }+ while (out.length > 1 && pointDistance(out[0], out[out.length - 1]) < eps) {+ out.pop();+ }+ return out;+};++const removeCollinear = (+ pts: GlobalPoint[],+ tolerance: number,+): GlobalPoint[] => {+ if (pts.length <= 3) {+ return pts;+ }+ const out: GlobalPoint[] = [];+ for (let i = 0; i < pts.length; i++) {+ const prev = out[out.length - 1] ?? pts[pts.length - 1];+ const next = pts[(i + 1) % pts.length];+ if (perpendicularDistance(pts[i], prev, next) >= tolerance) {+ out.push(pts[i]);+ }+ }+ return out.length >= 3 ? out : pts;+};++/**+ * Simplify an open ring under a point budget. Returns null when it collapses+ * below a triangle or cannot fit the budget.+ */+const simplifyRing = (+ ring: GlobalPoint[],+ options: BucketFillOptions,+ budget: number,+): GlobalPoint[] | null => {+ const pts = dedupeConsecutive(ring, options.snapEpsilon);+ if (pts.length < 3) {+ return null;+ }++ // Ramer–Douglas–Peucker via the same `simplify` the freedraw renderer+ // uses (identical default tolerance), escalating until under the point cap+ let tolerance = 0.75;+ let simplified = simplify(pts, tolerance) as GlobalPoint[];+ while (simplified.length > budget && tolerance < 1e6) {+ tolerance *= 2;+ simplified = simplify(pts, tolerance) as GlobalPoint[];+ }+ if (simplified.length > budget) {+ return null;+ }++ simplified = removeCollinear(simplified, 0.05);+ return simplified.length >= 3 ? simplified : null;+};++/**+ * Splice a hole contour into the ring as a zero-width "keyhole": walk the+ * ring to the attachment vertex, bridge to the hole, traverse the hole, and+ * bridge back along the same edge. The doubled bridge cancels under the+ * even-odd rule the renderer uses for looped-line fills (and under the+ * pattern fills' scanline parity), leaving the hole interior unpainted+ * while the result stays one closed polygon.+ */+const spliceHoleIntoRing = (+ ring: GlobalPoint[],+ hole: GlobalPoint[],+): GlobalPoint[] => {+ // opposite winding: even-odd doesn't care, but this keeps the path+ // correct under the nonzero rule as well (defense against renderer or+ // export changes)+ const oriented =+ Math.sign(polygonSignedArea(hole, 0)) ===+ Math.sign(polygonSignedArea(ring, 0))+ ? [...hole].reverse()+ : hole;++ // shortest bridge, so the (invisible) channel never spans the region+ let bestRingIndex = 0;+ let bestHoleIndex = 0;+ let bestDistance = Infinity;+ for (let i = 0; i < ring.length; i++) {+ for (let j = 0; j < oriented.length; j++) {+ const distance = pointDistance(ring[i], oriented[j]);+ if (distance < bestDistance) {+ bestDistance = distance;+ bestRingIndex = i;+ bestHoleIndex = j;+ }+ }+ }++ const out: GlobalPoint[] = ring.slice(0, bestRingIndex + 1);+ // full hole loop, ending back on its attachment vertex+ for (let k = 0; k <= oriented.length; k++) {+ out.push(oriented[(bestHoleIndex + k) % oriented.length]);+ }+ out.push(ring[bestRingIndex]);+ out.push(...ring.slice(bestRingIndex + 1));+ return out;+};++/**+ * Simplify the face ring and its hole contours (each independently, so the+ * keyhole bridges stay exactly zero-width), splice the holes in, and return+ * the result explicitly closed (first point repeated as last), along with+ * the indices of the holes that were actually spliced. Returns null when+ * the outer ring cannot form a valid polygon; holes that cannot fit the+ * remaining point budget are dropped (the island then just gets painted+ * over, the pre-hole-support behavior).+ */+const finalizePolygon = (+ outerRing: GlobalPoint[],+ holeRings: GlobalPoint[][],+ options: BucketFillOptions,+): { scenePoints: GlobalPoint[]; splicedHoleIndices: number[] } | null => {+ let ring = simplifyRing(outerRing, options, options.maxGeneratedPoints);+ if (!ring) {+ return null;+ }++ // largest first, so a tight point budget drops the least visible islands+ const byAreaDesc = holeRings+ .map((holeRing, index) => ({ holeRing, index }))+ .sort((a, b) => polygonArea(b.holeRing, 0) - polygonArea(a.holeRing, 0));+ const splicedHoleIndices: number[] = [];+ for (const { holeRing, index } of byAreaDesc) {+ // a spliced hole costs its own points + 2 bridge duplicates+ const budget = options.maxGeneratedPoints - ring.length - 2;+ if (budget < 3) {+ break;+ }+ const hole = simplifyRing(holeRing, options, budget);+ if (!hole) {+ continue;+ }+ ring = spliceHoleIntoRing(ring, hole);+ splicedHoleIndices.push(index);+ }++ // close the polygon exactly once+ return { scenePoints: [...ring, ring[0]], splicedHoleIndices };+};++// -----------------------------------------------------------------------------+// public API+// -----------------------------------------------------------------------------++export const computeBucketFillPolygon = (args: {+ point: GlobalPoint;+ elements: readonly NonDeletedExcalidrawElement[];+ elementsMap: ElementsMap;+ options?: Partial<BucketFillOptions>;+}): BucketFillGeometryResult => {+ const options = { ...DEFAULT_BUCKET_FILL_OPTIONS, ...args.options };+ const { point, elements, elementsMap } = args;++ // 1. owner under the pointer — the fast common case (click inside a closed+ // element). When there is none (regions formed by open lines, or+ // self-intersecting outlines whose hit-test fails), the owner-less+ // fallback below builds the arrangement from everything near the click.+ const owner = findOwner(point, elements, elementsMap);++ const indexOf = new Map<string, number>();+ elements.forEach((element, i) => indexOf.set(element.id, i));++ // 2+3. collect boundary segments within `candidateBounds`, tagged with+ // their source element and clipped to their visible parts (portions hidden+ // behind an opaque element above are not boundaries — only what the user+ // actually sees can stop fill). Returns null when over the segment cap.+ const collectSegments = (+ candidateBounds: Bounds,+ primary: NonDeletedExcalidrawElement | null,+ ): SourceSegment[] | null => {+ const inRange = (element: ExcalidrawElement) =>+ doBoundsIntersect(+ candidateBounds,+ getElementBounds(element, elementsMap),+ );+ const boundaries = elements.filter(+ (element) =>+ element.id !== primary?.id &&+ isEligibleBoundary(element) &&+ inRange(element),+ );+ // the opaque elements that hide outlines beneath them — including+ // existing bucket fills: an outline buried under an opaque fill is+ // invisible, so it must not stop a new fill either+ const coverers = elements.filter(+ (element) => rendersOpaqueFill(element) && inRange(element),+ );++ const rawSegments: SourceSegment[] = [];+ const collect = (element: ExcalidrawElement) => {+ const elementIndex = indexOf.get(element.id) ?? 0;+ const coverersAbove = coverers.filter(+ (coverer) =>+ coverer.id !== element.id &&+ (indexOf.get(coverer.id) ?? 0) > elementIndex,+ );+ // half this element's stroke still renders when its centerline lies on+ // a coverer's edge — never treat that band as hidden+ const clipMargin = Math.max(+ options.snapEpsilon,+ element.strokeWidth / 2,+ BUCKET_FILL_COVER_MARGIN,+ );+ const segments = isLineElement(element)+ ? lineElementIdealSegments(element, elementsMap)+ : isFreeDrawElement(element)+ ? freedrawIdealSegments(element, elementsMap)+ : getElementLineSegments(element, elementsMap);+ // freedraw and non-polygon line loops render as closed once their+ // endpoints are within LINE_CONFIRM_THRESHOLD (isPathALoop), but their+ // segment chain leaves that closure gap open — bridge it explicitly so+ // the region reads as closed here too. Deliberately isPathALoop (the+ // renderer's own closure rule), NOT gapTolerance: whether an element+ // paints its background must match whether fill treats it as closed.+ if (+ (element.type === "freedraw" ||+ (isLineElement(element) && !element.polygon)) &&+ isPathALoop(element.points) &&+ segments.length > 0+ ) {+ const first = segments[0][0];+ const last = segments[segments.length - 1][1];+ if (pointDistance(first, last) >= options.snapEpsilon) {+ segments.push(lineSegment(last, first));+ }+ }+ for (const segment of segments) {+ // enforce the segment budget WHILE collecting: without this, a huge+ // scene does all the expensive visibility clipping before the cap+ // is ever consulted+ if (rawSegments.length > options.maxBoundarySegments) {+ return;+ }+ // keep sub-epsilon segments: buildFaces collapses them via node+ // merging without breaking the chain (see note there); only true+ // zero-length degenerates are noise+ if (segmentLength(segment) === 0) {+ continue;+ }+ if (coverersAbove.length === 0) {+ rawSegments.push({ segment, elementId: element.id });+ continue;+ }+ for (const [a, b] of clipSegmentToVisible(+ segment[0],+ segment[1],+ coverersAbove,+ elementsMap,+ options.snapEpsilon,+ clipMargin,+ )) {+ rawSegments.push({+ segment: lineSegment(a, b),+ elementId: element.id,+ });+ }+ }+ };+ for (const element of primary ? [primary, ...boundaries] : boundaries) {+ if (rawSegments.length > options.maxBoundarySegments) {+ break;+ }+ collect(element);+ }+ return rawSegments.length > options.maxBoundarySegments+ ? null+ : rawSegments;+ };++ const buildAndSelect = (+ rawSegments: SourceSegment[],+ ): FaceSelection | null | "too_complex" => {+ const faces = buildFaces(rawSegments, options);+ if (!faces) {+ return "too_complex";+ }+ return selectFaceFromArrangement(faces, point, options);+ };++ // 4. resolve the face under the click+ let selection: FaceSelection | null = null;+ if (owner) {+ const pad = options.gapTolerance + 2 + Math.max(owner.strokeWidth ?? 1, 1);+ const searchBounds = expandBounds(+ getElementBounds(owner, elementsMap),+ pad,+ );+ const rawSegments = collectSegments(searchBounds, owner);+ if (!rawSegments) {+ return { ok: false, reason: "too_complex" };+ }+ const selected = buildAndSelect(rawSegments);+ if (selected === "too_complex") {+ return { ok: false, reason: "too_complex" };+ }+ if (!selected) {+ return { ok: false, reason: "open_region" };+ }+ selection = selected;+ } else {+ // owner-less fallback: search an expanding box around the click. A face+ // is final once its ring stays clear of the box frontier — any element+ // that could still subdivide it would intersect the box and is already+ // included; a ring touching the frontier may be missing far-away+ // boundaries, so grow and retry.+ const totalEligible = elements.reduce(+ (count, element) => count + (isEligibleBoundary(element) ? 1 : 0),+ 0,+ );+ if (totalEligible === 0) {+ return { ok: false, reason: "no_owner" };+ }+ let radius = options.fallbackSearchRadius;+ for (let attempt = 0; attempt < 4 && !selection; attempt++, radius *= 2) {+ const box: Bounds = [+ point[0] - radius,+ point[1] - radius,+ point[0] + radius,+ point[1] + radius,+ ];+ const inRange = elements.reduce(+ (count, element) =>+ count ++ (isEligibleBoundary(element) &&+ doBoundsIntersect(box, getElementBounds(element, elementsMap))+ ? 1+ : 0),+ 0,+ );+ // every eligible element is in range: whatever this box yields is+ // FINAL — a bigger box would rebuild the identical arrangement, and+ // the frontier heuristic below only exists to approximate exactly+ // this condition+ const isFinalAttempt = attempt === 3 || inRange === totalEligible;+ if (inRange === 0) {+ // empty at this radius — the region may still lie farther out, so+ // keep growing (a distant enclosure, e.g. a huge line square whose+ // strokes are all beyond the first box)+ continue;+ }+ const rawSegments = collectSegments(box, null);+ // the fallback is speculative — never toast on its failures. Over the+ // segment cap counts as a failure, not a "too complex" complaint.+ if (!rawSegments) {+ return { ok: false, reason: "no_owner" };+ }+ const selected = buildAndSelect(rawSegments);+ if (selected === "too_complex") {+ return { ok: false, reason: "no_owner" };+ }+ if (+ selected &&+ (isFinalAttempt ||+ selected.face.ring.every(+ (p) =>+ p[0] > box[0] + options.gapTolerance &&+ p[1] > box[1] + options.gapTolerance &&+ p[0] < box[2] - options.gapTolerance &&+ p[1] < box[3] - options.gapTolerance,+ ))+ ) {+ selection = selected;+ }+ if (!selection && isFinalAttempt) {+ // nothing more can enter range — no point burning further builds+ break;+ }+ }+ if (!selection) {+ // no enclosed region under the pointer — stay silent like `no_owner`;+ // clicking open canvas shouldn't nag+ return { ok: false, reason: "no_owner" };+ }+ }+ const { face, holes } = selection;++ // 5. simplify and validate. Note the returned ring may be a keyhole path+ // (holes spliced in via zero-width bridges); its signed area is then the+ // NET filled area, which is exactly what the size check should measure.+ const finalized = finalizePolygon(+ face.ring,+ holes.map((hole) => hole.ring),+ options,+ );+ if (!finalized) {+ return { ok: false, reason: "invalid_polygon" };+ }+ const { scenePoints, splicedHoleIndices } = finalized;+ if (polygonArea(scenePoints, 0) < options.minArea) {+ return { ok: false, reason: "too_small" };+ }++ // spliced islands genuinely bound the visible fill, so they join the+ // boundary metadata (and, via the app layer, group inheritance)+ const contributors = new Set<string>(face.contributors);+ for (const index of splicedHoleIndices) {+ for (const id of holes[index].contributors) {+ contributors.add(id);+ }+ }++ // 6. z-order. Two constraints, applied over ALL scene elements (not just+ // the region's participants):+ //+ // - the fill goes ABOVE the topmost opaque element whose paint overlaps+ // the region ANYWHERE (same "covers" predicate boundary clipping uses).+ // After a fill the region should read uniformly filled — the raster+ // flood-fill outcome — so older opaque paint must not poke through it;+ // the paint containing the click point is just the special case where+ // the fill would otherwise be hidden at the very point clicked;+ // - otherwise it goes BELOW the lowest element that must stay visible:+ // every participant (their outlines border the fill; deliberately+ // including islands whose hole was dropped for the point budget — the+ // fill paints straight through those, so staying below them is what+ // keeps them visible at all), plus any visible NON-participant whose+ // mark lies inside the region (a floating line, a label, an icon — an+ // opaque fill would bury them). A visible stroke merely CROSSING the+ // region would have subdivided the face and be a participant already,+ // so sampling the element center + path points is enough to catch the+ // wholly-inside marks that remain. The even-odd containment matches+ // the render rule, so elements inside a keyhole hole are correctly NOT+ // constrained (the fill doesn't paint there).+ //+ // When the two constraints conflict (an overlapping coverer sits above+ // some in-region mark in z), above-the-coverer wins: a mark buried under+ // opaque paint was largely hidden already, while paint poking through a+ // fresh fill always reads as the fill having failed.+ const participantIds = new Set<string>(+ owner ? [owner.id, ...contributors] : contributors,+ );+ for (const hole of holes) {+ for (const id of hole.contributors) {+ participantIds.add(id);+ }+ }++ const fillRegion = scenePoints as unknown as Polygon<GlobalPoint>;+ const [regionMinX, regionMinY, regionMaxX, regionMaxY] =+ getBoundsFromPoints(scenePoints);+ const markInsideRegion = (element: ExcalidrawElement): boolean => {+ const [minX, minY, maxX, maxY] = getElementBounds(element, elementsMap);+ if (+ maxX < regionMinX ||+ minX > regionMaxX ||+ maxY < regionMinY ||+ minY > regionMaxY+ ) {+ return false;+ }+ const samples: GlobalPoint[] = [+ pointFrom<GlobalPoint>((minX + maxX) / 2, (minY + maxY) / 2),+ ];+ if (isLinearElement(element) || isFreeDrawElement(element)) {+ const center = elementCenterPoint(element, elementsMap);+ const step = Math.max(1, Math.floor(element.points.length / 8));+ for (let i = 0; i < element.points.length; i += step) {+ samples.push(+ pointRotateRads(+ pointFrom<GlobalPoint>(+ element.x + element.points[i][0],+ element.y + element.points[i][1],+ ),+ center,+ element.angle,+ ),+ );+ }+ }+ return samples.some((sample) => polygonIncludesPoint(sample, fillRegion));+ };++ /**+ * Whether the element's paint overlaps the fill region anywhere. Sampled+ * in both directions (element outline inside the region, region ring+ * inside the element — covering partial overlap and containment either+ * way), plus the click point itself; exactness doesn't matter for a+ * z-order decision.+ */+ const paintOverlapsRegion = (element: ExcalidrawElement): boolean => {+ const [minX, minY, maxX, maxY] = getElementBounds(element, elementsMap);+ if (+ maxX < regionMinX ||+ minX > regionMaxX ||+ maxY < regionMinY ||+ minY > regionMaxY+ ) {+ return false;+ }+ if (isPointInElement(point, element, elementsMap)) {+ return true;+ }+ const outline = getElementLineSegments(element, elementsMap);+ const outlineStep = Math.max(1, Math.floor(outline.length / 16));+ for (let i = 0; i < outline.length; i += outlineStep) {+ if (polygonIncludesPoint(outline[i][0], fillRegion)) {+ return true;+ }+ }+ const ringStep = Math.max(1, Math.floor(scenePoints.length / 16));+ for (let i = 0; i < scenePoints.length; i += ringStep) {+ if (isPointInElement(scenePoints[i], element, elementsMap)) {+ return true;+ }+ }+ return false;+ };++ let lowestAbove: ExcalidrawElement | null = null;+ let covering: ExcalidrawElement | null = null;+ for (const element of elements) {+ // the coverer constraint is evaluated for EVERY element, not just the+ // `mustStayAbove` ones: an opaque element overlapping the region away+ // from the click (or straddling its edge, center outside) is neither a+ // participant nor a sampled in-region mark — missing it would insert+ // the fill beneath it, and its paint would poke through the fill+ if (rendersOpaqueFill(element) && paintOverlapsRegion(element)) {+ covering = element;+ }+ const mustStayAbove =+ participantIds.has(element.id) ||+ (rendersAnyMark(element) && markInsideRegion(element));+ if (mustStayAbove) {+ lowestAbove = lowestAbove ?? element;+ }+ }+ // a face always has contributors from `elements`, so a participant exists;+ // the last-element fallback is defensive only+ const insertion: BucketFillInsertion = covering+ ? { placement: "above", elementId: covering.id }+ : {+ placement: "below",+ elementId: (lowestAbove ?? elements[elements.length - 1]).id,+ };++ return {+ ok: true,+ ownerId: owner?.id ?? null,+ // elements (other than the owner) whose outlines actually bound the fill+ boundaryElementIds: [...contributors].filter((id) => id !== owner?.id),+ scenePoints,+ insertion,+ };+};++/**+ * Whether the element the click landed on is a fill the bucket tool should+ * restyle in place (instead of stacking an identical fill on top), given+ * the computed region.+ *+ * Fill-compatibility is decided by shape (`isBucketFillCompatible`): a fill+ * the user gave a stroke to has been repurposed into an outline and+ * participates as a boundary instead of being restyled.+ *+ * One guard on top: the computed region's net area and bounds must match+ * the element's. Without it, a click inside a shape drawn ON TOP of a+ * filled region would recolor the underlying fill instead of filling that+ * shape; a click on a since-subdivided part of an old fill likewise+ * creates a new (smaller) fill rather than restyling the old one.+ */+export const isRestylableFill = (args: {+ hitElement: ExcalidrawElement;+ scenePoints: readonly GlobalPoint[];+ elementsMap: ElementsMap;+}): boolean => {+ const { hitElement, scenePoints, elementsMap } = args;+ if (!isBucketFillCompatible(hitElement)) {+ return false;+ }++ const center = elementCenterPoint(hitElement, elementsMap);+ const ring = hitElement.points.map((p) =>+ pointRotateRads(+ pointFrom<GlobalPoint>(hitElement.x + p[0], hitElement.y + p[1]),+ center,+ hitElement.angle,+ ),+ );+ // same region? net areas (keyhole bridges cancel) and bounds must agree+ const fillArea = polygonArea(ring, 0);+ const regionArea = polygonArea(scenePoints, 0);+ const sameArea =+ Math.abs(fillArea - regionArea) <= 0.05 * Math.max(fillArea, regionArea);+ const [aMinX, aMinY, aMaxX, aMaxY] = getBoundsFromPoints(ring);+ const [bMinX, bMinY, bMaxX, bMaxY] = getBoundsFromPoints(scenePoints);+ const tolerance = BUCKET_FILL_REGION_MATCH_TOLERANCE;+ const sameBounds =+ Math.abs(aMinX - bMinX) <= tolerance &&+ Math.abs(aMinY - bMinY) <= tolerance &&+ Math.abs(aMaxX - bMaxX) <= tolerance &&+ Math.abs(aMaxY - bMaxY) <= tolerance;++ return sameArea && sameBounds;+};diff --git a/packages/element/src/comparisons.ts b/packages/element/src/comparisons.tsindex 45c03cf489..ea4fc7f2a4 100644--- a/packages/element/src/comparisons.ts+++ b/packages/element/src/comparisons.ts@@ -8,7 +8,9 @@ export const hasBackground = (type: ElementOrToolType) =>type === "diamond" ||type === "line" ||type === "freedraw" ||- type === "autoshape";+ type === "autoshape" ||+ // tool-only type; makes the `G` background shortcut work for bucket fill+ type === "bucketfill";export const hasStrokeColor = (type: ElementOrToolType) =>type === "rectangle" ||diff --git a/packages/element/src/index.ts b/packages/element/src/index.tsindex e2a8da535e..e30ba2b3b2 100644--- a/packages/element/src/index.ts+++ b/packages/element/src/index.ts@@ -60,6 +60,7 @@ export * from "./align";export * from "./arrowEndpointText";export * from "./binding";export * from "./bounds";+export * from "./bucketFill";export * from "./collision";export * from "./comparisons";export * from "./containerCache";diff --git a/packages/element/src/shape.ts b/packages/element/src/shape.tsindex ecc5580c13..4e7c747535 100644--- a/packages/element/src/shape.ts+++ b/packages/element/src/shape.ts@@ -1,5 +1,5 @@import { simplify } from "points-on-curve";-import { getStroke } from "perfect-freehand";+import { getStroke, getStrokePoints } from "perfect-freehand";import { LaserPointer } from "@excalidraw/laser-pointer";import {@@ -1253,6 +1253,26 @@ export const getFreedrawOutlinePoints = (: 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];};diff --git a/packages/element/tests/bucketFill.test.ts b/packages/element/tests/bucketFill.test.tsnew file mode 100644index 0000000000..728a38a950--- /dev/null+++ b/packages/element/tests/bucketFill.test.ts@@ -0,0 +1,2272 @@+import { arrayToMap, ROUNDNESS } from "@excalidraw/common";+import {+ distanceToLineSegment,+ lineSegment,+ pointFrom,+ polygonIncludesPoint,+} from "@excalidraw/math";++import { API } from "@excalidraw/excalidraw/tests/helpers/api";++import type { GlobalPoint, LocalPoint, Polygon } from "@excalidraw/math";++import { computeBucketFillPolygon, isRestylableFill } from "../src/bucketFill";+import { getFreedrawStrokeCenterPoints } from "../src/shape";++import type { ElementsMap, NonDeletedExcalidrawElement } from "../src/types";++const setup = (elements: NonDeletedExcalidrawElement[]) => ({+ elements,+ elementsMap: arrayToMap(elements) as ElementsMap,+});++const polygonArea = (pts: GlobalPoint[]): number => {+ let area = 0;+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {+ area += (pts[j][0] + pts[i][0]) * (pts[j][1] - pts[i][1]);+ }+ return Math.abs(area / 2);+};++/**+ * Turn a computed fill polygon into the line element the app would create+ * for it, so a follow-up `computeBucketFillPolygon` sees the prior fill.+ */+const materializeFill = (scenePoints: readonly GlobalPoint[]) => {+ const minX = Math.min(...scenePoints.map((p) => p[0]));+ const minY = Math.min(...scenePoints.map((p) => p[1]));+ const maxX = Math.max(...scenePoints.map((p) => p[0]));+ const maxY = Math.max(...scenePoints.map((p) => p[1]));+ return API.createElement({+ type: "line",+ x: minX,+ y: minY,+ width: maxX - minX,+ height: maxY - minY,+ points: scenePoints.map((p) =>+ pointFrom<LocalPoint>(p[0] - minX, p[1] - minY),+ ),+ polygon: true,+ backgroundColor: "#ffc9c9",+ fillStyle: "solid",+ strokeColor: "transparent",+ });+};++const isClosed = (pts: GlobalPoint[]): boolean =>+ pts.length > 3 &&+ pts[0][0] === pts[pts.length - 1][0] &&+ pts[0][1] === pts[pts.length - 1][1];++describe("computeBucketFillPolygon", () => {+ it("fills a simple rectangle and returns a closed polygon", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ const { elements, elementsMap } = setup([rect]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBe(rect.id);+ expect(result.boundaryElementIds).toEqual([]);+ // transparent owner => the fill goes below it+ expect(result.insertion).toEqual({+ placement: "below",+ elementId: rect.id,+ });+ expect(isClosed(result.scenePoints)).toBe(true);+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -1);+ });++ it("fills a rotated rectangle", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ angle: Math.PI / 5,+ roundness: null,+ });+ const { elements, elementsMap } = setup([rect]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(isClosed(result.scenePoints)).toBe(true);+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -1);+ });++ it("fills an ellipse with a bounded point count", () => {+ const ellipse = API.createElement({+ type: "ellipse",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ });+ const { elements, elementsMap } = setup([ellipse]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(isClosed(result.scenePoints)).toBe(true);+ // circle of r=50 ~ 7854; simplified polygon is slightly smaller+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(7000);+ expect(polygonArea(result.scenePoints)).toBeLessThan(7900);+ expect(result.scenePoints.length).toBeLessThanOrEqual(64);+ expect(result.scenePoints.length).toBeGreaterThan(6);+ });++ it("fills a curved line polygon along its smoothed path", () => {+ // curved (`roundness`) lines render a curve fitted through the points;+ // the fill boundary must sample that curve, not cut corners along the+ // raw polyline+ const points = [+ pointFrom<LocalPoint>(0, 50),+ pointFrom<LocalPoint>(35, 0),+ pointFrom<LocalPoint>(100, 20),+ pointFrom<LocalPoint>(90, 80),+ pointFrom<LocalPoint>(30, 100),+ pointFrom<LocalPoint>(0, 50),+ ];+ const blob = API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points,+ polygon: true,+ roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS },+ });+ const { elements, elementsMap } = setup([blob]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // the smoothed curve bulges away from the polyline between sparse+ // points — some fill vertex must deviate from every polyline chord by+ // clearly more than the snap epsilon (a polyline-based boundary would+ // keep all vertices within ~1px of the chords)+ const chords = points+ .slice(0, -1)+ .map((p, i) => lineSegment(p as any, points[i + 1] as any));+ const maxDeviation = Math.max(+ ...result.scenePoints.map((vertex) =>+ Math.min(+ ...chords.map((chord) => distanceToLineSegment(vertex, chord as any)),+ ),+ ),+ );+ expect(maxDeviation).toBeGreaterThan(2);+ });++ it("fills a diamond", () => {+ // regression: a roundness:null diamond still has tiny (~2px chord) corner+ // arcs whose densely-subdivided segments used to be dropped by the+ // sub-epsilon length filter, disconnecting the outline at the corners+ const diamond = API.createElement({+ type: "diamond",+ x: 0,+ y: 0,+ width: 200,+ height: 150,+ roundness: null,+ });+ const { elements, elementsMap } = setup([diamond]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(100, 75),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(isClosed(result.scenePoints)).toBe(true);+ // diamond area = w*h/2 = 15000+ expect(polygonArea(result.scenePoints)).toBeCloseTo(15000, -3);+ });++ it("fills a freedraw loop with a hand-drawn closure gap", () => {+ // regression: isPathALoop accepts closure gaps up to LINE_CONFIRM_THRESHOLD+ // (8px), so the segment chain must be bridged explicitly or the region+ // reads as open even though it renders (and hit-tests) as closed.+ // Realistically dense points (~10px spacing, like actual drawing input) —+ // the boundary follows the streamline-smoothed centerline, which only+ // tracks the input at drawing-like densities+ const points: LocalPoint[] = [];+ const corners = [+ [0, 0],+ [100, 0],+ [100, 100],+ [0, 100],+ [0, 5],+ ];+ for (let c = 0; c < corners.length - 1; c++) {+ const [ax, ay] = corners[c];+ const [bx, by] = corners[c + 1];+ const steps = Math.ceil(Math.hypot(bx - ax, by - ay) / 10);+ for (let s = 0; s < steps; s++) {+ points.push(+ pointFrom<LocalPoint>(+ ax + ((bx - ax) * s) / steps,+ ay + ((by - ay) * s) / steps,+ ),+ );+ }+ }+ points.push(pointFrom<LocalPoint>(0, 5));+ const freedraw = API.createElement({+ type: "freedraw",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points,+ });+ const { elements, elementsMap } = setup([freedraw]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(isClosed(result.scenePoints)).toBe(true);+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -3);+ });++ it("fills an exactly-closed freedraw loop", () => {+ // the sibling of the gapped-closure test: last point === first point,+ // so no synthetic closing segment is needed at all+ const points: LocalPoint[] = [];+ const corners = [+ [0, 0],+ [100, 0],+ [100, 100],+ [0, 100],+ [0, 0],+ ];+ for (let c = 0; c < corners.length - 1; c++) {+ const [ax, ay] = corners[c];+ const [bx, by] = corners[c + 1];+ const steps = Math.ceil(Math.hypot(bx - ax, by - ay) / 10);+ for (let s = 0; s < steps; s++) {+ points.push(+ pointFrom<LocalPoint>(+ ax + ((bx - ax) * s) / steps,+ ay + ((by - ay) * s) / steps,+ ),+ );+ }+ }+ points.push(pointFrom<LocalPoint>(0, 0));+ const freedraw = API.createElement({+ type: "freedraw",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points,+ });+ const { elements, elementsMap } = setup([freedraw]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(isClosed(result.scenePoints)).toBe(true);+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -3);+ });++ it("fills a line polygon", () => {+ const triangle = API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: [+ pointFrom<LocalPoint>(0, 100),+ pointFrom<LocalPoint>(50, 0),+ pointFrom<LocalPoint>(100, 100),+ pointFrom<LocalPoint>(0, 100),+ ],+ polygon: true,+ });+ const { elements, elementsMap } = setup([triangle]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 70),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(isClosed(result.scenePoints)).toBe(true);+ expect(polygonArea(result.scenePoints)).toBeCloseTo(5000, -3);+ });++ it("fills the overlap region split by a rectangle below the owner", () => {+ const below = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ roundness: null,+ });+ // `owner` is drawn last => topmost => chosen as owner; `below` is lower+ // z-order but must still participate in the boundary graph.+ const { elements, elementsMap } = setup([below, owner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(75, 75),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBe(owner.id);+ expect(result.boundaryElementIds).toContain(below.id);+ // both participants are transparent => below the lowest one+ expect(result.insertion).toEqual({+ placement: "below",+ elementId: below.id,+ });+ // overlap region is the 50x50 square (50,50)-(100,100) => area 2500,+ // much smaller than either full 100x100 rectangle+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(2300);+ expect(polygonArea(result.scenePoints)).toBeLessThan(2700);+ });++ it("fills the owner-minus-overlap region when clicking outside the overlap", () => {+ const below = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ roundness: null,+ });+ const { elements, elementsMap } = setup([below, owner]);++ // (130,130) is inside `owner` but outside `below`+ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(130, 130),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // owner (10000) minus overlap (2500) => 7500+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(7200);+ expect(polygonArea(result.scenePoints)).toBeLessThan(7800);+ });++ it("ignores outline portions hidden behind an opaque element on top", () => {+ // `hidden` sits below `owner`; the part of its outline inside `owner` is+ // covered by owner's opaque fill, so it must not act as a boundary+ const hidden = API.createElement({+ type: "rectangle",+ x: 40,+ y: 40,+ width: 100,+ height: 100,+ roundness: null,+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "#ffd43b",+ });+ // owner drawn last => on top, with an opaque fill+ const { elements, elementsMap } = setup([hidden, owner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(20, 20),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBe(owner.id);+ // the whole visible owner fills (~10000); the hidden outline does NOT carve+ // out the ~6400 L-shape it would if it were visible+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(9000);+ });++ it("respects outlines visible through a transparent element on top", () => {+ // same geometry, but `owner` is transparent, so the lower rectangle's+ // outline shows through and splits the region+ const lower = API.createElement({+ type: "rectangle",+ x: 40,+ y: 40,+ width: 100,+ height: 100,+ roundness: null,+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ const { elements, elementsMap } = setup([lower, owner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(20, 20),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // the visible outline carves out the overlap corner => ~6400 L-shape+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(6000);+ expect(polygonArea(result.scenePoints)).toBeLessThan(7000);+ });++ it("ignores a text element's never-rendered backgroundColor", () => {+ // text elements inherit currentItemBackgroundColor on creation but never+ // paint it — such a text box overlapping the owner outline must neither+ // cover (clip) the outline nor act as a boundary+ const owner = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ const text = API.createElement({+ type: "text",+ x: 80,+ y: 40,+ width: 60,+ height: 25,+ backgroundColor: "#ffec99",+ });+ const { elements, elementsMap } = setup([owner, text]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -1);+ });++ it("does not treat a hachure-filled element as covering", () => {+ // hachure fill is see-through: the lower outline stays visible through it+ // and must still act as a boundary+ const lower = API.createElement({+ type: "rectangle",+ x: 40,+ y: 40,+ width: 100,+ height: 100,+ roundness: null,+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "#ffd43b",+ fillStyle: "hachure",+ });+ const { elements, elementsMap } = setup([lower, owner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(20, 20),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // the outline visible through the hachure carves out the overlap corner+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(6000);+ expect(polygonArea(result.scenePoints)).toBeLessThan(7000);+ });++ it("does not treat a semi-transparent element as covering", () => {+ const lower = API.createElement({+ type: "rectangle",+ x: 40,+ y: 40,+ width: 100,+ height: 100,+ roundness: null,+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "#ffd43b",+ opacity: 50,+ });+ const { elements, elementsMap } = setup([lower, owner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(20, 20),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // the outline blended through the 50% fill still bounds the region+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(6000);+ expect(polygonArea(result.scenePoints)).toBeLessThan(7000);+ });++ it.each([+ ["#RRGGBBAA hex", "#ffd43b80"],+ ["rgba()", "rgba(255, 212, 59, 0.5)"],+ ])(+ "does not treat a partial-alpha (%s) background as covering",+ (_label, backgroundColor) => {+ // same scene as the semi-transparent test, but the translucency comes+ // from the COLOR's alpha channel at full element opacity — the outline+ // blended through it is just as visible and must still bound the region+ const lower = API.createElement({+ type: "rectangle",+ x: 40,+ y: 40,+ width: 100,+ height: 100,+ roundness: null,+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor,+ });+ const { elements, elementsMap } = setup([lower, owner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(20, 20),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(6000);+ expect(polygonArea(result.scenePoints)).toBeLessThan(7000);+ },+ );++ it("fills the whole top element when clicking an opaque overlap", () => {+ // clicking the overlap of two OPAQUE shapes fills the whole top shape, not+ // the small overlap: the lower outline is hidden behind the top shape's+ // opaque fill, so it does not subdivide the visible region+ const lower = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "#ffd43b",+ });+ const top = API.createElement({+ type: "rectangle",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "#ffd43b",+ });+ const { elements, elementsMap } = setup([lower, top]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(75, 75), // inside the 50x50 overlap+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBe(top.id);+ // the whole top rectangle (~10000), NOT the 50x50 overlap (~2500)+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(9000);+ // the opaque owner would hide a fill beneath it => above it+ expect(result.insertion).toEqual({+ placement: "above",+ elementId: top.id,+ });+ });++ it("fills a rounded owner partially covered by a thin opaque overlap", () => {+ // regression: a thin opaque coverer crossing the owner's ROUNDED corners+ // left sub-pixel gaps in the clipped outline, opening the region. The+ // gapTolerance-based node merging in the arrangement bridges them.+ const rounded = { type: ROUNDNESS.ADAPTIVE_RADIUS } as const;+ const owner = API.createElement({+ type: "rectangle",+ x: 180,+ y: 650,+ width: 240,+ height: 195,+ roundness: rounded,+ backgroundColor: "#ffd43b",+ });+ const sideways = API.createElement({+ type: "rectangle",+ x: 5,+ y: 690,+ width: 230,+ height: 160,+ roundness: rounded,+ backgroundColor: "#ffd43b",+ });+ // thin opaque cover: its bottom edge overlaps the owner's top by ~5px,+ // crossing the owner's rounded top corners+ const cover = API.createElement({+ type: "rectangle",+ x: 110,+ y: 510,+ width: 245,+ height: 145,+ roundness: rounded,+ backgroundColor: "#a5d8ff",+ });+ const { elements, elementsMap } = setup([sideways, owner, cover]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(300, 740),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBe(owner.id);+ });++ it("fills a region enclosed only by open lines (owner-less)", () => {+ // 4 open lines forming a diamond; no closed element anywhere+ const mkLine = (pts: [number, number][]) =>+ API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: pts.map(([x, y]) => pointFrom<LocalPoint>(x, y)),+ });+ const l1 = mkLine([+ [50, 0],+ [100, 50],+ ]);+ const l2 = mkLine([+ [100, 50],+ [50, 100],+ ]);+ const l3 = mkLine([+ [50, 100],+ [0, 50],+ ]);+ const l4 = mkLine([+ [0, 50],+ [50, 0],+ ]);+ const { elements, elementsMap } = setup([l1, l2, l3, l4]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBeNull();+ expect(result.boundaryElementIds.sort()).toEqual(+ [l1.id, l2.id, l3.id, l4.id].sort(),+ );+ expect(isClosed(result.scenePoints)).toBe(true);+ // diamond with diagonals 100 => area 5000+ expect(polygonArea(result.scenePoints)).toBeCloseTo(5000, -3);+ });++ it("fills a loop formed by a single self-crossing open polyline", () => {+ // open polyline that crosses itself, enclosing a triangle+ const line = API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(100, 100),+ pointFrom<LocalPoint>(0, 100),+ pointFrom<LocalPoint>(100, 0),+ ],+ });+ const { elements, elementsMap } = setup([line]);++ // click inside the enclosed lower triangle (50,50)-(0,100)-(100,100)...+ // actually the loop is the triangle between the two crossing diagonals+ // and the bottom edge; its centroid is around (50, 83)+ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 80),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBeNull();+ expect(result.boundaryElementIds).toEqual([line.id]);+ // triangle (50,50)-(0,100)-(100,100) => area 2500+ expect(polygonArea(result.scenePoints)).toBeCloseTo(2500, -3);+ });++ it("fills a region closed by an open line against a shape's outside wall", () => {+ // an open V-line whose two ends touch the rectangle's right edge,+ // enclosing a region OUTSIDE the rectangle+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ const line = API.createElement({+ type: "line",+ x: 100,+ y: 20,+ width: 60,+ height: 60,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(60, 30),+ pointFrom<LocalPoint>(0, 60),+ ],+ });+ const { elements, elementsMap } = setup([rect, line]);++ // inside the triangle right of the rectangle's wall+ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(115, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBeNull();+ expect(result.boundaryElementIds.sort()).toEqual([line.id, rect.id].sort());+ // triangle (100,20)-(160,50)-(100,80) => area 1800+ expect(polygonArea(result.scenePoints)).toBeCloseTo(1800, -3);+ });++ it("fills only the clicked lobe of a self-intersecting (figure-eight) polygon", () => {+ const line = API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(100, 100),+ pointFrom<LocalPoint>(100, 0),+ pointFrom<LocalPoint>(0, 100),+ pointFrom<LocalPoint>(0, 0),+ ],+ polygon: true,+ });+ const { elements, elementsMap } = setup([line]);++ // left lobe: triangle (0,0)-(50,50)-(0,100), centroid ~(17, 50)+ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(17, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // one lobe (area 2500), not the whole figure-eight+ expect(polygonArea(result.scenePoints)).toBeCloseTo(2500, -3);+ });++ it("handles a line retracing part of the owner's edge (collinear overlap)", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ // line running exactly along the rect's top edge, extending past it+ const retrace = API.createElement({+ type: "line",+ x: -50,+ y: 0,+ width: 200,+ height: 0,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)],+ });+ const { elements, elementsMap } = setup([rect, retrace]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBe(rect.id);+ expect(isClosed(result.scenePoints)).toBe(true);+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -3);+ });++ it("bridges endpoint gaps up to gapTolerance without distorting the shape", () => {+ // triangle of open lines whose corners have ~5px gaps: bridged by the+ // default tolerance (8), unfillable with a stricter one+ const mkLine = (pts: [number, number][]) =>+ API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: pts.map(([x, y]) => pointFrom<LocalPoint>(x, y)),+ });+ const l1 = mkLine([+ [4, 0],+ [96, 0],+ ]);+ const l2 = mkLine([+ [100, 4],+ [52, 96],+ ]);+ const l3 = mkLine([+ [48, 96],+ [0, 4],+ ]);+ const { elements, elementsMap } = setup([l1, l2, l3]);+ const point = pointFrom<GlobalPoint>(50, 30);++ const result = computeBucketFillPolygon({ point, elements, elementsMap });+ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // fidelity: gaps are closed by ADDING connector edges, never by moving+ // vertices — every polygon vertex must lie (near-)on one of the strokes,+ // not be dragged toward a merged corner position+ const strokes = [+ lineSegment(pointFrom<GlobalPoint>(4, 0), pointFrom<GlobalPoint>(96, 0)),+ lineSegment(+ pointFrom<GlobalPoint>(100, 4),+ pointFrom<GlobalPoint>(52, 96),+ ),+ lineSegment(pointFrom<GlobalPoint>(48, 96), pointFrom<GlobalPoint>(0, 4)),+ ];+ for (const vertex of result.scenePoints) {+ const distance = Math.min(+ ...strokes.map((stroke) => distanceToLineSegment(vertex, stroke)),+ );+ expect(distance).toBeLessThanOrEqual(2);+ }++ const strict = computeBucketFillPolygon({+ point,+ elements,+ elementsMap,+ options: { gapTolerance: 2 },+ });+ expect(strict.ok).toBe(false);+ });++ it("bridges a stroke ending short of a long edge at the projection point", () => {+ // chord stopping 6px short of both rectangle walls: the nearest NODES on+ // those walls are the far-away corners, so bridging must split the wall+ // edge at the chord end's projection instead of snapping to a corner+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ const chord = API.createElement({+ type: "line",+ x: 6,+ y: 50,+ width: 88,+ height: 0,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(88, 0)],+ });+ const { elements, elementsMap } = setup([rect, chord]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 25),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // upper half of the rectangle, not the whole thing+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(4500);+ expect(polygonArea(result.scenePoints)).toBeLessThan(5500);+ });++ it("bounds bridge-grid indexing for scene-spanning edges", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ // The chord needs the bridge grid to reach both rectangle walls.+ const chord = API.createElement({+ type: "line",+ x: 6,+ y: 50,+ width: 88,+ height: 0,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(88, 0)],+ });+ // This open line's bounds touch the owner's local search area, so its full+ // million-pixel span joins the arrangement even though it does not bound+ // the clicked face.+ const sceneSpanning = API.createElement({+ type: "line",+ x: -500_000,+ y: 105,+ width: 1_000_000,+ height: 0,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(1_000_000, 0),+ ],+ });+ const { elements, elementsMap } = setup([rect, chord, sceneSpanning]);++ const originalSet = Map.prototype.set;+ let spatialBucketSets = 0;+ const setSpy = vi+ .spyOn(Map.prototype, "set")+ .mockImplementation(function (this: Map<unknown, unknown>, key, value) {+ if (typeof key === "string" && /^-?\d+:-?\d+$/.test(key)) {+ spatialBucketSets++;+ if (spatialBucketSets > 512) {+ throw new Error("spatial grid exceeded its bucket budget");+ }+ }+ return originalSet.call(this, key, value);+ });++ const result = (() => {+ try {+ return computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 25),+ elements,+ elementsMap,+ });+ } finally {+ setSpy.mockRestore();+ }+ })();++ expect(result.ok).toBe(true);+ expect(spatialBucketSets).toBeLessThanOrEqual(512);+ if (result.ok) {+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(4500);+ expect(polygonArea(result.scenePoints)).toBeLessThan(5500);+ }+ });++ const lineSquare = (half: number) => {+ const mkLine = (x: number, y: number, dx: number, dy: number) =>+ API.createElement({+ type: "line",+ x,+ y,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(dx, dy)],+ });+ return [+ mkLine(-half, -half, 2 * half, 0),+ mkLine(half, -half, 0, 2 * half),+ mkLine(half, half, -2 * half, 0),+ mkLine(-half, half, 0, -2 * half),+ ] as NonDeletedExcalidrawElement[];+ };++ it("the owner-less fallback keeps expanding past an empty first radius", () => {+ // regression: an empty candidate set at the first radius used to return+ // no_owner immediately — a 2,000px square of open lines around the+ // click has all its strokes beyond the initial 512px box+ const { elements, elementsMap } = setup(lineSquare(1000));++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(0, 0),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeCloseTo(4_000_000, -5);+ });++ it("the owner-less fallback accepts a complete face touching the frontier", () => {+ // regression: all four lines fit the first 512px box, but the ring's+ // vertices at ±508 graze the frontier — with every eligible element+ // already in range the face is complete and must be accepted, not+ // rejected as possibly-unfinished+ const { elements, elementsMap } = setup(lineSquare(508));++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(0, 0),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeCloseTo(1016 * 1016, -4);+ });++ it("a fully invisible closed element cannot own a fill", () => {+ // regression: a rect with transparent stroke AND transparent background+ // renders no pixels — clicking the seemingly empty canvas used to+ // conjure a fill out of it+ const ghost = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ strokeColor: "transparent",+ backgroundColor: "transparent",+ });+ const { elements, elementsMap } = setup([ghost]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result).toEqual({ ok: false, reason: "no_owner" });+ });++ it("returns no_owner for open canvas", () => {+ const { elements, elementsMap } = setup([]);+ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(10, 10),+ elements,+ elementsMap,+ });+ expect(result).toEqual({ ok: false, reason: "no_owner" });+ });++ it("returns no_owner when clicking outside every closed shape", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 50,+ height: 50,+ roundness: null,+ });+ const { elements, elementsMap } = setup([rect]);+ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(500, 500),+ elements,+ elementsMap,+ });+ expect(result.ok).toBe(false);+ });++ it("returns too_complex when the segment cap is exceeded", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ const { elements, elementsMap } = setup([rect]);+ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ options: { maxBoundarySegments: 2 },+ });+ expect(result).toEqual({ ok: false, reason: "too_complex" });+ });++ it("does not re-enumerate dense segment pairs in every spatial cell", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ // Every divider occupies roughly 100 grid cells. Enumerating all pairs+ // independently in every shared cell turns these 1,000 segments into+ // ~50 million pair visits despite there being only ~500,000 pairs.+ const dividers = Array.from({ length: 1000 }, () =>+ API.createElement({+ type: "line",+ x: -10,+ y: 50,+ width: 120,+ height: 0,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(120, 0)],+ }),+ );+ const { elements, elementsMap } = setup([rect, ...dividers]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 25),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeCloseTo(5000, -1);+ }, 2000);++ it("fill-compatible paint never becomes the owner", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ });+ // a strokeless bg polygon (what a generated fill is — no marker, fills+ // are recognized by shape) sitting ON TOP of the rect. Hachure, so it+ // exercises the ownership exclusion in isolation without also acting+ // as an opaque coverer that would clip the rect's coincident outline+ const priorFill = API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(100, 0),+ pointFrom<LocalPoint>(100, 100),+ pointFrom<LocalPoint>(0, 100),+ pointFrom<LocalPoint>(0, 0),+ ],+ polygon: true,+ backgroundColor: "#b2f2bb",+ fillStyle: "hachure",+ strokeColor: "transparent",+ });+ const { elements, elementsMap } = setup([rect, priorFill]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // owner is the rectangle, not the paint on top of it+ expect(result.ownerId).toBe(rect.id);+ });++ it("inserts below a visible non-contributor inside the region", () => {+ // a floating line inside the rect doesn't subdivide the region (its+ // dangling chain forms no face), so it isn't a contributor — but it's+ // visible, and an opaque fill above it would bury it+ const floating = API.createElement({+ type: "line",+ x: 30,+ y: 50,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(40, 0)],+ });+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ // scene order: line lowest — the fill must slot in below it+ const { elements, elementsMap } = setup([floating, rect]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(10, 10),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.insertion).toEqual({+ placement: "below",+ elementId: floating.id,+ });+ });++ it("inserts below a text label inside the region", () => {+ const label = API.createElement({+ type: "text",+ x: 30,+ y: 40,+ text: "hi",+ });+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ const { elements, elementsMap } = setup([label, rect]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(10, 10),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.insertion).toEqual({+ placement: "below",+ elementId: label.id,+ });+ });++ it("inserts above a covering non-participant (sub-region refill)", () => {+ // whole-rect fill exists; a line then subdivides the region and the top+ // half is filled anew — the new fill must go ABOVE the old opaque fill+ // (not below the participants, where the old fill would hide it)+ const oldFill = API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(100, 0),+ pointFrom<LocalPoint>(100, 100),+ pointFrom<LocalPoint>(0, 100),+ pointFrom<LocalPoint>(0, 0),+ ],+ polygon: true,+ backgroundColor: "#b2f2bb",+ fillStyle: "solid",+ strokeColor: "transparent",+ });+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ const splitter = API.createElement({+ type: "line",+ x: -5,+ y: 50,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(110, 0)],+ });+ const { elements, elementsMap } = setup([oldFill, rect, splitter]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 25),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.insertion).toEqual({+ placement: "above",+ elementId: oldFill.id,+ });+ });++ it("inserts above a coverer straddling the region edge (center outside)", () => {+ // regression: the coverer constraint must be evaluated for EVERY+ // element — an opaque strokeless rect straddling the region edge+ // contains the click while being neither a participant nor (with its+ // center outside the region) a sampled in-region mark; gating the+ // coverer check on those buried the fill beneath it+ const line = API.createElement({+ type: "line",+ x: -20,+ y: 100,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(240, 0)],+ strokeColor: "#1e1e1e",+ });+ const coverer = API.createElement({+ type: "rectangle",+ x: 160,+ y: 20,+ width: 100,+ height: 60,+ roundness: null,+ backgroundColor: "#ffc9c9",+ fillStyle: "solid",+ strokeColor: "transparent",+ });+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 200,+ height: 200,+ roundness: null,+ backgroundColor: "transparent",+ });+ // z-order: line (lowest), coverer, rect — the rect on top keeps the+ // coverer from clipping any face boundary+ const { elements, elementsMap } = setup([line, coverer, rect]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(170, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.insertion).toEqual({+ placement: "above",+ elementId: coverer.id,+ });+ });++ it("inserts above an opaque coverer overlapping the region away from the click", () => {+ // same trio as above, but the click lands OUTSIDE the coverer: after a+ // fill the region must read uniformly filled (the raster flood-fill+ // outcome), so opaque paint overlapping the region anywhere — not just+ // under the click — must not poke through the new fill+ const line = API.createElement({+ type: "line",+ x: -20,+ y: 100,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(240, 0)],+ strokeColor: "#1e1e1e",+ });+ const coverer = API.createElement({+ type: "rectangle",+ x: 150,+ y: 20,+ width: 110,+ height: 60,+ roundness: null,+ backgroundColor: "#a5d8ff",+ fillStyle: "solid",+ strokeColor: "transparent",+ });+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 200,+ height: 200,+ roundness: null,+ backgroundColor: "transparent",+ });+ const { elements, elementsMap } = setup([line, coverer, rect]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(60, 50),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.insertion).toEqual({+ placement: "above",+ elementId: coverer.id,+ });+ });++ it("an opaque prior fill hides strokes beneath it from new fills", () => {+ // the line crossing the rect would normally split it in two — but it+ // lies UNDER an opaque fill, so the user can't see it and it must not+ // stop the new fill either+ const buried = API.createElement({+ type: "line",+ x: -5,+ y: 50,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(110, 0)],+ });+ const priorFill = API.createElement({+ type: "line",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(100, 0),+ pointFrom<LocalPoint>(100, 100),+ pointFrom<LocalPoint>(0, 100),+ pointFrom<LocalPoint>(0, 0),+ ],+ polygon: true,+ backgroundColor: "#b2f2bb",+ fillStyle: "solid",+ strokeColor: "transparent",+ });+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ // realistic fill stacking: buried line lowest, fill above it, owner on top+ const { elements, elementsMap } = setup([buried, priorFill, rect]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(50, 25),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // the whole rect, not the top half the buried line would carve out+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -2);+ expect(result.boundaryElementIds).not.toContain(buried.id);+ });++ // a fill's polygon runs along the CENTERLINE of the strokes that bound it,+ // so once the fill counts as a coverer, a clip test without a boundary+ // margin eats those strokes on the next click and adjacent regions merge+ // (or the region falls open). Rounded corners are what trigger it: the+ // sampled arc midpoints land inside the fill ring within simplification+ // jitter. See final-review-04.md §11.+ it("a fill does not clip the strokes that bound it (fill-then-fill, transparent container on top)", () => {+ const upper = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: { type: ROUNDNESS.ADAPTIVE_RADIUS },+ backgroundColor: "#ffd43b",+ fillStyle: "solid",+ });+ const lower = API.createElement({+ type: "rectangle",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ roundness: { type: ROUNDNESS.ADAPTIVE_RADIUS },+ backgroundColor: "transparent",+ });++ // step 1: click the overlap — the lens between the two containers+ const first = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(75, 75),+ ...setup([upper, lower]),+ });+ expect(first.ok).toBe(true);+ if (!first.ok) {+ return;+ }+ expect(polygonArea(first.scenePoints)).toBeGreaterThan(2000);+ expect(polygonArea(first.scenePoints)).toBeLessThan(2600);+ expect(first.insertion).toEqual({+ placement: "above",+ elementId: upper.id,+ });++ // step 2: materialize the lens fill at its computed insertion and click+ // the lower container's remaining region+ const second = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(120, 120),+ ...setup([upper, materializeFill(first.scenePoints), lower]),+ });+ expect(second.ok).toBe(true);+ if (!second.ok) {+ return;+ }+ // the lower container MINUS the lens (~7270), not the whole container+ // (~9530 — the regression: the fill flooded through the lens)+ expect(polygonArea(second.scenePoints)).toBeGreaterThan(6900);+ expect(polygonArea(second.scenePoints)).toBeLessThan(7700);+ });++ it("a fill does not clip the strokes that bound it (fill-then-fill, opaque container on top)", () => {+ const lower = API.createElement({+ type: "rectangle",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ roundness: { type: ROUNDNESS.ADAPTIVE_RADIUS },+ backgroundColor: "transparent",+ });+ const upper = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: { type: ROUNDNESS.ADAPTIVE_RADIUS },+ backgroundColor: "#ffd43b",+ fillStyle: "solid",+ });++ // step 1: click the overlap — the opaque container is on top, so the+ // region is its whole footprint+ const first = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(75, 75),+ ...setup([lower, upper]),+ });+ expect(first.ok).toBe(true);+ if (!first.ok) {+ return;+ }+ expect(polygonArea(first.scenePoints)).toBeGreaterThan(9000);+ expect(polygonArea(first.scenePoints)).toBeLessThan(10000);+ expect(first.insertion).toEqual({+ placement: "above",+ elementId: upper.id,+ });++ // step 2: click the lower container's remaining region — before the+ // boundary-margin fix this failed outright (`open_region`)+ const second = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(120, 120),+ ...setup([lower, upper, materializeFill(first.scenePoints)]),+ });+ expect(second.ok).toBe(true);+ if (!second.ok) {+ return;+ }+ expect(polygonArea(second.scenePoints)).toBeGreaterThan(6900);+ expect(polygonArea(second.scenePoints)).toBeLessThan(7700);+ });++ it("isRestylableFill accepts strokeless bg polygons covering the region", () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ const { elements, elementsMap } = setup([rect]);+ const click = pointFrom<GlobalPoint>(50, 50);+ const result = computeBucketFillPolygon({+ point: click,+ elements,+ elementsMap,+ });+ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ const scenePoints = result.scenePoints;++ // NOTE deliberately no `customData.bucketFill` — restylability is+ // shape-based (the marker goes stale once the user restyles a fill)+ const mkFill = (size: number, overrides: object = {}) =>+ API.createElement({+ type: "line",+ x: 0,+ y: 0,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(size, 0),+ pointFrom<LocalPoint>(size, size),+ pointFrom<LocalPoint>(0, size),+ pointFrom<LocalPoint>(0, 0),+ ],+ polygon: true,+ backgroundColor: "#b2f2bb",+ fillStyle: "solid",+ strokeColor: "transparent",+ ...overrides,+ });++ // fill-like polygon covering the clicked region -> restylable+ const fill = mkFill(100);+ expect(+ isRestylableFill({+ hitElement: fill,+ scenePoints,+ elementsMap: setup([fill, rect]).elementsMap,+ }),+ ).toBe(true);++ // a fill the user gave a visible stroke has been repurposed into an+ // outline (it participates as a boundary instead) -> not restylable+ const stroked = mkFill(100, { strokeColor: "#1e1e1e" });+ expect(+ isRestylableFill({+ hitElement: stroked,+ scenePoints,+ elementsMap: setup([stroked, rect]).elementsMap,+ }),+ ).toBe(false);++ // covers a smaller region than the computed one -> not restylable+ const subRegion = mkFill(20);+ expect(+ isRestylableFill({+ hitElement: subRegion,+ scenePoints,+ elementsMap: setup([subRegion, rect]).elementsMap,+ }),+ ).toBe(false);++ // a plain shape is never restylable+ expect(+ isRestylableFill({+ hitElement: rect,+ scenePoints,+ elementsMap,+ }),+ ).toBe(false);+ });++ it("a fill given a visible stroke afterwards acts as a boundary", () => {+ const strokedFill = API.createElement({+ type: "line",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(100, 0),+ pointFrom<LocalPoint>(100, 100),+ pointFrom<LocalPoint>(0, 100),+ pointFrom<LocalPoint>(0, 0),+ ],+ polygon: true,+ backgroundColor: "#b2f2bb",+ fillStyle: "solid",+ strokeColor: "#1e1e1e",+ });+ const outer = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 200,+ height: 200,+ roundness: null,+ backgroundColor: "transparent",+ });+ const { elements, elementsMap } = setup([strokedFill, outer]);++ const annulus = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(25, 100),+ elements,+ elementsMap,+ });++ expect(annulus.ok).toBe(true);+ if (!annulus.ok) {+ return;+ }+ // the stroked fill is a visible outline now: it islands the region+ expect(polygonArea(annulus.scenePoints)).toBeCloseTo(30000, -2);+ expect(annulus.boundaryElementIds).toContain(strokedFill.id);++ // ...but a fill still never becomes an OWNER: clicking inside it falls+ // through to the rect while the fill's outline bounds the region+ const inside = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(100, 100),+ elements,+ elementsMap,+ });+ expect(inside.ok).toBe(true);+ if (!inside.ok) {+ return;+ }+ expect(inside.ownerId).toBe(outer.id);+ expect(polygonArea(inside.scenePoints)).toBeCloseTo(10000, -2);+ });++ it("fills a sparse freedraw along its rendered (smoothed) centerline", () => {+ // raw freedraw points can sit 20px+ apart; the renderer draws a+ // streamline-smoothed path between them, so the fill boundary must+ // sample that same path, not the raw chords (which visibly poke out)+ // prettier-ignore+ const CIRCLE_POINTS: [number, number][] = [[240,120],[238.18,140.84],[232.76,161.04],[223.92,180],[211.93,197.13],[197.13,211.93],[180,223.92],[161.04,232.76],[140.84,238.18],[120,240],[99.16,238.18],[78.96,232.76],[60,223.92],[42.87,211.93],[28.07,197.13],[16.08,180],[7.24,161.04],[1.82,140.84],[0,120],[1.82,99.16],[7.24,78.96],[16.08,60],[28.07,42.87],[42.87,28.07],[60,16.08],[78.96,7.24],[99.16,1.82],[120,0],[140.84,1.82],[161.04,7.24],[180,16.08],[197.13,28.07],[211.93,42.87],[223.92,60],[232.76,78.96],[238.18,99.16],[239.93,115.81]];+ const circle = API.createElement({+ type: "freedraw",+ x: 0,+ y: 0,+ width: 240,+ height: 240,+ points: CIRCLE_POINTS.map((p) => pointFrom<LocalPoint>(p[0], p[1])),+ });+ const { elements, elementsMap } = setup([+ circle as NonDeletedExcalidrawElement,+ ]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(120, 120),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ const distToPolyline = (p: GlobalPoint, poly: [number, number][]) => {+ let best = Infinity;+ for (let i = 0; i < poly.length - 1; i++) {+ const [ax, ay] = poly[i];+ const [bx, by] = poly[i + 1];+ const dx = bx - ax;+ const dy = by - ay;+ const l2 = dx * dx + dy * dy;+ const t = l2+ ? Math.max(0, Math.min(1, ((p[0] - ax) * dx + (p[1] - ay) * dy) / l2))+ : 0;+ best = Math.min(+ best,+ Math.hypot(p[0] - (ax + t * dx), p[1] - (ay + t * dy)),+ );+ }+ return best;+ };+ const rawPolyline = [...CIRCLE_POINTS, CIRCLE_POINTS[0]];+ const smoothedPolyline = [+ ...getFreedrawStrokeCenterPoints(circle),+ CIRCLE_POINTS[0],+ ] as [number, number][];+ // every fill vertex lies ON the smoothed centerline (RDP only removes+ // vertices, it never moves them)...+ const deviationFromSmoothed = Math.max(+ ...result.scenePoints.map((v) => distToPolyline(v, smoothedPolyline)),+ );+ expect(deviationFromSmoothed).toBeLessThan(0.5);+ // ...and measurably OFF the raw polyline, proving the boundary follows+ // the rendered path rather than the raw chords+ const deviationFromRaw = Math.max(+ ...result.scenePoints.map((v) => distToPolyline(v, rawPolyline)),+ );+ expect(deviationFromRaw).toBeGreaterThan(1.5);+ });++ it("fills a freedraw whose closure only exists in the smoothed stroke", () => {+ // real-world repro: the raw ends sit ~21px apart and ~14px from the+ // rest of the raw path — but the RENDERED (smoothed) stroke passes+ // within ~3px of its own tail, which reads as visually closed and must+ // be bridgeable+ // prettier-ignore+ const BLOB_POINTS: [number, number][] = [[0,0],[0,-0.3],[0,-0.6],[-0.6,-0.6],[-2.1,-0.6],[-4.7,-0.6],[-7.9,-0.6],[-11.2,0.3],[-18.2,3.8],[-26.2,7.9],[-33.8,13.2],[-42.3,20.0],[-50.9,27.6],[-56.7,34.7],[-62.0,43.5],[-63.2,50.3],[-63.8,54.7],[-60.0,60.3],[-51.7,65.3],[-38.2,69.1],[-21.5,72.3],[-3.5,73.8],[16.5,75.0],[36.7,75.0],[66.7,75.0],[74.4,75.8],[76.1,75.8],[76.1,76.1],[75.6,76.7],[71.1,77.9],[59.7,80.5],[46.2,85.0],[33.5,89.1],[21.2,95.0],[12.6,101.1],[6.8,106.7],[4.4,112.6],[4.4,116.4],[5.6,119.9],[10.3,124.1],[18.8,127.3],[32.0,129.6],[47.3,131.7],[62.6,131.7],[80.5,131.7],[97.3,129.1],[114.4,126.4],[139.0,123.5],[147.0,122.0],[150.2,122.0],[152.9,121.7],[154.6,120.2],[155.8,118.5],[157.9,114.1],[162.0,104.9],[167.0,93.2],[172.3,81.4],[177.3,69.7],[181.4,60.6],[184.6,52.0],[186.4,46.2],[187.3,42.3],[187.8,39.7],[187.8,37.6],[187.8,36.2],[185.5,34.4],[181.1,32.0],[172.9,29.4],[158.7,25.0],[144.3,21.8],[128.2,19.1],[100.0,14.4],[90.8,13.2],[86.7,12.1],[85.8,11.5],[85.5,11.5],[85.5,11.2],[86.1,10.9],[87.6,9.7],[88.8,7.9],[89.4,6.5],[89.4,5.6],[89.4,4.4],[86.7,2.9],[81.4,1.5],[74.1,0.3],[62.6,-0.6],[50.9,-1.2],[42.0,-1.2],[31.7,-1.2],[23.2,-0.6],[17.1,0.6],[12.1,1.5],[9.7,2.1],[8.5,2.1],[7.9,2.1],[7.6,2.1],[7.3,2.1],[6.5,1.5],[4.7,0],[1.8,-1.2],[-1.5,-2.4],[-5.6,-2.9],[-10.0,-3.8],[-14.7,-4.1],[-17.6,-4.4],[-21.5,-5.3],[-23.8,-5.6],[-25.6,-5.9],[-26.8,-6.2],[-27.0,-6.2],[-27.3,-6.2],[-27.3,-5.3],[-27.3,-4.4],[-26.8,-2.9],[-25.9,-1.5],[-24.7,-0.3],[-24.1,0.3],[-23.2,1.2],[-22.6,1.5],[-22.0,1.8],[-21.8,2.1],[-21.5,2.1],[-21.5,2.1]];+ const blob = API.createElement({+ type: "freedraw",+ x: 0,+ y: 0,+ width: 252,+ height: 138,+ points: BLOB_POINTS.map((p) => pointFrom<LocalPoint>(p[0], p[1])),+ });+ const { elements, elementsMap } = setup([+ blob as NonDeletedExcalidrawElement,+ ]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(126, 69),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeGreaterThan(15000);+ });++ describe("islands (holes)", () => {+ const rect = (x: number, y: number, size: number) =>+ API.createElement({+ type: "rectangle",+ x,+ y,+ width: size,+ height: size,+ roundness: null,+ backgroundColor: "transparent",+ });++ // NOTE: `polygonArea` (abs shoelace) doubles as the NET area for keyhole+ // rings — the zero-width bridges cancel and holes subtract++ /**+ * containment under the even-odd rule — the rule the renderer paints+ * looped-line fills with, so this asserts what actually shows on screen+ */+ const evenOddContains = (pts: GlobalPoint[], p: GlobalPoint): boolean =>+ polygonIncludesPoint(p, pts as unknown as Polygon<GlobalPoint>);++ it("punches a hole for an island inside the filled region", () => {+ const outer = rect(0, 0, 200);+ const inner = rect(50, 50, 100);+ const { elements, elementsMap } = setup([outer, inner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(25, 100), // in the annulus+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // annulus, not the whole outer interior (which would be ~40000)+ expect(polygonArea(result.scenePoints)).toBeCloseTo(30000, -2);+ expect(isClosed(result.scenePoints)).toBe(true);+ // the island bounds the fill too+ expect(result.boundaryElementIds).toContain(inner.id);+ // and participates in z-order: below the lowest participant+ expect(result.insertion).toEqual({+ placement: "below",+ elementId: outer.id,+ });+ });++ it("clicking inside the island still fills just the island", () => {+ const outer = rect(0, 0, 200);+ const inner = rect(50, 50, 100);+ const { elements, elementsMap } = setup([outer, inner]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(100, 100),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.ownerId).toBe(inner.id);+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -2);+ });++ it("subtracts only outermost islands (island-in-island)", () => {+ const outer = rect(0, 0, 300);+ const middle = rect(50, 50, 200);+ const innermost = rect(100, 100, 100);+ const { elements, elementsMap } = setup([outer, middle, innermost]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(25, 150), // outer annulus+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // outer minus middle; the innermost sits inside the hole and is+ // irrelevant to the clicked region+ expect(polygonArea(result.scenePoints)).toBeCloseTo(90000 - 40000, -2);+ });++ it("subtracts a subdivided island by its outside contour", () => {+ const outer = rect(0, 0, 200);+ const inner = rect(50, 50, 100);+ // line splitting the island into two faces — the island's footprint+ // must still be subtracted as ONE contour+ const splitter = API.createElement({+ type: "line",+ x: 50,+ y: 100,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],+ });+ const { elements, elementsMap } = setup([outer, inner, splitter]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(25, 100),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeCloseTo(30000, -2);+ });++ it("an island connected to the boundary is not a hole", () => {+ const outer = rect(0, 0, 200);+ const inner = rect(50, 50, 100);+ // line connecting the island to the outer wall merges the components;+ // the click region becomes a C-shaped single face instead+ const connector = API.createElement({+ type: "line",+ x: 150,+ y: 100,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(50, 0)],+ });+ const { elements, elementsMap } = setup([outer, inner, connector]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(25, 100),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // same net region as the annulus, reached without any hole splicing+ expect(polygonArea(result.scenePoints)).toBeCloseTo(30000, -2);+ });++ it("an open line island does not punch a hole", () => {+ const owner = rect(0, 0, 100);+ const floating = API.createElement({+ type: "line",+ x: 30,+ y: 50,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(40, 0)],+ });+ const { elements, elementsMap } = setup([owner, floating]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(10, 10),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeCloseTo(10000, -2);+ });++ it("punches multiple sibling islands", () => {+ const outer = rect(0, 0, 300);+ const a = rect(30, 30, 80);+ const b = rect(190, 190, 80);+ const { elements, elementsMap } = setup([outer, a, b]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(150, 20),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(polygonArea(result.scenePoints)).toBeCloseTo(90000 - 2 * 6400, -2);+ expect(+ evenOddContains(result.scenePoints, pointFrom<GlobalPoint>(70, 70)),+ ).toBe(false);+ expect(+ evenOddContains(result.scenePoints, pointFrom<GlobalPoint>(230, 230)),+ ).toBe(false);+ expect(+ evenOddContains(result.scenePoints, pointFrom<GlobalPoint>(150, 150)),+ ).toBe(true);+ });++ it("overlapping islands punch their union regardless of element order", () => {+ // regression: bounded-vs-unbounded face orientation used to be+ // inferred from the largest |area| face, but the outermost outline's+ // interior and outside contour tie on |area|, making the outcome an+ // enumeration-order coin flip — overlapping islands then decomposed+ // into arbitrary sub-face "holes" (lenses filling, islands vanishing)+ const mkRect = (x: number, y: number) =>+ API.createElement({+ type: "rectangle",+ x,+ y,+ width: 120,+ height: 80,+ roundness: null,+ backgroundColor: "transparent",+ });+ const outer = rect(0, 0, 400);+ const a = mkRect(40, 100);+ const b = mkRect(140, 140);+ const c = mkRect(240, 100);++ for (const order of [+ [a, b, c, outer],+ [c, b, a, outer],+ [b, a, c, outer],+ ]) {+ const { elements, elementsMap } = setup(order);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(200, 30),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // outer minus the union: 3×(120×80) − two 20×40 lenses+ expect(polygonArea(result.scenePoints)).toBeCloseTo(+ 160000 - (3 * 9600 - 2 * 800),+ -2,+ );+ // what renders (even-odd): every part of the union is unpainted —+ // the lenses, the single-rect parts — and the outer region is painted+ expect(+ evenOddContains(result.scenePoints, pointFrom<GlobalPoint>(150, 160)),+ ).toBe(false); // a∩b lens+ expect(+ evenOddContains(result.scenePoints, pointFrom<GlobalPoint>(80, 140)),+ ).toBe(false); // a only+ expect(+ evenOddContains(result.scenePoints, pointFrom<GlobalPoint>(200, 170)),+ ).toBe(false); // b only+ expect(+ evenOddContains(result.scenePoints, pointFrom<GlobalPoint>(200, 30)),+ ).toBe(true); // outer region+ }+ });++ it("inserts below the island when the island is lowest in z-order", () => {+ const inner = rect(50, 50, 100);+ const outer = rect(0, 0, 200);+ // island BELOW the outer shape in scene order: the fill must still go+ // below the island so its outline stays visible+ const { elements, elementsMap } = setup([inner, outer]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(25, 100),+ elements,+ elementsMap,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ expect(result.insertion).toEqual({+ placement: "below",+ elementId: inner.id,+ });+ });++ it("a hole dropped for the point budget leaves boundaries but keeps z-order", () => {+ const inner = rect(50, 50, 100);+ const outer = rect(0, 0, 200);+ const { elements, elementsMap } = setup([inner, outer]);++ const result = computeBucketFillPolygon({+ point: pointFrom<GlobalPoint>(25, 100),+ elements,+ elementsMap,+ // the outer ring fits the cap, the hole does not+ options: { maxGeneratedPoints: 6 },+ });++ expect(result.ok).toBe(true);+ if (!result.ok) {+ return;+ }+ // the fill paints through the dropped island...+ expect(polygonArea(result.scenePoints)).toBeCloseTo(40000, -2);+ // ...so it must NOT claim the island as a boundary...+ expect(result.boundaryElementIds).not.toContain(inner.id);+ // ...but still inserts below it, keeping the painted-over island+ // visible (deliberate: see the participant-set note in the source)+ expect(result.insertion).toEqual({+ placement: "below",+ elementId: inner.id,+ });+ });+ });+});diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsxindex c7ee2751ca..3ea13e7b2a 100644--- a/packages/excalidraw/actions/actionProperties.tsx+++ b/packages/excalidraw/actions/actionProperties.tsx@@ -3,8 +3,11 @@ import { pointFrom } from "@excalidraw/math";import { useEffect, useMemo, useRef, useState } from "react";import {+ BUCKET_FILL_BACKGROUND_PICKS,+ COLOR_PALETTE,DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE,DEFAULT_ELEMENT_BACKGROUND_PICKS,+ getBucketFillBackgroundColor,DEFAULT_ELEMENT_STROKE_COLOR_PALETTE,DEFAULT_ELEMENT_STROKE_PICKS,ARROW_TYPE,@@ -486,6 +489,55 @@ export const actionChangeBackgroundColor = register<},});+export const actionChangeBucketFillBackgroundColor = register<+ Pick<AppState, "currentItemBackgroundColor">+>({+ name: "changeBucketFillBackgroundColor",+ label: "labels.changeBackground",+ trackEvent: false,+ // the bucket fill tool has no element to mutate; it shares+ // `currentItemBackgroundColor` but hides `transparent` (an invisible fill+ // would be a no-op) and shows the effective fallback color instead+ perform: (elements, appState, value) => {+ return {+ appState: {+ ...appState,+ ...value,+ },+ captureUpdate: CaptureUpdateAction.EVENTUALLY,+ };+ },+ PanelComponent: ({ elements, appState, updateData, app }) => {+ const { stylesPanelMode } = getStylesPanelInfo(app);++ return (+ <>+ {stylesPanelMode === "full" && (+ <h3 aria-hidden="true">{t("labels.background")}</h3>+ )}+ <ColorPicker+ topPicks={BUCKET_FILL_BACKGROUND_PICKS}+ palette={DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE}+ // hidden rather than removed from the palette so the remaining+ // colors keep their usual hotkeys (w for white etc.)+ excludedColors={[COLOR_PALETTE.transparent]}+ type="elementBackground"+ label={t("labels.background")}+ color={getBucketFillBackgroundColor(+ appState.currentItemBackgroundColor,+ )}+ onChange={(color) =>+ updateData({ currentItemBackgroundColor: color })+ }+ elements={elements}+ appState={appState}+ updateData={updateData}+ />+ </>+ );+ },+});+export const actionChangeFillStyle = register<ExcalidrawElement["fillStyle"]>({name: "changeFillStyle",label: "labels.fill",diff --git a/packages/excalidraw/actions/index.ts b/packages/excalidraw/actions/index.tsindex f1964e034b..6d2321ba0e 100644--- a/packages/excalidraw/actions/index.ts+++ b/packages/excalidraw/actions/index.ts@@ -10,6 +10,7 @@ export { actionDuplicateSelection } from "./actionDuplicateSelection";export {actionChangeStrokeColor,actionChangeBackgroundColor,+ actionChangeBucketFillBackgroundColor,actionChangeStrokeWidth,actionChangeFillStyle,actionChangeSloppiness,diff --git a/packages/excalidraw/actions/types.ts b/packages/excalidraw/actions/types.tsindex fa13b7a605..4f7cbd37c7 100644--- a/packages/excalidraw/actions/types.ts+++ b/packages/excalidraw/actions/types.ts@@ -64,6 +64,7 @@ export type ActionName =| "stats"| "changeStrokeColor"| "changeBackgroundColor"+ | "changeBucketFillBackgroundColor"| "changeFillStyle"| "changeStrokeWidth"| "changeSloppiness"diff --git a/packages/excalidraw/components/Actions.tsx b/packages/excalidraw/components/Actions.tsxindex eef96556c1..ec5133a38a 100644--- a/packages/excalidraw/components/Actions.tsx+++ b/packages/excalidraw/components/Actions.tsx@@ -152,6 +152,18 @@ export const SelectedShapeActions = ({app,);+ // the bucket fill tool configures only the fill it creates: color, fill+ // style, and opacity (shared `currentItem*` values; no stroke properties)+ if (appState.activeTool.type === "bucketfill") {+ return (+ <div className="selected-shape-actions">+ <div>{renderAction("changeBucketFillBackgroundColor")}</div>+ {renderAction("changeFillStyle")}+ {renderAction("changeOpacity")}+ </div>+ );+ }+return (<div className="selected-shape-actions"><div>{predicates.strokeColor && renderAction("changeStrokeColor")}</div>@@ -626,10 +638,14 @@ export const CompactShapeActions = ({</div>)}- {/* Background Color */}+ {/* Background Color (the bucket fill variant excludes `transparent`) */}{predicates.backgroundColor && (<div className="compact-action-item">- {renderAction("changeBackgroundColor")}+ {renderAction(+ appState.activeTool.type === "bucketfill"+ ? "changeBucketFillBackgroundColor"+ : "changeBackgroundColor",+ )}</div>)}@@ -780,9 +796,14 @@ export const MobileShapeActions = ({{renderAction("changeStrokeColor")}</div>)}+ {/* Background Color (the bucket fill variant excludes `transparent`) */}{predicates.backgroundColor && (<div className="compact-action-item">- {renderAction("changeBackgroundColor")}+ {renderAction(+ appState.activeTool.type === "bucketfill"+ ? "changeBucketFillBackgroundColor"+ : "changeBackgroundColor",+ )}</div>)}<CombinedShapePropertiesdiff --git a/packages/excalidraw/components/App.bucketFill.ts b/packages/excalidraw/components/App.bucketFill.tsnew file mode 100644index 0000000000..a16324ac72--- /dev/null+++ b/packages/excalidraw/components/App.bucketFill.ts@@ -0,0 +1,220 @@+import {+ getBucketFillBackgroundColor,+ getSizeFromPoints,+} from "@excalidraw/common";+import { pointFrom, type GlobalPoint, type LocalPoint } from "@excalidraw/math";++import {+ computeBucketFillPolygon,+ isBucketFillCompatible,+ isFrameLikeElement,+ isRestylableFill,+ newLinearElement,+ ShapeCache,+} from "@excalidraw/element";++import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";++import { t } from "../i18n";++import type App from "./App";++type ScenePoint = {+ x: number;+ y: number;+};++/** Owns bucket-fill interaction and App-bound scene mutations. */+export class AppBucketFill {+ constructor(private app: App) {}++ /**+ * The click armed on pointer down, committed on pointer up. Deferring the+ * scene mutation to pointer up is what lets a pinch/pan second finger, a+ * long-press context menu, or a pointercancel abort the fill — on pointer+ * down the editor cannot yet know the gesture will stay a single-pointer+ * click.+ */+ private pending: ScenePoint | null = null;++ /** Arm a fill at the pointer-down position; nothing mutates yet. */+ handlePointerDown = (scenePointer: ScenePoint) => {+ this.pending = scenePointer;+ };++ /**+ * Commit the armed fill, at the pointer-DOWN position (what the user+ * aimed at). No-op when the gesture was aborted in the meantime.+ */+ handlePointerUp = () => {+ const scenePointer = this.pending;+ this.pending = null;+ if (scenePointer) {+ this.fill(scenePointer);+ }+ };++ /** Abort the armed fill (second finger, context menu, pointercancel). */+ cancel = () => {+ this.pending = null;+ };++ /**+ * Apply the current bucket fill settings to an existing fill-compatible+ * element (no-op when nothing would change). One undoable step.+ */+ private restyle = (element: NonDeletedExcalidrawElement) => {+ const backgroundColor = getBucketFillBackgroundColor(+ this.app.state.currentItemBackgroundColor,+ );+ if (+ element.backgroundColor === backgroundColor &&+ element.fillStyle === this.app.state.currentItemFillStyle &&+ element.opacity === this.app.state.currentItemOpacity+ ) {+ return;+ }+ this.app.scene.mutateElement(element, {+ backgroundColor,+ fillStyle: this.app.state.currentItemFillStyle,+ opacity: this.app.state.currentItemOpacity,+ });+ // the roughjs drawable is cached by element reference; in-place+ // mutation keeps the reference, so evict it or the canvas won't+ // reflect the new style+ ShapeCache.delete(element);+ this.app.scheduleCapture();+ };++ private fill = (scenePointer: ScenePoint) => {+ // shared with the generic shape background, but a transparent fill would+ // be invisible, so fall back to a real color (appState is not mutated)+ const backgroundColor = getBucketFillBackgroundColor(+ this.app.state.currentItemBackgroundColor,+ );++ const elements = this.app.scene.getNonDeletedElements();+ const elementsMap = this.app.scene.getNonDeletedElementsMap();+ const point = pointFrom<GlobalPoint>(scenePointer.x, scenePointer.y);++ const hitElement = this.app.getElementAtPosition(point[0], point[1]);++ // gap bridging is covered by the default gapTolerance (a bucket-specific+ // constant): connector edges close visual gaps without distorting the+ // shape, so no zoom-dependent tuning is needed+ const result = computeBucketFillPolygon({ point, elements, elementsMap });++ if (!result.ok) {+ // no region could be derived, but the click still landed on existing+ // paint (e.g. an orphaned fill whose boundaries were deleted, or a+ // hand-drawn strokeless bg polygon on empty canvas) — restyling it is+ // the sensible outcome, and beats a toast+ if (hitElement && isBucketFillCompatible(hitElement)) {+ this.restyle(hitElement);+ return;+ }+ if (result.reason === "too_complex") {+ this.app.setToast({+ message: t("bucketfill.tooComplex"),+ duration: 3000,+ });+ } else if (+ result.reason === "open_region" ||+ result.reason === "too_small" ||+ result.reason === "invalid_polygon"+ ) {+ this.app.setToast({+ message: t("bucketfill.noRegion"),+ duration: 3000,+ });+ }+ // "no_owner" stays silent — clicking empty canvas shouldn't nag+ return;+ }++ // re-clicking an already-filled region shouldn't stack a duplicate:+ // restyle the existing fill with the current settings, or no-op when+ // nothing would change+ if (+ hitElement &&+ isRestylableFill({+ hitElement,+ scenePoints: result.scenePoints,+ elementsMap,+ })+ ) {+ this.restyle(hitElement);+ return;+ }++ const { width, height } = getSizeFromPoints(result.scenePoints);+ // linear elements are normalized so points[0] must be [0, 0]; use the+ // first scene point as the element origin+ const [originX, originY] = result.scenePoints[0];+ const points = result.scenePoints.map((p) =>+ pointFrom<LocalPoint>(p[0] - originX, p[1] - originY),+ );++ const owner = result.ownerId ? elementsMap.get(result.ownerId) : null;+ // owner-less fills (regions formed by open lines) take their frame from+ // the click position and only inherit a group shared by every boundary+ const frameId = owner+ ? isFrameLikeElement(owner)+ ? owner.id+ : owner.frameId+ : this.app.getTopLayerFrameAtSceneCoords(scenePointer)?.id ?? null;+ const groupIds = owner+ ? owner.groupIds+ : result.boundaryElementIds+ .map((id) => elementsMap.get(id)?.groupIds)+ .filter((groupIds): groupIds is string[] => !!groupIds)+ .reduce(+ (common, groupIds) =>+ common === null+ ? groupIds+ : common.filter((groupId) => groupIds.includes(groupId)),+ null as string[] | null,+ ) ?? [];++ const fill = newLinearElement({+ type: "line",+ x: originX,+ y: originY,+ width,+ height,+ points,+ polygon: true,+ strokeColor: "transparent",+ backgroundColor,+ fillStyle: this.app.state.currentItemFillStyle,+ strokeWidth: 1,+ strokeStyle: "solid",+ roughness: 0,+ roundness: null,+ opacity: this.app.state.currentItemOpacity,+ frameId,+ groupIds,+ // no marker: fills are recognized by shape (`isBucketFillCompatible`),+ // since metadata would go stale the moment the user restyles the fill+ });++ // resolve the geometry's relative placement against the+ // deleted-inclusive array that `insertElementsAtIndex` operates on+ const anchorIndex = this.app.scene+ .getElementsIncludingDeleted()+ .findIndex((el) => el.id === result.insertion.elementId);+ this.app.scene.insertElementsAtIndex(+ [fill],+ anchorIndex < 0+ ? null+ : result.insertion.placement === "above"+ ? anchorIndex + 1+ : anchorIndex,+ );++ // Keep the bucket fill tool active and do NOT select the new fill, so the+ // user can keep filling regions back-to-back without re-selecting the tool+ // (even when the tool isn't locked).+ this.app.scheduleCapture();+ };+}diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex cb8320118b..a6fc3572a9 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -432,6 +432,7 @@ import ConvertElementTypePopup, {import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";import { AppArrowText } from "./App.arrowText";+import { AppBucketFill } from "./App.bucketFill";import { AppCursor } from "./App.cursor";import { AppDrawShape } from "./App.drawshape";import { AppFlowchart } from "./App.flowchart";@@ -681,6 +682,7 @@ class App extends React.Component<AppProps, AppState> {public onStateChange: OnStateChange = this.appStateObserver.onStateChange;+ public bucketFill: AppBucketFill = new AppBucketFill(this);public flowchart: AppFlowchart = new AppFlowchart(this);public cursor: AppCursor = new AppCursor(this);public arrowText: AppArrowText = new AppArrowText(this);@@ -3085,6 +3087,8 @@ class App extends React.Component<AppProps, AppState> {}});+ public scheduleCapture = () => this.store.scheduleCapture();+// Lifecycleprivate onBlur = withBatchedUpdates(() => {@@ -4981,6 +4985,12 @@ class App extends React.Component<AppProps, AppState> {this.resetContextMenuTimer();}+ if (event.type === "pointercancel") {+ // the browser took the pointer over (scroll, palm rejection) — no+ // pointerup will follow, so the armed bucket fill must not commit+ this.bucketFill.cancel();+ }+const wasMultiTouchGesture = gesture.pointers.size >= 2;gesture.pointers.delete(event.pointerId);@@ -6427,7 +6437,7 @@ class App extends React.Component<AppProps, AppState> {};// NOTE: Hot path for hit testing, so avoid unnecessary computations- getElementAtPosition(+ public getElementAtPosition(x: number,y: number,opts?: (@@ -7399,7 +7409,7 @@ class App extends React.Component<AppProps, AppState> {* finds candidate frame under cursor (when dragging frame children/elements* inside frames)*/- private getTopLayerFrameAtSceneCoords = (+ public getTopLayerFrameAtSceneCoords = (/*** should be already grid aligned (basically should be what the call site* sets the element's coords to, if applicable)@@ -8716,6 +8726,17 @@ class App extends React.Component<AppProps, AppState> {);} else if (this.state.activeTool.type === "autoshape") {this.drawShape.handlePointerDown(pointerDownState);+ } else if (this.state.activeTool.type === TOOL_TYPE.bucketfill) {+ // one-shot click tool: pointer down only ARMS the fill — it commits in+ // the shared pointer-up teardown, and only when the interaction stayed+ // a single-pointer click (a second finger, a context menu, or a+ // pointercancel aborts it). Dispatched like any other tool (laser has+ // the same shape) so the shared pointer lifecycle below — public+ // onPointerDown/onPointerUp callbacks, pointer-up teardown,+ // missing-pointer-up cleanup — runs for bucket clicks too. In view+ // mode this branch is unreachable:+ // `handleCanvasPanUsingWheelOrSpaceDrag` swallows the pointer-down.+ this.bucketFill.handlePointerDown(scenePointer);} else if (this.state.activeTool.type !== "eraser" &&this.state.activeTool.type !== "hand" &&@@ -11376,6 +11397,20 @@ class App extends React.Component<AppProps, AppState> {if (pointerDownState.eventListeners.onMove) {pointerDownState.eventListeners.onMove.flush();}++ // an armed bucket fill commits only on a GENUINE pointer up. The+ // missing-pointer-up cleanup replays this handler with the pointer+ // DOWN event (e.g. when a second finger lands mid-press — pinch/pan+ // intent), and a tool switch mid-press orphans the click — both must+ // discard the fill instead of committing an unwanted edit.+ if (+ childEvent.type === "pointerup" &&+ this.state.activeTool.type === TOOL_TYPE.bucketfill+ ) {+ this.bucketFill.handlePointerUp();+ } else {+ this.bucketFill.cancel();+ }const {newElement,resizingElement,@@ -12347,6 +12382,9 @@ class App extends React.Component<AppProps, AppState> {if (!this.isToolLocked() &&activeTool.type !== "freedraw" &&+ // bucket fill stays active for back-to-back fills regardless of the+ // tool lock (paint-bucket UX)+ activeTool.type !== TOOL_TYPE.bucketfill &&(activeTool.type !== "lasso" ||// if lasso is turned on but from selection => reset to selection(activeTool.type === "lasso" && activeTool.fromSelection))@@ -13078,6 +13116,10 @@ class App extends React.Component<AppProps, AppState> {return;}+ // a context menu during a press (touch long-press) means the user is+ // not committing a bucket click+ this.bucketFill.cancel();+if ((("pointerType" in event.nativeEvent &&event.nativeEvent.pointerType === "touch") ||diff --git a/packages/excalidraw/components/ColorPicker/ColorPicker.tsx b/packages/excalidraw/components/ColorPicker/ColorPicker.tsxindex f15d7eb38f..9c2697c846 100644--- a/packages/excalidraw/components/ColorPicker/ColorPicker.tsx+++ b/packages/excalidraw/components/ColorPicker/ColorPicker.tsx@@ -52,6 +52,8 @@ interface ColorPickerProps {palette?: ColorPaletteCustom | null;topPicks?: ColorTuple;updateData: (formData?: any) => void;+ /** palette colors to hide from the popup, keeping hotkey positions */+ excludedColors?: readonly string[];}const ColorPickerPopupContent = ({@@ -64,6 +66,7 @@ const ColorPickerPopupContent = ({updateData,getOpenPopup,appState,+ excludedColors,}: Pick<ColorPickerProps,| "type"@@ -74,6 +77,7 @@ const ColorPickerPopupContent = ({| "palette"| "updateData"| "appState"+ | "excludedColors"> & {getOpenPopup: () => AppState["openPopup"];}) => {@@ -151,6 +155,7 @@ const ColorPickerPopupContent = ({<Pickerref={colorPickerContentRef}palette={palette}+ excludedColors={excludedColors}color={color}onChange={(changedColor) => {// Save caret position before color change if editing text@@ -289,6 +294,7 @@ export const ColorPicker = ({topPicks,updateData,appState,+ excludedColors,}: ColorPickerProps) => {const openRef = useRef(appState.openPopup);useEffect(() => {@@ -352,6 +358,7 @@ export const ColorPicker = ({label={label}elements={elements}palette={palette}+ excludedColors={excludedColors}updateData={updateData}getOpenPopup={() => openRef.current}appState={appState}diff --git a/packages/excalidraw/components/ColorPicker/Picker.tsx b/packages/excalidraw/components/ColorPicker/Picker.tsxindex 9c48c58075..34d306e74d 100644--- a/packages/excalidraw/components/ColorPicker/Picker.tsx+++ b/packages/excalidraw/components/ColorPicker/Picker.tsx@@ -41,6 +41,7 @@ interface PickerProps {onEyeDropperToggle: (force?: boolean) => void;onEscape: (event: React.KeyboardEvent | KeyboardEvent) => void;showHotKey?: boolean;+ excludedColors?: readonly string[];}export const Picker = React.forwardRef(@@ -57,6 +58,7 @@ export const Picker = React.forwardRef(onEyeDropperToggle,onEscape,showHotKey = true,+ excludedColors,}: PickerProps,ref,) => {@@ -155,6 +157,7 @@ export const Picker = React.forwardRef(updateData,activeShade,onEscape,+ excludedColors,});if (handled) {@@ -190,6 +193,7 @@ export const Picker = React.forwardRef(onChange={onChange}activeShade={activeShade}showHotKey={showHotKey}+ excludedColors={excludedColors}/></div>diff --git a/packages/excalidraw/components/ColorPicker/PickerColorList.tsx b/packages/excalidraw/components/ColorPicker/PickerColorList.tsxindex 13928f0239..3253ddef30 100644--- a/packages/excalidraw/components/ColorPicker/PickerColorList.tsx+++ b/packages/excalidraw/components/ColorPicker/PickerColorList.tsx@@ -21,6 +21,11 @@ interface PickerColorListProps {onChange: (color: string) => void;activeShade: number;showHotKey?: boolean;+ /**+ * palette colors to hide. Hidden entries keep their position in the hotkey+ * order (their hotkey goes dead instead of remapping the colors after them).+ */+ excludedColors?: readonly string[];}const PickerColorList = ({@@ -29,6 +34,7 @@ const PickerColorList = ({onChange,activeShade,showHotKey = true,+ excludedColors,}: PickerColorListProps) => {const colorObj = getColorNameAndShadeFromColor({color,@@ -52,6 +58,19 @@ const PickerColorList = ({const color =(Array.isArray(value) ? value[activeShade] : value) || "transparent";+ if (excludedColors?.includes(color)) {+ // invisible placeholder so the remaining colors keep their exact+ // grid positions (and hotkeys) — muscle memory stays intact+ return (+ <div+ key={key}+ className="color-picker__button color-picker__button--large"+ style={{ visibility: "hidden" }}+ aria-hidden="true"+ />+ );+ }+const keybinding = colorPickerHotkeyBindings[index];const label = t(`colors.${key.replace(/\d+/, "")}` as unknown as TranslationKeys,diff --git a/packages/excalidraw/components/ColorPicker/colorPickerUtils.ts b/packages/excalidraw/components/ColorPicker/colorPickerUtils.tsindex fee8f8cfc2..cfda429534 100644--- a/packages/excalidraw/components/ColorPicker/colorPickerUtils.ts+++ b/packages/excalidraw/components/ColorPicker/colorPickerUtils.ts@@ -1,4 +1,7 @@-import { MAX_CUSTOM_COLORS_USED_IN_CANVAS } from "@excalidraw/common";+import {+ isTransparent,+ MAX_CUSTOM_COLORS_USED_IN_CANVAS,+} from "@excalidraw/common";import type { ExcalidrawElement } from "@excalidraw/element/types";@@ -67,7 +70,9 @@ export const getMostUsedCustomColors = (const color =element[elementColorTypeMap[type] as "backgroundColor" | "strokeColor"];- return isCustomColor({ color, palette });+ // fully-transparent colors are "no color", not a reusable custom color+ // (matters for palettes that exclude `transparent`, e.g. bucket fill)+ return !isTransparent(color) && isCustomColor({ color, palette });});const colorCountMap = new Map<string, number>();diff --git a/packages/excalidraw/components/ColorPicker/keyboardNavHandlers.ts b/packages/excalidraw/components/ColorPicker/keyboardNavHandlers.tsindex 15a2748f17..465e328783 100644--- a/packages/excalidraw/components/ColorPicker/keyboardNavHandlers.ts+++ b/packages/excalidraw/components/ColorPicker/keyboardNavHandlers.ts@@ -55,6 +55,7 @@ interface HotkeyHandlerProps {update: React.SetStateAction<ActiveColorPickerSectionAtomType>,) => void;activeShade: number;+ excludedColors?: readonly string[];}/**@@ -68,6 +69,7 @@ const hotkeyHandler = ({customColors,setActiveColorPickerSection,activeShade,+ excludedColors,}: HotkeyHandlerProps): boolean => {if (colorObj?.shade != null) {// shift + numpad is extremely messed up on windows apparently@@ -98,6 +100,14 @@ const hotkeyHandler = ({const r = Array.isArray(paletteValue)? paletteValue[activeShade]: paletteValue;+ // hotkeys of excluded (hidden) or absent palette entries are dead, not+ // remapped — this keeps every other color on its usual key. Still+ // HANDLED: within the modal's keyboard scope the key is deliberately+ // inert, and reporting it unhandled would let it escape to global+ // shortcuts (`q` toggles the tool lock)+ if (r == null || excludedColors?.includes(r)) {+ return true;+ }onChange(r);setActiveColorPickerSection("baseColors");return true;@@ -119,6 +129,7 @@ interface ColorPickerKeyNavHandlerProps {activeShade: number;onEyeDropperToggle: (force?: boolean) => void;onEscape: (event: React.KeyboardEvent | KeyboardEvent) => void;+ excludedColors?: readonly string[];}/**@@ -136,6 +147,7 @@ export const colorPickerKeyNavHandler = ({activeShade,onEyeDropperToggle,onEscape,+ excludedColors,}: ColorPickerKeyNavHandlerProps): boolean => {if (event[KEYS.CTRL_OR_CMD]) {return false;@@ -226,6 +238,7 @@ export const colorPickerKeyNavHandler = ({customColors,setActiveColorPickerSection,activeShade,+ excludedColors,})) {return true;@@ -249,12 +262,28 @@ export const colorPickerKeyNavHandler = ({const colorNames = Object.keys(palette) as (keyof ColorPalette)[];const indexOfColorName = colorNames.indexOf(colorName);- const newColorIndex = arrowHandler(+ let newColorIndex = arrowHandler(event.key,indexOfColorName,colorNames.length,);+ // step over excluded (hidden) palette entries, continuing in the+ // arrow's direction+ let guard = 0;+ while (newColorIndex !== undefined && guard++ < colorNames.length) {+ const value = palette[colorNames[newColorIndex]];+ const resolved = Array.isArray(value) ? value[activeShade] : value;+ if (!excludedColors?.includes(resolved)) {+ break;+ }+ newColorIndex = arrowHandler(+ event.key,+ newColorIndex,+ colorNames.length,+ );+ }+if (newColorIndex !== undefined) {const newColorName = colorNames[newColorIndex];const newColorNameValue = palette[newColorName];diff --git a/packages/excalidraw/components/HelpDialog.tsx b/packages/excalidraw/components/HelpDialog.tsxindex eb68326017..82d0032289 100644--- a/packages/excalidraw/components/HelpDialog.tsx+++ b/packages/excalidraw/components/HelpDialog.tsx@@ -186,6 +186,7 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {/><Shortcut label={t("toolBar.frame")} shortcuts={[KEYS.F]} /><Shortcut label={t("toolBar.laser")} shortcuts={[KEYS.K]} />+ <Shortcut label={t("toolBar.bucketfill")} shortcuts={[KEYS.B]} /><Shortcutlabel={t("labels.eyeDropper")}shortcuts={[KEYS.I, "Shift+S", "Shift+G"]}diff --git a/packages/excalidraw/components/MobileToolbar.tsx b/packages/excalidraw/components/MobileToolbar.tsxindex 40fee2965c..6591c95f0a 100644--- a/packages/excalidraw/components/MobileToolbar.tsx+++ b/packages/excalidraw/components/MobileToolbar.tsx@@ -30,6 +30,7 @@ import {EmbedIcon,laserPointerToolIcon,drawShapeToolIcon,+ bucketFillIcon,mermaidLogoIcon,MagicIcon,} from "./icons";@@ -76,6 +77,7 @@ export const MobileToolbar = ({ app, setAppState }: MobileToolbarProps) => {const drawShapeToolSelected = activeTool.type === "autoshape";const laserToolSelected = activeTool.type === "laser";const embeddableToolSelected = activeTool.type === "embeddable";+ const bucketFillToolSelected = activeTool.type === "bucketfill";const { TTDDialogTriggerTunnel } = useTunnels();@@ -110,7 +112,14 @@ export const MobileToolbar = ({ app, setAppState }: MobileToolbarProps) => {const showFrameToolOutside = toolbarWidth >= MIN_WIDTH + 3 * ADDITIONAL_WIDTH;const extraTools: readonly typeof activeTool.type[] = (- ["text", "frame", "embeddable", "laser", "magicframe"] as const+ [+ "text",+ "frame",+ "embeddable",+ "laser",+ "bucketfill",+ "magicframe",+ ] as const).filter((tool) => {if (showTextToolOutside && tool === "text") {return false;@@ -132,6 +141,8 @@ export const MobileToolbar = ({ app, setAppState }: MobileToolbarProps) => {? EmbedIcon: activeTool.type === "laser"? laserPointerToolIcon+ : activeTool.type === "bucketfill"+ ? bucketFillIcon: activeTool.type === "magicframe"? MagicIcon: DotsIcon@@ -308,6 +319,16 @@ export const MobileToolbar = ({ app, setAppState }: MobileToolbarProps) => {>{t("toolBar.laser")}</DropdownMenu.Item>+ <DropdownMenu.Item+ onSelect={() => app.setActiveTool({ type: "bucketfill" })}+ icon={bucketFillIcon}+ data-testid="toolbar-bucketfill"+ selected={bucketFillToolSelected}+ shortcut={KEYS.B.toLocaleUpperCase()}+ disabled={isToolButtonDisabled(app, "bucketfill")}+ >+ {t("toolBar.bucketfill")}+ </DropdownMenu.Item><div style={{ margin: "6px 0", fontSize: 14, fontWeight: 600 }}>Generate</div>diff --git a/packages/excalidraw/components/Toolbar.tsx b/packages/excalidraw/components/Toolbar.tsxindex d5d692cb12..cc85b8c0a2 100644--- a/packages/excalidraw/components/Toolbar.tsx+++ b/packages/excalidraw/components/Toolbar.tsx@@ -19,6 +19,7 @@ import {frameToolIcon,LassoIcon,laserPointerToolIcon,+ bucketFillIcon,MagicIcon,mermaidLogoIcon,DotsIcon,@@ -65,6 +66,7 @@ const ExtraToolsDropdown = ({const frameToolSelected = activeTool.type === "frame";const drawShapeToolSelected = activeTool.type === "autoshape";const laserToolSelected = activeTool.type === "laser";+ const bucketFillToolSelected = activeTool.type === "bucketfill";const lassoToolSelected =isFullStylesPanel &&activeTool.type === "lasso" &&@@ -80,6 +82,7 @@ const ExtraToolsDropdown = ({embeddableToolSelected ||(isFullStylesPanel && drawShapeToolSelected) ||lassoToolSelected ||+ bucketFillToolSelected ||// in collab we're already highlighting the laser button// outside toolbar, so let's not highlight extra-tools button// on top of it@@ -101,6 +104,8 @@ const ExtraToolsDropdown = ({? laserPointerToolIcon: lassoToolSelected? LassoIcon+ : bucketFillToolSelected+ ? bucketFillIcon: DotsIcon}</DropdownMenu.Trigger><DropdownMenu.Content@@ -147,6 +152,16 @@ const ExtraToolsDropdown = ({>{t("toolBar.laser")}</DropdownMenu.Item>+ <DropdownMenu.Item+ onSelect={() => app.setActiveTool({ type: "bucketfill" })}+ icon={bucketFillIcon}+ data-testid="toolbar-bucketfill"+ selected={bucketFillToolSelected}+ shortcut={KEYS.B.toLocaleUpperCase()}+ disabled={isToolButtonDisabled(app, "bucketfill")}+ >+ {t("toolBar.bucketfill")}+ </DropdownMenu.Item>{isFullStylesPanel && (<DropdownMenu.ItemonSelect={() => app.setActiveTool({ type: "lasso" })}diff --git a/packages/excalidraw/components/Tools.tsx b/packages/excalidraw/components/Tools.tsxindex 406c0fbea9..30930504ce 100644--- a/packages/excalidraw/components/Tools.tsx+++ b/packages/excalidraw/components/Tools.tsx@@ -24,6 +24,7 @@ import {ImageIcon,EraserIcon,laserPointerToolIcon,+ bucketFillIcon,LassoIcon,handIcon,frameToolIcon,@@ -143,6 +144,10 @@ export const TOOLS = defineTools({icon: laserPointerToolIcon,letterKey: KEYS.K,},+ bucketfill: {+ icon: bucketFillIcon,+ letterKey: KEYS.B,+ },lasso: {icon: LassoIcon,fillable: false,diff --git a/packages/excalidraw/components/shapeActionPredicates.ts b/packages/excalidraw/components/shapeActionPredicates.tsindex 94fcb988e6..f1857e4f4e 100644--- a/packages/excalidraw/components/shapeActionPredicates.ts+++ b/packages/excalidraw/components/shapeActionPredicates.ts@@ -113,6 +113,9 @@ export const getShapeActionPredicates = (strokeColor: canChangeStrokeColor(appState, targetElements),backgroundColor: canChangeBackgroundColor(appState, targetElements),fill:+ // bucket fill never renders transparent (it falls back to a real+ // color), so its fill style stays relevant either way+ activeToolType === "bucketfill" ||(hasBackground(activeToolType) &&!isTransparent(appState.currentItemBackgroundColor)) ||targetElements.some(diff --git a/packages/excalidraw/data/restore.ts b/packages/excalidraw/data/restore.tsindex a6987e9df6..2f51abd833 100644--- a/packages/excalidraw/data/restore.ts+++ b/packages/excalidraw/data/restore.ts@@ -219,6 +219,7 @@ export const AllowedExcalidrawActiveTools: Record<laser: false,autoshape: false,magicframe: false,+ bucketfill: true,};export type RestoredDataState = {diff --git a/packages/excalidraw/locales/en.json b/packages/excalidraw/locales/en.jsonindex 5535a2adba..62413515c0 100644--- a/packages/excalidraw/locales/en.json+++ b/packages/excalidraw/locales/en.json@@ -332,11 +332,16 @@"embeddable": "Web Embed","laser": "Laser pointer","autoshape": "Draw to shape",+ "bucketfill": "Bucket fill","hand": "Hand (panning tool)","extraTools": "More tools","mermaidToExcalidraw": "Mermaid to Excalidraw","convertElementType": "Toggle shape type"},+ "bucketfill": {+ "noRegion": "Couldn't find an enclosed region to fill here.",+ "tooComplex": "This region is too complex to fill."+ },"element": {"rectangle": "Rectangle","diamond": "Diamond",diff --git a/packages/excalidraw/tests/bucketFill.test.tsx b/packages/excalidraw/tests/bucketFill.test.tsxnew file mode 100644index 0000000000..f53a11634e--- /dev/null+++ b/packages/excalidraw/tests/bucketFill.test.tsx@@ -0,0 +1,707 @@+import { KEYS } from "@excalidraw/common";+import { CaptureUpdateAction } from "@excalidraw/element";+import { pointFrom } from "@excalidraw/math";++import type { LocalPoint } from "@excalidraw/math";++import type { ExcalidrawLineElement } from "@excalidraw/element/types";++import { Excalidraw } from "../index";++import { API } from "./helpers/api";+import { Keyboard, Pointer } from "./helpers/ui";+import {+ act,+ fireEvent,+ GlobalTestState,+ render,+ togglePopover,+} from "./test-utils";++const { h } = window;++const mouse = new Pointer("mouse");++const selectBucketFill = () => {+ act(() => {+ h.app.setActiveTool({ type: "bucketfill" });+ });+};++describe("bucket fill tool", () => {+ beforeAll(() => {+ // radix popovers (font family, color picker) need a ResizeObserver;+ // jsdom has none (same stub as test-utils' togglePopover)+ (global as any).ResizeObserver = class ResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ };+ });++ beforeEach(async () => {+ await render(<Excalidraw handleKeyboardGlobally={true} />);+ });++ const seedRectangle = () => {+ const rect = API.createElement({+ type: "rectangle",+ x: 20,+ y: 20,+ width: 120,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ // commit the owner as its own history increment so the bucket fill is a+ // separate, independently-undoable step+ act(() => {+ h.app.updateScene({+ elements: [rect],+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ });+ });+ return rect;+ };++ it("creates a unselected line polygon with the current background color", () => {+ const rect = seedRectangle();+ act(() => {+ // the bucket fill color is the shared shape background color+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);++ const fill = h.elements.find(+ (el) => el.type === "line" && !el.isDeleted,+ ) as ExcalidrawLineElement | undefined;++ expect(fill).toBeDefined();+ expect(fill!.polygon).toBe(true);+ expect(fill!.backgroundColor).toBe("#ffec99");+ expect(fill!.strokeColor).toBe("transparent");+ expect(fill!.fillStyle).toBe("solid");+ // no metadata marker: fills are recognized by shape, not provenance+ expect(fill!.customData).toBeUndefined();++ // linear elements must be normalized: points[0] === [0, 0], and the+ // polygon is explicitly closed+ expect(fill!.points[0]).toEqual([0, 0]);+ expect(fill!.points[fill!.points.length - 1]).toEqual([0, 0]);++ // inserted immediately below (before) the owner in z-order+ expect(h.elements[0].id).toBe(fill!.id);+ expect(h.elements[1].id).toBe(rect.id);++ // the fill is NOT selected and the tool stays active so the user can keep+ // filling regions back-to-back+ expect(h.state.selectedElementIds[fill!.id]).not.toBe(true);+ expect(h.state.activeTool.type).toBe("bucketfill");+ });++ it("fires the public onPointerDown/onPointerUp callbacks", async () => {+ // regression: the bucket branch used to early-return before the shared+ // pointer lifecycle, silently skipping the public callback contract+ const onPointerDown = vi.fn();+ const onPointerUp = vi.fn();+ await render(+ <Excalidraw+ handleKeyboardGlobally={true}+ onPointerDown={onPointerDown}+ onPointerUp={onPointerUp}+ />,+ );+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);++ expect(onPointerDown).toHaveBeenCalledTimes(1);+ expect(onPointerUp).toHaveBeenCalledTimes(1);+ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(1);+ });++ it("recovers from a lost pointer-up via the shared cleanup", () => {+ // regression: the old bespoke once-listener only reset pointer state on+ // a real pointer-up; the shared missing-pointer-up cleanup now covers+ // lost ones (e.g. window blurred mid-click)+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.downAt(80, 70);+ expect(h.state.cursorButton).toBe("down");++ act(() => {+ (h.app as any).maybeCleanupAfterMissingPointerUp(null);+ });+ expect(h.state.cursorButton).toBe("up");+ // the click never completed, so the armed fill is discarded — an+ // interrupted interaction must not leave a permanent edit+ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(0);+ mouse.upAt(80, 70);+ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(0);+ });++ it("dragging with the bucket tool neither selects nor creates extras", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.downAt(80, 70);+ mouse.moveTo(120, 100); // drag well past any threshold+ mouse.upAt(120, 100);++ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(1);+ expect(h.state.selectionElement).toBeNull();+ expect(Object.keys(h.state.selectedElementIds)).toHaveLength(0);+ expect(h.state.activeTool.type).toBe("bucketfill");+ });++ it("re-clicking a filled region does not stack a duplicate fill", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);+ mouse.clickAt(80, 70);++ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(1);+ });++ it("re-clicking with a changed color restyles the existing fill", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffc9c9" });+ });+ mouse.clickAt(80, 70);++ const fills = h.elements.filter(+ (el) => el.type === "line" && !el.isDeleted,+ );+ expect(fills).toHaveLength(1);+ expect(fills[0].backgroundColor).toBe("#ffc9c9");++ // the restyle is its own undoable step+ Keyboard.withModifierKeys({ ctrl: true }, () => {+ Keyboard.keyPress(KEYS.Z);+ });+ const afterUndo = h.elements.filter(+ (el) => el.type === "line" && !el.isDeleted,+ );+ expect(afterUndo).toHaveLength(1);+ expect(afterUndo[0].backgroundColor).toBe("#ffec99");+ });++ it("restyles an orphaned fill even when no region can be derived", () => {+ const rect = seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);++ // delete the rectangle: the fill's boundaries are gone, so no region+ // can be derived around the click anymore+ act(() => {+ h.app.updateScene({+ elements: h.elements.filter((el) => el.id !== rect.id),+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ });+ });+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffc9c9" });+ });++ mouse.clickAt(80, 70); // on the orphaned paint++ const fills = h.elements.filter(+ (el) => el.type === "line" && !el.isDeleted,+ );+ expect(fills).toHaveLength(1);+ expect(fills[0].backgroundColor).toBe("#ffc9c9");+ });++ it("clicking a since-subdivided part of a filled region creates a new fill", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70); // fill the whole rectangle++ // split the region with a line drawn afterwards+ const splitter = API.createElement({+ type: "line",+ x: 10,+ y: 70,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(140, 0)],+ });+ act(() => {+ h.app.updateScene({+ elements: [...h.elements, splitter],+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ });+ });++ mouse.clickAt(80, 45); // top half: a different (smaller) region now++ const fills = h.elements.filter(+ (el) => el.type === "line" && !el.isDeleted && el.id !== splitter.id,+ );+ expect(fills).toHaveLength(2);+ });++ it("can fill multiple regions in a row without re-selecting the tool", () => {+ const first = API.createElement({+ type: "rectangle",+ x: 20,+ y: 20,+ width: 100,+ height: 80,+ roundness: null,+ backgroundColor: "transparent",+ });+ const second = API.createElement({+ type: "rectangle",+ x: 200,+ y: 20,+ width: 100,+ height: 80,+ roundness: null,+ backgroundColor: "transparent",+ });+ act(() => {+ h.app.updateScene({+ elements: [first, second],+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ });+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(70, 60); // inside first+ expect(h.state.activeTool.type).toBe("bucketfill");+ mouse.clickAt(250, 60); // inside second, tool still active++ const fills = h.elements.filter(+ (el) => el.type === "line" && !el.isDeleted,+ );+ expect(fills).toHaveLength(2);+ expect(h.state.activeTool.type).toBe("bucketfill");+ });++ it("shows fill color, fill style and opacity in the panel when the tool is active", () => {+ seedRectangle();+ selectBucketFill();++ const panel = document.querySelector(".selected-shape-actions");+ expect(panel).not.toBeNull();+ // the fill (background) color picker is shown...+ expect(panel!.querySelector('[aria-label="Background"]')).not.toBeNull();+ // ...along with the fill style + opacity controls for the created fills...+ expect(panel!.querySelector('[data-testid="fill-hachure"]')).not.toBeNull();+ expect(panel!.querySelector('[data-testid="opacity"]')).not.toBeNull();+ // ...and nothing else from the generic shape panel (e.g. stroke)+ expect(panel!.querySelector('[aria-label="Stroke"]')).toBeNull();+ });++ it("uses the current fill style and opacity for created fills", () => {+ seedRectangle();+ act(() => {+ API.setAppState({+ currentItemBackgroundColor: "#ffec99",+ currentItemFillStyle: "hachure",+ currentItemOpacity: 60,+ });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);++ const fill = h.elements.find(+ (el) => el.type === "line" && !el.isDeleted,+ ) as ExcalidrawLineElement | undefined;+ expect(fill).toBeDefined();+ expect(fill!.fillStyle).toBe("hachure");+ expect(fill!.opacity).toBe(60);+ });++ it("selects the tool with the b shortcut", () => {+ expect(h.state.activeTool.type).toBe("selection");+ Keyboard.keyPress(KEYS.B);+ expect(h.state.activeTool.type).toBe("bucketfill");+ });++ it("opens the background color popup with the g shortcut", () => {+ selectBucketFill();+ Keyboard.keyPress(KEYS.G);+ expect(h.state.openPopup).toBe("elementBackground");+ });++ it("swallows the hidden transparent entry's hotkey (q) inside the picker", () => {+ // regression: the hidden transparent entry's `q` returned "unhandled",+ // so the picker didn't stop propagation and App.onKeyDown toggled the+ // global tool lock while the color dialog was open+ seedRectangle();+ selectBucketFill();+ togglePopover("Background");++ const picker = document.querySelector(".color-picker-content")!;+ expect(picker).not.toBeNull();+ expect(h.state.activeTool.locked).toBe(false);+ const before = h.state.currentItemBackgroundColor;++ // `q` maps to the hidden transparent swatch AND to the global tool-lock+ // shortcut — inside the modal it must be dead, not leaked+ fireEvent.keyDown(picker, { key: "q" });+ expect(h.state.activeTool.locked).toBe(false);+ expect(h.state.currentItemBackgroundColor).toBe(before);++ // the other hotkeys keep working on their usual keys (w = white)+ fireEvent.keyDown(picker, { key: "w" });+ expect(h.state.currentItemBackgroundColor).not.toBe(before);+ expect(h.state.currentItemBackgroundColor).not.toBe("transparent");+ });++ it("shift+f opens the font popup instead of switching to bucket fill", () => {+ // regression: bucket fill was originally bound to shift+f, shadowing the+ // long-standing "show fonts" shortcut for text elements+ const text = API.createElement({ type: "text", x: 20, y: 20 });+ act(() => {+ h.app.updateScene({+ elements: [text],+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ });+ API.setAppState({ selectedElementIds: { [text.id]: true } });+ });++ Keyboard.withModifierKeys({ shift: true }, () => {+ Keyboard.keyPress("F");+ });++ expect(h.state.activeTool.type).not.toBe("bucketfill");+ expect(h.state.openPopup).toBe("fontFamily");+ });++ it("falls back to green when the shared background color is transparent", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "transparent" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);++ const fill = h.elements.find(+ (el) => el.type === "line" && !el.isDeleted,+ ) as ExcalidrawLineElement | undefined;+ expect(fill).toBeDefined();+ expect(fill!.backgroundColor).toBe("#b2f2bb");+ // the shared appState value is left untouched+ expect(h.state.currentItemBackgroundColor).toBe("transparent");+ });++ it("inserts the overlap fill below the lowest participating shape", () => {+ const below = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ act(() => {+ h.app.updateScene({+ elements: [below, owner],+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ });+ });+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ // click the overlap lens (inside both rectangles)+ mouse.clickAt(75, 75);++ const fill = h.elements.find((el) => el.type === "line" && !el.isDeleted)!;+ expect(fill).toBeDefined();+ // both rectangles bound the lens, so the fill goes below the lower one+ expect(h.elements[0].id).toBe(fill.id);+ expect(h.elements[1].id).toBe(below.id);+ expect(h.elements[2].id).toBe(owner.id);+ });++ it("inserts the fill above a participant whose opaque background covers it", () => {+ // lower rectangle is filled red: its background would hide a fill placed+ // beneath it, so the bucket fill must go above it (but below the+ // transparent owner, whose outline should stay visible)+ const below = API.createElement({+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "#ff0000",+ });+ const owner = API.createElement({+ type: "rectangle",+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ roundness: null,+ backgroundColor: "transparent",+ });+ act(() => {+ h.app.updateScene({+ elements: [below, owner],+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ });+ });+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(75, 75);++ const fill = h.elements.find((el) => el.type === "line" && !el.isDeleted)!;+ expect(fill).toBeDefined();+ // order: below (red, covered) -> fill -> owner (transparent outline on top)+ expect(h.elements[0].id).toBe(below.id);+ expect(h.elements[1].id).toBe(fill.id);+ expect(h.elements[2].id).toBe(owner.id);+ });++ it("does nothing when clicking empty canvas", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(400, 400);++ expect(h.elements.filter((el) => el.type === "line")).toHaveLength(0);+ });++ it("does not fill on right-click or middle-click", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ for (const button of [1, 2]) {+ fireEvent.pointerDown(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ button,+ pointerId: 1,+ pointerType: "mouse",+ });+ fireEvent.pointerUp(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ button,+ pointerId: 1,+ pointerType: "mouse",+ });+ }++ expect(h.elements.filter((el) => el.type === "line")).toHaveLength(0);+ });++ it("a normal touch tap fills once, on release", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ fireEvent.pointerDown(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ button: 0,+ pointerId: 1,+ pointerType: "touch",+ });+ // the fill is only armed while the finger is down — nothing committed yet+ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(0);+ fireEvent.pointerUp(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ pointerId: 1,+ pointerType: "touch",+ });++ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(1);+ });++ it("a second touch pointer aborts the fill (pinch/pan intent)", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ fireEvent.pointerDown(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ button: 0,+ pointerId: 1,+ pointerType: "touch",+ });+ // a second finger lands while the first is still down+ fireEvent.pointerDown(GlobalTestState.interactiveCanvas, {+ clientX: 100,+ clientY: 90,+ button: 0,+ pointerId: 2,+ pointerType: "touch",+ });+ fireEvent.pointerUp(GlobalTestState.interactiveCanvas, {+ pointerId: 2,+ pointerType: "touch",+ });+ fireEvent.pointerUp(GlobalTestState.interactiveCanvas, {+ pointerId: 1,+ pointerType: "touch",+ });++ // the user meant to pinch/pan, not to fill — no permanent edit+ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(0);+ });++ it("pointercancel aborts the fill", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ fireEvent.pointerDown(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ button: 0,+ pointerId: 1,+ pointerType: "touch",+ });+ // the browser takes the pointer over (scroll, palm rejection) — no+ // pointerup will follow+ fireEvent.pointerCancel(GlobalTestState.interactiveCanvas, {+ pointerId: 1,+ pointerType: "touch",+ });++ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(0);++ // and the next tap fills normally+ fireEvent.pointerDown(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ button: 0,+ pointerId: 2,+ pointerType: "touch",+ });+ fireEvent.pointerUp(GlobalTestState.interactiveCanvas, {+ clientX: 80,+ clientY: 70,+ pointerId: 2,+ pointerType: "touch",+ });+ expect(+ h.elements.filter((el) => el.type === "line" && !el.isDeleted),+ ).toHaveLength(1);+ });++ it("does not fill in view mode", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();+ act(() => {+ API.setAppState({ viewModeEnabled: true });+ });++ mouse.clickAt(80, 70);++ expect(h.elements.filter((el) => el.type === "line")).toHaveLength(0);+ });++ it("undo removes the generated fill in one step", () => {+ seedRectangle();+ act(() => {+ API.setAppState({ currentItemBackgroundColor: "#ffec99" });+ });+ selectBucketFill();++ mouse.clickAt(80, 70);++ const fill = h.elements.find((el) => el.type === "line" && !el.isDeleted)!;+ expect(fill).toBeDefined();++ Keyboard.withModifierKeys({ ctrl: true }, () => {+ Keyboard.keyPress(KEYS.Z);+ });++ expect(+ h.elements.find((el) => el.id === fill.id && !el.isDeleted),+ ).toBeUndefined();+ // the owner rectangle survives+ expect(+ h.elements.filter((el) => el.type === "rectangle" && !el.isDeleted),+ ).toHaveLength(1);+ });+});diff --git a/packages/excalidraw/tests/colorPickerHotkeys.test.ts b/packages/excalidraw/tests/colorPickerHotkeys.test.tsnew file mode 100644index 0000000000..84347eb0d3--- /dev/null+++ b/packages/excalidraw/tests/colorPickerHotkeys.test.ts@@ -0,0 +1,82 @@+import { COLOR_PALETTE } from "@excalidraw/common";++import type { ColorPaletteCustom } from "@excalidraw/common";++import { colorPickerKeyNavHandler } from "../components/ColorPicker/keyboardNavHandlers";++const handlerArgs = (+ key: string,+ palette: ColorPaletteCustom,+ onChange: (color: string) => void,+ excludedColors?: readonly string[],+) => ({+ event: {+ key,+ ctrlKey: false,+ metaKey: false,+ shiftKey: false,+ preventDefault: () => {},+ stopPropagation: () => {},+ } as unknown as React.KeyboardEvent,+ activeColorPickerSection: null,+ palette,+ color: null,+ onChange,+ customColors: [],+ setActiveColorPickerSection: () => {},+ updateData: () => {},+ activeShade: 1,+ onEyeDropperToggle: () => {},+ onEscape: () => {},+ excludedColors,+});++describe("color picker hotkeys", () => {+ it("reports an excluded (hidden) entry's hotkey as handled without selecting it", () => {+ // regression: returning "unhandled" let the key escape the modal and hit+ // global shortcuts (`q` toggles the tool lock; see the integration+ // regression in bucketFill.test.tsx)+ const onChange = vi.fn();+ const palette = {+ transparent: COLOR_PALETTE.transparent,+ red: "#ff0000",+ } as ColorPaletteCustom;++ const handled = colorPickerKeyNavHandler(+ handlerArgs("q", palette, onChange, [COLOR_PALETTE.transparent]),+ );++ expect(handled).toBe(true);+ expect(onChange).not.toHaveBeenCalled();+ });++ it("reports a hotkey past the end of a short custom palette as handled", () => {+ // a host-provided palette with fewer entries than hotkey bindings must+ // not leak the unbound keys either+ const onChange = vi.fn();+ const palette = { red: "#ff0000" } as ColorPaletteCustom;++ // `b` is the 15th binding — far past the single palette entry+ const handled = colorPickerKeyNavHandler(+ handlerArgs("b", palette, onChange),+ );++ expect(handled).toBe(true);+ expect(onChange).not.toHaveBeenCalled();+ });++ it("still selects a present, non-excluded entry", () => {+ const onChange = vi.fn();+ const palette = {+ transparent: COLOR_PALETTE.transparent,+ red: "#ff0000",+ } as ColorPaletteCustom;++ const handled = colorPickerKeyNavHandler(+ handlerArgs("w", palette, onChange, [COLOR_PALETTE.transparent]),+ );++ expect(handled).toBe(true);+ expect(onChange).toHaveBeenCalledWith("#ff0000");+ });+});diff --git a/packages/excalidraw/tests/helpers/api.ts b/packages/excalidraw/tests/helpers/api.tsindex b3a857a4c3..3459d715c7 100644--- a/packages/excalidraw/tests/helpers/api.ts+++ b/packages/excalidraw/tests/helpers/api.ts@@ -207,6 +207,7 @@ export class API {? ExcalidrawTextElement["containerId"]: never;points?: T extends "arrow" | "line" | "freedraw" ? readonly LocalPoint[] : never;+ polygon?: T extends "line" ? boolean : never;strokeOptions?: T extends "freedraw"? ExcalidrawFreeDrawElement["strokeOptions"]: never;@@ -358,6 +359,7 @@ export class API {pointFrom<LocalPoint>(0, 0),pointFrom<LocalPoint>(100, 100),],+ polygon: rest.polygon,});break;case "image":diff --git a/packages/excalidraw/tests/selection.test.tsx b/packages/excalidraw/tests/selection.test.tsxindex 2db5732375..6447c10909 100644--- a/packages/excalidraw/tests/selection.test.tsx+++ b/packages/excalidraw/tests/selection.test.tsx@@ -1351,7 +1351,8 @@ describe("tool locking & selection", () => {// no top-level toolbar button (rendered in the extra-tools dropdown)value !== "frame" &&value !== "embeddable" &&- value !== "autoshape"+ value !== "autoshape" &&+ value !== "bucketfill") {const element = UI.createElement(value);expect(h.state.selectedElementIds[element.id]).not.toBe(true);diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.tsindex 0ef9b3cf78..48bce3bfb3 100644--- a/packages/excalidraw/types.ts+++ b/packages/excalidraw/types.ts@@ -161,7 +161,8 @@ export type ToolType =| "magicframe"| "embeddable"| "laser"- | "autoshape";+ | "autoshape"+ | "bucketfill";export type ElementOrToolType = ExcalidrawElementType | ToolType | "custom";diff --git a/packages/math/src/polygon.ts b/packages/math/src/polygon.tsindex d7deead303..63b187d24b 100644--- a/packages/math/src/polygon.ts+++ b/packages/math/src/polygon.ts@@ -87,12 +87,15 @@ export function polygonIsClosed<Point extends LocalPoint | GlobalPoint>(* The signed area of a polygon via the shoelace formula. Positive when the* vertices wind counter-clockwise in a y-down coordinate system.*- * The polygon may be given open or closed; a closing vertex is ignored.+ * The polygon may be given open or closed; a closing vertex*/export function polygonSignedArea<Point extends LocalPoint | GlobalPoint>(polygon: readonly Point[],+ tolerance: number = PRECISION,): number {- const pts = polygonIsClosed(polygon) ? polygon.slice(0, -1) : polygon;+ const pts = polygonIsClosed(polygon, tolerance)+ ? polygon.slice(0, -1)+ : polygon;let sum = 0;for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {sum += pts[j][0] * pts[i][1] - pts[i][0] * pts[j][1];@@ -102,8 +105,9 @@ export function polygonSignedArea<Point extends LocalPoint | GlobalPoint>(export function polygonArea<Point extends LocalPoint | GlobalPoint>(polygon: readonly Point[],+ tolerance: number = PRECISION,): number {- return Math.abs(polygonSignedArea(polygon));+ return Math.abs(polygonSignedArea(polygon, tolerance));}/**