@fulate/core 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { clamp, cloneDeep, has, isEqual, isFunction, isNull, isNumber, isObjectLike, isString, isUndefined, last } from "lodash-es";
2
- import { Bound, Intersection, clipPolygonToRect, createCanvasGradient, createPointView, formatPremultipliedColor, isGradient, isIdentityMatrix, makeBoundingBoxFromRects, parsePremultipliedColor, qrDecompose, rectEdgePosition, transformPoint } from "@fulate/share";
2
+ import { Bound, Intersection, Matrix2D, clipPolygonToRect, createCanvasGradient, createPointView, formatPremultipliedColor, isGradient, makeBoundingBoxFromRects, parsePremultipliedColor, qrDecompose, rectEdgePosition, transformPoint } from "@fulate/share";
3
3
  import RBush from "rbush";
4
4
  import { Easing, Group, Tween } from "@tweenjs/tween.js";
5
5
  //#region packages/core/src/event.ts
@@ -524,6 +524,134 @@ var TransformProperties = class extends NodeProperties {
524
524
  }
525
525
  };
526
526
  //#endregion
527
+ //#region packages/core/src/mutation/structure-change.ts
528
+ var NO_STRUCTURE_BATCH = {
529
+ changes: [],
530
+ placementNodes: /* @__PURE__ */ new Set()
531
+ };
532
+ /** 标出一组互不相同数值中的一个最长递增子序列。 */
533
+ function markLongestIncreasingSubsequence(values) {
534
+ const tails = [];
535
+ const previous = new Int32Array(values.length);
536
+ for (let index = 0; index < values.length; index++) {
537
+ const value = values[index];
538
+ let low = 0;
539
+ let high = tails.length;
540
+ while (low < high) {
541
+ const middle = low + high >> 1;
542
+ if (values[tails[middle]] < value) low = middle + 1;
543
+ else high = middle;
544
+ }
545
+ previous[index] = low > 0 ? tails[low - 1] : -1;
546
+ tails[low] = index;
547
+ }
548
+ const kept = new Uint8Array(values.length);
549
+ for (let index = tails.length > 0 ? tails[tails.length - 1] : -1; index >= 0; index = previous[index]) kept[index] = 1;
550
+ return kept;
551
+ }
552
+ /** @internal 计算同一 owner 两份 children 的最小 placement 差异。 */
553
+ function diffChildren(before, after) {
554
+ const shared = Math.min(before.length, after.length);
555
+ let start = 0;
556
+ while (start < shared && before[start] === after[start]) start++;
557
+ let beforeEnd = before.length;
558
+ let end = after.length;
559
+ while (beforeEnd > start && end > start && before[beforeEnd - 1] === after[end - 1]) {
560
+ beforeEnd--;
561
+ end--;
562
+ }
563
+ const beforeIndices = /* @__PURE__ */ new Map();
564
+ for (let index = start; index < beforeEnd; index++) beforeIndices.set(before[index], index);
565
+ const changes = [];
566
+ const retainedAfter = [];
567
+ const retainedBefore = [];
568
+ for (let index = start; index < end; index++) {
569
+ const node = after[index];
570
+ const beforeIndex = beforeIndices.get(node);
571
+ if (beforeIndex === void 0) {
572
+ changes.push({
573
+ node,
574
+ beforeIndex: -1,
575
+ afterIndex: index
576
+ });
577
+ continue;
578
+ }
579
+ beforeIndices.delete(node);
580
+ retainedAfter.push(index);
581
+ retainedBefore.push(beforeIndex);
582
+ }
583
+ const kept = markLongestIncreasingSubsequence(retainedBefore);
584
+ for (let index = 0; index < retainedAfter.length; index++) {
585
+ if (kept[index]) continue;
586
+ changes.push({
587
+ node: after[retainedAfter[index]],
588
+ beforeIndex: retainedBefore[index],
589
+ afterIndex: retainedAfter[index]
590
+ });
591
+ }
592
+ for (const [node, beforeIndex] of beforeIndices) changes.push({
593
+ node,
594
+ beforeIndex,
595
+ afterIndex: -1
596
+ });
597
+ return {
598
+ start,
599
+ end,
600
+ changes
601
+ };
602
+ }
603
+ /** @internal 按 parent 对象身份合并,并只保留最终非空变化。 */
604
+ function prepareStructureBatch(effects) {
605
+ if (effects.length === 0) return NO_STRUCTURE_BATCH;
606
+ const finalChildren = /* @__PURE__ */ new Map();
607
+ for (const effect of effects) finalChildren.set(effect.owner, effect.children);
608
+ const changes = [];
609
+ const placementNodes = /* @__PURE__ */ new Set();
610
+ for (const [owner, children] of finalChildren) {
611
+ const before = owner.children;
612
+ const diff = diffChildren(before, children);
613
+ if (diff.changes.length === 0) continue;
614
+ const changed = [];
615
+ for (const { node, beforeIndex, afterIndex } of diff.changes) {
616
+ changed.push(node);
617
+ if (beforeIndex < 0 || afterIndex < 0) placementNodes.add(node);
618
+ }
619
+ changes.push({
620
+ owner,
621
+ children,
622
+ before,
623
+ start: diff.start,
624
+ end: diff.end,
625
+ changed
626
+ });
627
+ }
628
+ if (changes.length === 0) return NO_STRUCTURE_BATCH;
629
+ return {
630
+ changes,
631
+ placementNodes
632
+ };
633
+ }
634
+ /** @internal 直接安装 affected raw links。 */
635
+ function installStructureLinks(batch) {
636
+ for (const node of batch.placementNodes) node.detachBatchParent();
637
+ for (const { owner, children, start, end } of batch.changes) owner.installBatchChildren(children, start, end);
638
+ }
639
+ /**
640
+ * @internal 所有 fields/raw links 安装及 History 记录后,自上而下同步每个 placement 节点;
641
+ * parent 先完成自身迁移,同批进入它的 children 再按 parent 的最终 context 同步。
642
+ */
643
+ function syncStructureLifecycles(nodes) {
644
+ if (nodes.size === 0) return;
645
+ const depths = /* @__PURE__ */ new Map();
646
+ for (const node of nodes) {
647
+ let depth = 0;
648
+ for (let parent = node.parent; parent; parent = parent.parent) depth++;
649
+ depths.set(node, depth);
650
+ }
651
+ const ordered = [...nodes].sort((left, right) => depths.get(left) - depths.get(right));
652
+ for (const node of ordered) node.syncPlacementLifecycle();
653
+ }
654
+ //#endregion
527
655
  //#region packages/core/src/node/node.ts
528
656
  var nodeKeyPrefix = Date.now().toString(36);
529
657
  var nodeKeySequence = 0;
@@ -536,6 +664,63 @@ function setProvidesParent(node, parentProvides) {
536
664
  if (Object.getPrototypeOf(node.provides) !== parentProvides) Object.setPrototypeOf(node.provides, parentProvides);
537
665
  }
538
666
  var NO_LIFECYCLE_ERROR = Symbol("no lifecycle error");
667
+ /** 中间插入把相邻标签间隔压到该值以下时,重排所在 owner 的全部 children 标签。 */
668
+ var MIN_SIBLING_ORDER_GAP = 1e-6;
669
+ /**
670
+ * 为 `children[start, end)` 分配递增的 sibling 标签。窗口两侧是未变化的邻居,标签落在它们之间;
671
+ * 首尾插入向外延伸,间隔耗尽时只重排这一个 owner。
672
+ */
673
+ function assignSiblingOrders(children, start, end) {
674
+ const count = end - start;
675
+ if (count === 0) return;
676
+ const lower = start > 0 ? children[start - 1].siblingOrder : void 0;
677
+ const upper = end < children.length ? children[end].siblingOrder : void 0;
678
+ let first;
679
+ let step = 1;
680
+ if (lower === void 0) first = upper === void 0 ? 0 : upper - count;
681
+ else if (upper === void 0) first = lower + 1;
682
+ else {
683
+ step = (upper - lower) / (count + 1);
684
+ if (step < MIN_SIBLING_ORDER_GAP) {
685
+ for (let index = 0; index < children.length; index++) children[index].siblingOrder = index;
686
+ return;
687
+ }
688
+ first = lower + step;
689
+ }
690
+ for (let index = 0; index < count; index++) children[start + index].siblingOrder = first + index * step;
691
+ }
692
+ /** 返回节点到所在树根的 parent 跳数。 */
693
+ function treeDepth(node) {
694
+ let depth = 0;
695
+ for (let parent = node.parent; parent; parent = parent.parent) depth++;
696
+ return depth;
697
+ }
698
+ /**
699
+ * @internal 按同一棵树的 preorder 比较两个节点;祖先排在后代之前。只沿两条 parent 链走到
700
+ * 最近公共祖先,比较其下两个 child 的 sibling 标签。
701
+ */
702
+ function compareTreeOrder(left, right) {
703
+ if (left === right) return 0;
704
+ let leftDepth = treeDepth(left);
705
+ let rightDepth = treeDepth(right);
706
+ let leftBranch = left;
707
+ let rightBranch = right;
708
+ while (leftDepth > rightDepth) {
709
+ leftBranch = leftBranch.parent;
710
+ leftDepth--;
711
+ }
712
+ if (leftBranch === right) return 1;
713
+ while (rightDepth > leftDepth) {
714
+ rightBranch = rightBranch.parent;
715
+ rightDepth--;
716
+ }
717
+ if (rightBranch === left) return -1;
718
+ while (leftBranch.parent !== rightBranch.parent) {
719
+ leftBranch = leftBranch.parent;
720
+ rightBranch = rightBranch.parent;
721
+ }
722
+ return leftBranch.siblingOrder - rightBranch.siblingOrder;
723
+ }
539
724
  var LifecycleState = /* @__PURE__ */ function(LifecycleState) {
540
725
  LifecycleState["New"] = "new";
541
726
  LifecycleState["Inactive"] = "inactive";
@@ -592,6 +777,8 @@ var Node = class extends EventEmitter {
592
777
  nextSibling = null;
593
778
  /** 上一个 sibling;只读使用,通过树操作维护。 */
594
779
  previousSibling = null;
780
+ /** @internal 在当前 parent children 中递增的顺序标签;只在同一 parent 的 children 间可比较。 */
781
+ siblingOrder = 0;
595
782
  /** 是否已完成首次 mount 且尚未卸载。 */
596
783
  get isMounted() {
597
784
  return this.lifecycleState === LifecycleState.Inactive || this.lifecycleState === LifecycleState.Active;
@@ -637,15 +824,20 @@ var Node = class extends EventEmitter {
637
824
  this.propertyState = properties;
638
825
  if (children) this.installChildren(this.adoptIncoming(children), false);
639
826
  }
640
- /** 安装最终 children 引用,并在一次循环内更新全部 raw links。 */
641
- installChildren(children, notifyParentChanges = true) {
827
+ /**
828
+ * 安装最终 children 引用,只更新 `[start, end)` 窗口及其两侧邻居的 raw links;
829
+ * 窗口外的公共前后缀与旧 children 相同。
830
+ */
831
+ installChildren(children, notifyParentChanges = true, start = 0, end = children.length) {
642
832
  this.childNodes = children;
643
- for (let index = 0; index < children.length; index++) {
833
+ assignSiblingOrders(children, start, end);
834
+ const last = Math.min(end, children.length - 1);
835
+ for (let index = Math.max(0, start - 1); index <= last; index++) {
644
836
  const child = children[index];
645
837
  child.previousSibling = children[index - 1] ?? null;
646
838
  child.nextSibling = children[index + 1] ?? null;
647
- this.linkChild(child, notifyParentChanges);
648
839
  }
840
+ for (let index = start; index < end; index++) this.linkChild(children[index], notifyParentChanges);
649
841
  }
650
842
  /** 建立结构所有权、上下文原型链和事件冒泡 parent。 */
651
843
  linkChild(child, notifyParentChange) {
@@ -675,48 +867,56 @@ var Node = class extends EventEmitter {
675
867
  markStructureDirty(changed) {
676
868
  const expected = this.childNodes;
677
869
  this.onChildrenChanged();
678
- if (this.childNodes !== expected) return;
679
- this.onStructureDirty();
680
- if (this.childNodes !== expected) return;
870
+ if (this.childNodes === expected) this.onStructureDirty();
871
+ this.publishStructureChange(changed);
872
+ }
873
+ /**
874
+ * 向 Root 发布已安装的 placement 变化。hook 重入提交更新 children 后,外层提交仍发布
875
+ * 自己已安装的变化;Root 按每个节点当前的 parent 与 lifecycle 过滤。
876
+ */
877
+ publishStructureChange(changed) {
681
878
  if (this.isActive) this.activeRoot?.commitStructureChange(this, changed);
682
879
  }
683
880
  /** 安装一次最终 children,并在当前提交仍有效时发布结构变化。 */
684
- commitChildren(next, entered = [], left = [], deactivateLeft = false, changed = [...entered, ...left]) {
881
+ commitChildren(next, entered = [], left = [], deactivateLeft = false) {
685
882
  const previous = this.childNodes;
686
- if (previous.length === next.length && previous.every((child, index) => child === next[index])) return false;
883
+ const diff = diffChildren(previous, next);
884
+ if (diff.changes.length === 0) return false;
687
885
  for (const child of left) {
688
886
  child.unlinkFromParent();
689
887
  if (this.childNodes !== previous) return true;
690
888
  }
691
- this.installChildren(next);
692
- if (deactivateLeft) for (const child of left) {
693
- if (!child.parent) child.transitionLifecycle(LifecycleState.Inactive);
694
- if (this.childNodes !== next) return true;
889
+ this.installChildren(next, true, diff.start, diff.end);
890
+ this.syncCommittedLifecycles(entered, left, deactivateLeft);
891
+ const changed = diff.changes.map(({ node }) => node);
892
+ if (this.childNodes === next) this.markStructureDirty(changed);
893
+ else this.publishStructureChange(changed);
894
+ return true;
895
+ }
896
+ /**
897
+ * 同步本次进入与离开节点的 lifecycle。lifecycle 回调可以同步重入修改结构,因此每个节点都按
898
+ * 自己与当前 owner 的实时 parent 和 lifecycle 判断,不因 children 被新提交替换而遗漏其余节点。
899
+ */
900
+ syncCommittedLifecycles(entered, left, deactivateLeft) {
901
+ if (deactivateLeft) {
902
+ for (const child of left) if (!child.parent) child.transitionLifecycle(LifecycleState.Inactive);
695
903
  }
696
- if (this.isActive) for (const child of entered) {
697
- if (this.childNodes !== next) return true;
904
+ for (const child of entered) {
698
905
  if (child.parent !== this) continue;
699
- const inheritedLayer = child.inject("layer") ?? null;
700
- if (child.isActive && child.activeLayer !== inheritedLayer) child.transitionLifecycle(LifecycleState.Inactive);
701
- child.transitionLifecycle(LifecycleState.Active);
702
- if (this.childNodes !== next) return true;
703
- }
704
- else for (const child of entered) {
705
- if (this.childNodes !== next) return true;
706
- if (child.parent !== this || !child.isActive) continue;
707
- child.transitionLifecycle(LifecycleState.Inactive);
708
- if (this.childNodes !== next) return true;
709
- }
710
- this.markStructureDirty(changed);
711
- return true;
906
+ if (this.isActive) {
907
+ const inheritedLayer = child.inject("layer") ?? null;
908
+ if (child.isActive && child.activeLayer !== inheritedLayer) child.transitionLifecycle(LifecycleState.Inactive);
909
+ child.transitionLifecycle(LifecycleState.Active);
910
+ } else if (child.isActive) child.transitionLifecycle(LifecycleState.Inactive);
911
+ }
712
912
  }
713
913
  /** @internal trusted batch 解除真实变化节点的旧 placement。 */
714
914
  detachBatchParent() {
715
915
  this.unlinkFromParent();
716
916
  }
717
- /** @internal 接收 trusted batch 转移所有权的最终 children 快照。 */
718
- installBatchChildren(children) {
719
- this.installChildren(children);
917
+ /** @internal 接收 trusted batch 转移所有权的最终 children 与其变化窗口。 */
918
+ installBatchChildren(children, start, end) {
919
+ this.installChildren(children, true, start, end);
720
920
  }
721
921
  /** @internal 按当前 parent 同步最终 lifecycle context。 */
722
922
  syncPlacementLifecycle() {
@@ -775,12 +975,19 @@ var Node = class extends EventEmitter {
775
975
  if (nodes.length === 0) return this;
776
976
  const adopted = this.adoptIncoming(nodes);
777
977
  if (adopted.length === 0) return this;
778
- const moving = new Set(adopted);
779
- const next = [...this.childNodes].filter((child) => !moving.has(child));
978
+ let next;
979
+ if (adopted.length === 1) {
980
+ next = this.childNodes.slice();
981
+ const current = next.indexOf(adopted[0]);
982
+ if (current !== -1) next.splice(current, 1);
983
+ } else {
984
+ const moving = new Set(adopted);
985
+ next = this.childNodes.filter((child) => !moving.has(child));
986
+ }
780
987
  const index = clamp(getIndex(next), 0, next.length);
781
988
  next.splice(index, 0, ...adopted);
782
989
  const entered = adopted.filter((child) => child.parent !== this);
783
- this.commitChildren(next, entered, [], false, adopted);
990
+ this.commitChildren(next, entered);
784
991
  return this;
785
992
  }
786
993
  /** 将节点移动或追加到 children 尾部。 */
@@ -812,14 +1019,12 @@ var Node = class extends EventEmitter {
812
1019
  }
813
1020
  /** 原子替换完整 children 序列。 */
814
1021
  replaceChildren(...children) {
815
- const current = this.childNodes;
816
- if (current.length === children.length && current.every((child, index) => child === children[index])) return this;
817
- const previous = [...current];
1022
+ const previous = this.childNodes;
818
1023
  const committed = this.adoptIncoming(children);
819
1024
  const committedSet = new Set(committed);
820
1025
  const left = previous.filter((child) => !committedSet.has(child));
821
1026
  const entered = committed.filter((child) => child.parent !== this);
822
- this.commitChildren(committed, entered, left, true, [...committed, ...left]);
1027
+ this.commitChildren(committed, entered, left, true);
823
1028
  return this;
824
1029
  }
825
1030
  /** 将节点移动到当前节点之前。 */
@@ -1786,6 +1991,10 @@ function createAuthoredLineSubpath(points, closed) {
1786
1991
  function geometrySnapshotHasGeometry(snapshot) {
1787
1992
  return snapshot instanceof RectangleGeometrySnapshot || genericSnapshotHasGeometry(snapshot);
1788
1993
  }
1994
+ /** @internal 普通矩形 canonical snapshot 返回其矩形;其他几何返回 `null`,不强制惰性 subpaths。 */
1995
+ function geometrySnapshotRectangle(snapshot) {
1996
+ return snapshot instanceof RectangleGeometrySnapshot ? snapshot.layoutReferenceBounds : null;
1997
+ }
1789
1998
  /** 创建尚未建立内部 index 的唯一 canonical snapshot query。 */
1790
1999
  function createGeometryQuery(snapshot) {
1791
2000
  return snapshot instanceof RectangleGeometrySnapshot ? new RectangleSnapshotGeometryQuery(snapshot) : new SnapshotGeometryQuery(snapshot);
@@ -1825,7 +2034,7 @@ function matrixChanged(matrix, previousA, previousB, previousC, previousD, previ
1825
2034
  var VISUAL_GEOMETRY_IMPACT$1 = ChangeImpact.LocalGeometry | ChangeImpact.WorldTransform | ChangeImpact.VisualBounds;
1826
2035
  var GEOMETRY_CACHE_IMPACT = ChangeImpact.LocalGeometry | ChangeImpact.WorldTransform | ChangeImpact.VisualBounds | ChangeImpact.HitBounds;
1827
2036
  var CHILD_LAYOUT_IMPACT = ChangeImpact.LocalGeometry | ChangeImpact.WorldTransform;
1828
- var IDENTITY_ELEMENT_TRANSFORM = new DOMMatrix();
2037
+ var IDENTITY_ELEMENT_TRANSFORM = new Matrix2D();
1829
2038
  /**
1830
2039
  * 一个 Element 唯一的变换、几何、damage 与子树派生状态 owner。
1831
2040
  *
@@ -1851,7 +2060,7 @@ var ElementTransform = class {
1851
2060
  /** 自身 reference 或 child world space 是否要求 descendants 重算布局。 */
1852
2061
  childLayoutDirty = false;
1853
2062
  /** 当前最后一次提交的 own world matrix。 */
1854
- worldMatrix = new DOMMatrix();
2063
+ worldMatrix = new Matrix2D();
1855
2064
  /** worldMatrix 的惰性逆矩阵。 */
1856
2065
  inverseWorldMatrix;
1857
2066
  /** 提供给 children 的 world 坐标空间逆矩阵。 */
@@ -1896,6 +2105,7 @@ var ElementTransform = class {
1896
2105
  }
1897
2106
  /** raw parent link 改变后只标记本地 world commit;publication 在结构阶段统一执行。 @internal */
1898
2107
  markParentChanged() {
2108
+ if ((!this.needsCommit || this.hitOnlyInvalidation) && this.element.isActive) this.captureCurrentVisualBounds();
1899
2109
  this.needsCommit = true;
1900
2110
  this.hitOnlyInvalidation = false;
1901
2111
  this.childLayoutDirty = true;
@@ -2115,7 +2325,7 @@ var ElementTransform = class {
2115
2325
  const offsetX = bounds ? bounds.left + (resolveOrigin(element.originX) + .5) * bounds.width : 0;
2116
2326
  const offsetY = bounds ? bounds.top + (resolveOrigin(element.originY) + .5) * bounds.height : 0;
2117
2327
  matrix.translateSelf(offsetX, offsetY);
2118
- if (hasAngle) matrix.rotateSelf(0, 0, element.angle);
2328
+ if (hasAngle) matrix.rotateSelf(element.angle);
2119
2329
  if (hasSkew) {
2120
2330
  if (element.skewX) matrix.skewXSelf(element.skewX);
2121
2331
  if (element.skewY) matrix.skewYSelf(element.skewY);
@@ -2134,18 +2344,16 @@ var ElementTransform = class {
2134
2344
  const previousF = this.worldMatrix.f;
2135
2345
  const authored = this.buildWorldMatrix();
2136
2346
  if (authored) {
2137
- this.worldMatrix = DOMMatrix.fromMatrix(authored);
2347
+ this.worldMatrix = Matrix2D.from(authored);
2138
2348
  return this.finishWorldMatrixCommit(previousA, previousB, previousC, previousD, previousE, previousF);
2139
2349
  }
2140
- let matrix = this.worldMatrix;
2141
- if (!matrix.is2D) matrix = this.worldMatrix = new DOMMatrix();
2142
2350
  const parent = this.element.parent;
2143
- this.writeScalarMatrix(matrix, parent?.transform?.getChildWorldMatrixView());
2351
+ this.writeScalarMatrix(this.worldMatrix, parent?.transform?.getChildWorldMatrixView());
2144
2352
  return this.finishWorldMatrixCommit(previousA, previousB, previousC, previousD, previousE, previousF);
2145
2353
  }
2146
2354
  /** 返回已提交的 world 矩阵副本,不包含 Viewport 和 DPR。 */
2147
2355
  getWorldMatrix() {
2148
- return DOMMatrix.fromMatrix(this.worldMatrix);
2356
+ return Matrix2D.from(this.worldMatrix);
2149
2357
  }
2150
2358
  /** 借用已提交矩阵;调用方不得修改或保留。 @internal */
2151
2359
  getWorldMatrixView() {
@@ -2160,7 +2368,7 @@ var ElementTransform = class {
2160
2368
  this.inverseChildWorldMatrix = inverse;
2161
2369
  return inverse;
2162
2370
  }
2163
- return this.inverseChildWorldMatrix = DOMMatrix.fromMatrix(childWorldMatrix).inverse();
2371
+ return this.inverseChildWorldMatrix = childWorldMatrix.inverse();
2164
2372
  }
2165
2373
  /** 返回已解析尺寸中心对应的 world 坐标。 */
2166
2374
  getWorldCenter() {
@@ -2461,7 +2669,7 @@ var ElementTransform = class {
2461
2669
  collectContentBoundsInReference(parentMatrix, referenceWorldInverse) {
2462
2670
  if (!this.element.visible || !this.contributesToAncestorContentBounds()) return null;
2463
2671
  const independentWorldMatrix = this.buildWorldMatrix();
2464
- const matrix = independentWorldMatrix ? referenceWorldInverse.multiply(independentWorldMatrix) : this.writeScalarMatrix(new DOMMatrix(), parentMatrix);
2672
+ const matrix = independentWorldMatrix ? referenceWorldInverse.multiply(independentWorldMatrix) : this.writeScalarMatrix(new Matrix2D(), parentMatrix);
2465
2673
  const ownBounds = this.hasGeometry() ? this.toBounds(matrix, this.getOwnContentBoundsView()) : null;
2466
2674
  let childParentMatrix = matrix;
2467
2675
  const childWorldMatrix = this.getChildWorldMatrixView();
@@ -2592,8 +2800,7 @@ var ElementTransform = class {
2592
2800
  hasInView() {
2593
2801
  const element = this.element;
2594
2802
  if (!element.visible || !element.isActive) return false;
2595
- const viewport = element.root.viewport;
2596
- const { left: viewLeft, top: viewTop, width: viewWidth, height: viewHeight } = viewport.getWorldRectView?.() ?? viewport.getWorldRect();
2803
+ const { left: viewLeft, top: viewTop, width: viewWidth, height: viewHeight } = element.root.viewport.getWorldRectView();
2597
2804
  const bounds = element.children.length === 0 ? this.hasGeometry() ? this.getWorldVisualBoundsView() : null : this.getRenderCoverageBoundsView();
2598
2805
  if (!bounds) return false;
2599
2806
  return bounds.left + bounds.width > viewLeft && bounds.left < viewLeft + viewWidth && bounds.top + bounds.height > viewTop && bounds.top < viewTop + viewHeight;
@@ -3068,8 +3275,6 @@ var Element = class Element extends Node {
3068
3275
  type = "element";
3069
3276
  /** 当前 Element 唯一的变换与几何运行时。 */
3070
3277
  transform;
3071
- /** @internal Layer 内用于绘制顺序命中的已提交树序号。 */
3072
- committedPaintOrder = -1;
3073
3278
  /** hover 时使用的 CSS cursor。 */
3074
3279
  get cursor() {
3075
3280
  return this.propertyState.cursor;
@@ -3421,15 +3626,18 @@ var Element = class Element extends Node {
3421
3626
  for (let i = 1; i < coords.length; i++) ctx.lineTo(coords[i].x, coords[i].y);
3422
3627
  ctx.closePath();
3423
3628
  ctx.clip();
3424
- ctx.beginPath();
3425
- ctx.moveTo(coords[0].x, coords[0].y);
3426
- for (let i = 1; i < coords.length; i++) ctx.lineTo(coords[i].x, coords[i].y);
3427
- ctx.closePath();
3428
3629
  ctx.strokeStyle = this.activeRoot?.skin.selection ?? SKIN_DEFAULTS.selection;
3429
3630
  ctx.lineWidth = 2 / scale;
3430
3631
  ctx.stroke();
3431
3632
  ctx.restore();
3432
3633
  }
3634
+ /**
3635
+ * @internal 把与 `paintHover()` 等价的轮廓追加到当前 path,由调用方统一描边。
3636
+ * 返回 `false` 时调用方改用 `paintHover()` 独立绘制。
3637
+ */
3638
+ traceHoverOutline(_ctx, _scale) {
3639
+ return false;
3640
+ }
3433
3641
  /** 从当前 live owner 直接解析一次可连接 Ports。 */
3434
3642
  getConnectionPorts() {
3435
3643
  this.resolveCurrentConnectionPortProjection();
@@ -3696,7 +3904,8 @@ var Element = class Element extends Node {
3696
3904
  };
3697
3905
  //#endregion
3698
3906
  //#region packages/core/src/node/reference-transform.ts
3699
- var IDENTITY_REFERENCE_TRANSFORM = new DOMMatrix();
3907
+ var IDENTITY_REFERENCE_TRANSFORM = new Matrix2D();
3908
+ var SCALE_EPSILON = 1e-9;
3700
3909
  /**
3701
3910
  * 纯 world translation 且 parent 线性变换未改变时,只生成真实变化的 left/top。
3702
3911
  * 这条结果与通用矩阵分解等价,但不 materialize 未变化的 pose/size fields。
@@ -3715,6 +3924,15 @@ function resolveSparseReferenceTranslation(baseline, intent, targetParentWorldMa
3715
3924
  authoredLocalDelta: IDENTITY_REFERENCE_TRANSFORM
3716
3925
  };
3717
3926
  }
3927
+ /**
3928
+ * 目标轴向尺度相对 authored 尺度的比例。与 1 的相对差不超过 {@link SCALE_EPSILON} 时视为尺寸
3929
+ * 不变,移动、旋转和翻转等刚体变换因此精确保留 authored width/height。
3930
+ */
3931
+ function resolveAuthoredScale(target, authored) {
3932
+ if (authored === 0) return 1;
3933
+ const ratio = Math.abs(target / authored);
3934
+ return Math.abs(ratio - 1) <= SCALE_EPSILON ? 1 : ratio;
3935
+ }
3718
3936
  function sameMatrix(left, right) {
3719
3937
  return sameLinearMatrix(left, right) && left.e === right.e && left.f === right.f;
3720
3938
  }
@@ -3722,7 +3940,7 @@ function sameLinearMatrix(left, right) {
3722
3940
  return left.a === right.a && left.b === right.b && left.c === right.c && left.d === right.d;
3723
3941
  }
3724
3942
  function createFrameLinearMatrix(frame) {
3725
- return new DOMMatrix().rotate(0, 0, frame.angle).skewX(frame.skewX).skewY(frame.skewY).scale(frame.scaleX, frame.scaleY);
3943
+ return new Matrix2D().rotateSelf(frame.angle).skewXSelf(frame.skewX).skewYSelf(frame.skewY).scaleSelf(frame.scaleX, frame.scaleY);
3726
3944
  }
3727
3945
  function transformReferenceBounds(bounds, matrix) {
3728
3946
  const right = bounds.left + bounds.width;
@@ -3774,14 +3992,7 @@ function resolveBakedAuthoredGeometryTransform(baseline, target) {
3774
3992
  const determinant = frameLinear.a * frameLinear.d - frameLinear.b * frameLinear.c;
3775
3993
  if (!Number.isFinite(determinant) || determinant === 0) return null;
3776
3994
  const targetLocal = target.parentInverseMatrix.multiply(target.worldMatrix);
3777
- const targetLinear = new DOMMatrix([
3778
- targetLocal.a,
3779
- targetLocal.b,
3780
- targetLocal.c,
3781
- targetLocal.d,
3782
- 0,
3783
- 0
3784
- ]);
3995
+ const targetLinear = new Matrix2D(targetLocal.a, targetLocal.b, targetLocal.c, targetLocal.d, 0, 0);
3785
3996
  const authoredLocalDelta = frameLinear.inverse().multiply(targetLinear);
3786
3997
  const nextBounds = transformReferenceBounds(baseline.referenceBounds, authoredLocalDelta);
3787
3998
  const offsetX = nextBounds.left + (resolveOrigin(baseline.frame.originX) + .5) * nextBounds.width;
@@ -3805,7 +4016,7 @@ function resolveBakedAuthoredGeometryTransform(baseline, target) {
3805
4016
  * 新几何后把真实 bounds 交回这里,保持 frame world matrix 与目标一致。
3806
4017
  */
3807
4018
  function resolveAuthoredGeometryFramePatch(baseline, resolution, authoredBounds) {
3808
- if (isIdentityMatrix(resolution.authoredLocalDelta)) return resolution.framePatch;
4019
+ if (resolution.authoredLocalDelta.isIdentity) return resolution.framePatch;
3809
4020
  const approximateBounds = transformReferenceBounds(baseline.referenceBounds, resolution.authoredLocalDelta);
3810
4021
  return {
3811
4022
  ...resolution.framePatch,
@@ -3845,7 +4056,7 @@ function resolveTargetParentWorldMatrix(baseline, intent) {
3845
4056
  function targetsFrozenReference(baseline, intent) {
3846
4057
  const delta = intent.worldDelta;
3847
4058
  const targetParentWorldMatrix = resolveTargetParentWorldMatrix(baseline, intent);
3848
- return isIdentityMatrix(delta) && sameMatrix(baseline.startParentWorldMatrix, targetParentWorldMatrix);
4059
+ return delta.isIdentity && sameMatrix(baseline.startParentWorldMatrix, targetParentWorldMatrix);
3849
4060
  }
3850
4061
  /** 从已持有的最终 world pose 纯计算 frame/authored delta。 */
3851
4062
  function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwnedGeometry, unwrappedRotationDelta, bakeGeometry = false) {
@@ -3855,8 +4066,8 @@ function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwned
3855
4066
  }
3856
4067
  const targetDecomposition = qrDecompose(target.parentInverseMatrix.multiply(target.worldMatrix));
3857
4068
  const targetAngle = unwrappedRotationDelta === void 0 ? targetDecomposition.angle : targetDecomposition.angle + 360 * Math.round((baseline.frame.angle + unwrappedRotationDelta - targetDecomposition.angle) / 360);
3858
- const authoredScaleX = preserveOwnedGeometry ? 1 : baseline.frame.scaleX === 0 ? 1 : Math.abs(targetDecomposition.scaleX / baseline.frame.scaleX);
3859
- const authoredScaleY = preserveOwnedGeometry ? 1 : baseline.frame.scaleY === 0 ? 1 : Math.abs(targetDecomposition.scaleY / baseline.frame.scaleY);
4069
+ const authoredScaleX = preserveOwnedGeometry ? 1 : resolveAuthoredScale(targetDecomposition.scaleX, baseline.frame.scaleX);
4070
+ const authoredScaleY = preserveOwnedGeometry ? 1 : resolveAuthoredScale(targetDecomposition.scaleY, baseline.frame.scaleY);
3860
4071
  const nextScaleX = preserveOwnedGeometry ? targetDecomposition.scaleX : baseline.frame.scaleX === 0 ? targetDecomposition.scaleX : Math.sign(targetDecomposition.scaleX) * Math.abs(baseline.frame.scaleX);
3861
4072
  const nextScaleY = preserveOwnedGeometry ? targetDecomposition.scaleY : baseline.frame.scaleY === 0 ? targetDecomposition.scaleY : Math.sign(targetDecomposition.scaleY) * Math.abs(baseline.frame.scaleY);
3862
4073
  const nextBoundsLeft = baseline.referenceBounds.left * authoredScaleX;
@@ -3868,7 +4079,7 @@ function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwned
3868
4079
  const offsetY = nextBoundsTop + (resolveOrigin(baseline.frame.originY) + .5) * nextBoundsHeight;
3869
4080
  const centerX = nextBoundsLeft + nextBoundsWidth / 2;
3870
4081
  const centerY = nextBoundsTop + nextBoundsHeight / 2;
3871
- const pose = new DOMMatrix().rotate(0, 0, targetAngle).skewX(targetDecomposition.skewX).scale(nextScaleX, nextScaleY);
4082
+ const pose = new Matrix2D().rotateSelf(targetAngle).skewXSelf(targetDecomposition.skewX).scaleSelf(nextScaleX, nextScaleY);
3872
4083
  const relativeCenterX = centerX - offsetX;
3873
4084
  const relativeCenterY = centerY - offsetY;
3874
4085
  const posedCenterX = offsetX + pose.a * relativeCenterX + pose.c * relativeCenterY;
@@ -3887,7 +4098,7 @@ function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwned
3887
4098
  height: baseline.frame.height * authoredScaleY
3888
4099
  } : {}
3889
4100
  },
3890
- authoredLocalDelta: baseline.writeMode === "authored-geometry" && !preserveOwnedGeometry ? new DOMMatrix().scale(authoredScaleX, authoredScaleY) : IDENTITY_REFERENCE_TRANSFORM
4101
+ authoredLocalDelta: baseline.writeMode === "authored-geometry" && !preserveOwnedGeometry ? new Matrix2D().scaleSelf(authoredScaleX, authoredScaleY) : IDENTITY_REFERENCE_TRANSFORM
3891
4102
  };
3892
4103
  }
3893
4104
  /**
@@ -4222,6 +4433,16 @@ var Shape = class extends Element {
4222
4433
  buildBorderPath(ctx) {
4223
4434
  this.buildPath(ctx);
4224
4435
  }
4436
+ /**
4437
+ * canonical geometry 是普通矩形时,向当前 path 追加向内偏移 `inset` 的等距矩形。
4438
+ * 直边内缩描边与轮廓裁剪逐像素一致;其他几何返回 `false`,由调用方使用轮廓裁剪。
4439
+ */
4440
+ traceInsetRectangle(ctx, inset) {
4441
+ const rectangle = geometrySnapshotRectangle(this.transform.getGeometrySnapshot());
4442
+ if (!rectangle || rectangle.width < inset * 2 || rectangle.height < inset * 2) return false;
4443
+ ctx.rect(rectangle.left + inset, rectangle.top + inset, rectangle.width - inset * 2, rectangle.height - inset * 2);
4444
+ return true;
4445
+ }
4225
4446
  /** 使用 Shape 的实际路径裁剪 children。 */
4226
4447
  applyChildClip(ctx) {
4227
4448
  this.buildPath(ctx);
@@ -4252,10 +4473,20 @@ var Shape = class extends Element {
4252
4473
  if (!borderColor || !this.borderWidth) return;
4253
4474
  if (isGradient(borderColor)) ctx.strokeStyle = createCanvasGradient(ctx, borderColor, this.width ?? 0, this.height ?? 0);
4254
4475
  else ctx.strokeStyle = borderColor;
4476
+ const inside = this.borderPosition === "inside";
4477
+ if (inside) {
4478
+ ctx.beginPath();
4479
+ if (this.traceInsetRectangle(ctx, this.borderWidth / 2)) {
4480
+ ctx.lineJoin = "miter";
4481
+ ctx.lineWidth = this.borderWidth;
4482
+ ctx.stroke();
4483
+ return;
4484
+ }
4485
+ }
4255
4486
  ctx.save();
4256
4487
  try {
4257
4488
  this.buildPath(ctx);
4258
- if (this.borderPosition === "inside") ctx.clip(this.fillRule);
4489
+ if (inside) ctx.clip(this.fillRule);
4259
4490
  else {
4260
4491
  const bounds = this.transform.getLayoutReferenceBoundsView();
4261
4492
  const outset = this.getBorderOutset();
@@ -4282,17 +4513,34 @@ var Shape = class extends Element {
4282
4513
  ctx.shadowOffsetX = 0;
4283
4514
  ctx.shadowOffsetY = 0;
4284
4515
  }
4516
+ /** 在轮廓内侧绘制 `1 / scale` 宽的 hover 轮廓。 */
4285
4517
  paintHover(ctx, scale) {
4286
4518
  ctx.save();
4287
4519
  this.applyPaintTransform(ctx);
4288
- this.buildPath(ctx);
4289
- ctx.clip(this.fillRule);
4290
- this.buildPath(ctx);
4291
4520
  ctx.strokeStyle = this.activeRoot?.skin.selection ?? SKIN_DEFAULTS.selection;
4292
- ctx.lineWidth = 2 / scale;
4521
+ ctx.beginPath();
4522
+ if (this.traceInsetRectangle(ctx, .5 / scale)) {
4523
+ ctx.lineJoin = "miter";
4524
+ ctx.lineWidth = 1 / scale;
4525
+ } else {
4526
+ this.buildPath(ctx);
4527
+ ctx.clip(this.fillRule);
4528
+ ctx.lineWidth = 2 / scale;
4529
+ }
4293
4530
  ctx.stroke();
4294
4531
  ctx.restore();
4295
4532
  }
4533
+ /**
4534
+ * @internal 普通矩形几何且 world 矩阵保持长度时,把与 `paintHover()` 相同的内侧轮廓追加到
4535
+ * 当前 path;调用方随后在 Viewport 变换下以 `1 / scale` 线宽统一描边。
4536
+ * 覆写 `paintHover()` 的子类同时覆写本方法,返回 `false` 或追加自身的等价轮廓。
4537
+ */
4538
+ traceHoverOutline(ctx, scale) {
4539
+ const { a, b, c, d } = this.transform.getWorldMatrixView();
4540
+ if (Math.abs(a * a + b * b - 1) > 1e-9 || Math.abs(c * c + d * d - 1) > 1e-9 || Math.abs(a * c + b * d) > 1e-9) return false;
4541
+ this.applyPaintTransform(ctx);
4542
+ return this.traceInsetRectangle(ctx, .5 / scale);
4543
+ }
4296
4544
  };
4297
4545
  //#endregion
4298
4546
  //#region packages/core/src/root/hit-test.ts
@@ -4396,7 +4644,7 @@ function* iteratePointElements(root, point, options = {}) {
4396
4644
  for (let index = root.layers.length - 1; index >= 0; index--) {
4397
4645
  const layer = root.layers[index];
4398
4646
  for (const element of layer.iterateCommittedElements(area)) {
4399
- if (!element.isActive || element.isUnmounted || element.activeRoot !== root || element.layer !== layer || root.getPaintOrder(element) === void 0) continue;
4647
+ if (!element.isActive || element.isUnmounted || element.activeRoot !== root || element.layer !== layer) continue;
4400
4648
  if (options.exclude?.has(element.key)) continue;
4401
4649
  if (scope && !isStrictDescendant(element, scope)) continue;
4402
4650
  if (!isPointerTargetWithinAncestorClips(root, element, point)) continue;
@@ -5323,7 +5571,7 @@ var RootFrameRuntime = class {
5323
5571
  /** 安装或移除 Root 生命周期内唯一的无调度 participant。 */
5324
5572
  setParticipant(participant) {
5325
5573
  this.participant = participant;
5326
- if (participant?.hasPendingWork() || participant?.hasPendingSpatialWork?.() || participant?.hasPendingOverlayWork?.() || participant?.hasPendingCompletionWork?.()) this.requestFrame();
5574
+ if (this.needsAnotherFrame()) this.requestFrame();
5327
5575
  }
5328
5576
  /** 判断 Layer 是否仍由当前活动 Root 拥有。 */
5329
5577
  ownsLayer(layer) {
@@ -5331,7 +5579,7 @@ var RootFrameRuntime = class {
5331
5579
  }
5332
5580
  /** 激活后为已存在的 animation、Layer 或 participant 工作请求帧。 */
5333
5581
  activate() {
5334
- if (hasRunningTweens(this.animationGroup) || this.pendingLayers.size > 0 || this.pendingLayouts.size > 0 || this.completionWork.size > 0 || this.participant?.hasPendingWork() || this.participant?.hasPendingSpatialWork?.() || this.participant?.hasPendingOverlayWork?.() || this.participant?.hasPendingCompletionWork?.()) this.requestFrame();
5582
+ if (this.needsAnotherFrame()) this.requestFrame();
5335
5583
  }
5336
5584
  /** Layer 离开 Root 时丢弃其尚未消费的帧登记。 */
5337
5585
  forgetLayer(layer) {
@@ -5435,7 +5683,7 @@ var RootFrameRuntime = class {
5435
5683
  return this.root.isActive && !this.root.isUnmounted && (this.pendingLayers.size > 0 || this.pendingLayouts.size > 0 || this.pendingTransformCompletions.size > 0 || this.completionWork.size > 0 || this.hoverRefreshPending || this.participant?.hasPendingWork() === true || this.participant?.hasPendingSpatialWork?.() === true || this.participant?.hasPendingOverlayWork?.() === true || this.participant?.hasPendingCompletionWork?.() === true);
5436
5684
  }
5437
5685
  needsAnotherFrame() {
5438
- return this.root.isActive && !this.root.isUnmounted && (this.pendingLayers.size > 0 || this.pendingLayouts.size > 0 || this.pendingTransformCompletions.size > 0 || this.completionWork.size > 0 || this.hoverRefreshPending || this.participant?.hasPendingWork() === true || this.participant?.hasPendingSpatialWork?.() === true || this.participant?.hasPendingOverlayWork?.() === true || this.participant?.hasPendingCompletionWork?.() === true || hasRunningTweens(this.animationGroup));
5686
+ return this.hasPendingSynchronousWork() || this.root.isActive && !this.root.isUnmounted && hasRunningTweens(this.animationGroup);
5439
5687
  }
5440
5688
  runFrame(time) {
5441
5689
  if (time !== void 0) this.animationGroup.update(time);
@@ -5704,98 +5952,6 @@ var SceneRegistry = class {
5704
5952
  }
5705
5953
  };
5706
5954
  //#endregion
5707
- //#region packages/core/src/mutation/structure-change.ts
5708
- var NO_STRUCTURE_CHANGES = [];
5709
- var NO_PLACEMENT_CHANGES = [];
5710
- var NO_PLACEMENT_NODES = /* @__PURE__ */ new Set();
5711
- var NO_LIFECYCLE_ROOTS = [];
5712
- var NO_STRUCTURE_BATCH = {
5713
- changes: NO_STRUCTURE_CHANGES,
5714
- placementNodes: NO_PLACEMENT_NODES
5715
- };
5716
- function sameChildren(left, right) {
5717
- return left.length === right.length && left.every((child, index) => child === right[index]);
5718
- }
5719
- /** @internal 按 parent 对象身份合并,并只保留最终非空变化。 */
5720
- function prepareStructureBatch(effects) {
5721
- if (effects.length === 0) return NO_STRUCTURE_BATCH;
5722
- const finalChildren = /* @__PURE__ */ new Map();
5723
- for (const effect of effects) finalChildren.set(effect.owner, effect.children);
5724
- const changes = [];
5725
- for (const [owner, children] of finalChildren) {
5726
- const before = owner.children;
5727
- if (sameChildren(before, children)) continue;
5728
- const beforeIndices = new Map(before.map((child, index) => [child, index]));
5729
- const afterIndices = new Map(children.map((child, index) => [child, index]));
5730
- const changed = /* @__PURE__ */ new Set();
5731
- for (const child of before) if (afterIndices.get(child) !== beforeIndices.get(child)) changed.add(child);
5732
- for (const child of children) if (beforeIndices.get(child) !== afterIndices.get(child)) changed.add(child);
5733
- changes.push({
5734
- owner,
5735
- children,
5736
- before,
5737
- changed: [...changed]
5738
- });
5739
- }
5740
- if (changes.length === 0) return NO_STRUCTURE_BATCH;
5741
- const finalParents = /* @__PURE__ */ new Map();
5742
- for (const { owner, children } of changes) for (const child of children) finalParents.set(child, owner);
5743
- const placementNodes = /* @__PURE__ */ new Set();
5744
- for (const { owner, before, children } of changes) {
5745
- for (const child of before) if (finalParents.get(child) !== owner) placementNodes.add(child);
5746
- for (const child of children) if (child.parent !== owner) placementNodes.add(child);
5747
- }
5748
- return {
5749
- changes,
5750
- placementNodes
5751
- };
5752
- }
5753
- /** @internal History-on 才把 affected-parent delta 收敛为实际 node placements。 */
5754
- function preparePlacementChanges(changes) {
5755
- if (changes.length === 0) return NO_PLACEMENT_CHANGES;
5756
- const before = /* @__PURE__ */ new Map();
5757
- const after = /* @__PURE__ */ new Map();
5758
- const candidates = /* @__PURE__ */ new Set();
5759
- for (const change of changes) {
5760
- change.before.forEach((node, index) => {
5761
- before.set(node, [change.owner, index]);
5762
- });
5763
- change.children.forEach((node, index) => {
5764
- after.set(node, [change.owner, index]);
5765
- });
5766
- change.changed.forEach((node) => candidates.add(node));
5767
- }
5768
- const placements = [];
5769
- for (const node of candidates) {
5770
- const beforePlacement = before.get(node);
5771
- const afterPlacement = after.get(node);
5772
- const beforeOwner = beforePlacement?.[0] ?? null;
5773
- const beforeIndex = beforePlacement?.[1] ?? -1;
5774
- const afterOwner = afterPlacement?.[0] ?? null;
5775
- const afterIndex = afterPlacement?.[1] ?? -1;
5776
- if (beforeOwner === afterOwner && beforeIndex === afterIndex) continue;
5777
- placements.push({
5778
- node,
5779
- beforeOwner,
5780
- beforeIndex
5781
- });
5782
- }
5783
- return placements;
5784
- }
5785
- /** @internal 直接安装 affected raw links,并返回需要同步 lifecycle 的局部 roots。 */
5786
- function installStructureLinks(batch) {
5787
- if (batch.changes.length === 0) return NO_LIFECYCLE_ROOTS;
5788
- for (const node of batch.placementNodes) node.detachBatchParent();
5789
- for (const { owner, children } of batch.changes) owner.installBatchChildren(children);
5790
- const lifecycleRoots = [];
5791
- for (const node of batch.placementNodes) if (!node.parent || !batch.placementNodes.has(node.parent)) lifecycleRoots.push(node);
5792
- return lifecycleRoots;
5793
- }
5794
- /** @internal 所有 fields/raw links 安装及 History 记录后同步局部 lifecycle。 */
5795
- function syncStructureLifecycles(nodes) {
5796
- for (const node of nodes) node.syncPlacementLifecycle();
5797
- }
5798
- //#endregion
5799
5955
  //#region packages/core/src/mutation/change-batch.ts
5800
5956
  /** @internal 合并 raw owner effects;单个 patch 直接借用,仅合并同 owner 字段时分配。 */
5801
5957
  function mergeOwnerPropertyChanges(ownerEffects) {
@@ -5840,17 +5996,16 @@ function applyChangeBatch(root, ownerEffects, structureEffects = [], history) {
5840
5996
  const structureBatch = prepareStructureBatch(structureEffects);
5841
5997
  const structure = structureBatch.changes;
5842
5998
  if (properties.length === 0 && structure.length === 0) return false;
5843
- const placements = history ? preparePlacementChanges(structure) : null;
5844
5999
  for (const { owner, commit } of properties) owner.installPropertyCommit(commit);
5845
- const lifecycleRoots = installStructureLinks(structureBatch);
6000
+ installStructureLinks(structureBatch);
5846
6001
  if (history) {
5847
6002
  for (const { owner, commit } of properties) for (const field of commit.update.fields) {
5848
6003
  if (!field.sourceChanged) continue;
5849
6004
  history.recordPropertyChange(owner, field.key, field.beforeSource);
5850
6005
  }
5851
- for (const placement of placements) history.recordPlacementChange(placement.node, placement.beforeOwner, placement.beforeIndex);
6006
+ for (const { owner, before } of structure) history.recordStructureChange(owner, before);
5852
6007
  }
5853
- syncStructureLifecycles(lifecycleRoots);
6008
+ syncStructureLifecycles(structureBatch.placementNodes);
5854
6009
  for (const { owner, commit } of properties) owner.syncPropertyCommitEvents(commit);
5855
6010
  for (const { owner, commit } of properties) owner.runPropertyCommitHook(commit);
5856
6011
  for (const { owner } of structure) owner.runBatchStructureHook();
@@ -6028,54 +6183,36 @@ var Root = class extends Node {
6028
6183
  }
6029
6184
  /** @internal 在 children 事务提交后刷新 Layer 顺序、布局、绘制和 hover。 */
6030
6185
  commitStructureChange(owner, changed) {
6031
- this.commitStructureChanges([{
6186
+ this.commitBatchStructureChanges([{
6032
6187
  owner,
6033
6188
  changed
6034
6189
  }]);
6035
6190
  if (this.sceneRegistry.hasSceneChangeObservers) this.sceneRegistry.notifySceneChange(void 0, [owner, ...changed]);
6036
6191
  }
6037
- /** @internal trusted batch 只消费受影响 owners/subgraph,并合并 Layer 工作。 */
6192
+ /**
6193
+ * @internal 只消费受影响 owners/subgraph,并合并 Layer 工作。离开的节点已在停用时
6194
+ * 登记旧区域;仍在 owner 下的进入或移动节点只重绘自身子树。绘制顺序由安装期的 sibling
6195
+ * 标签直接给出,不需要重排整层。
6196
+ */
6038
6197
  commitBatchStructureChanges(changes, layerOrderImpact = false) {
6039
- this.commitStructureChanges(changes, layerOrderImpact);
6040
- }
6041
- commitStructureChanges(changes, layerOrderImpact = false) {
6042
- const affectedLayers = /* @__PURE__ */ new Set();
6043
- const visited = /* @__PURE__ */ new Set();
6044
6198
  let layerOrderChanged = layerOrderImpact;
6045
- const collect = (node) => {
6046
- if (visited.has(node)) return;
6047
- visited.add(node);
6048
- if (node.isLayerNode()) layerOrderChanged = true;
6049
- const layer = node.isActive ? node.layer : null;
6050
- if (layer && this.ownsLayer(layer) && (!node.isLayerNode() || node.parent === this)) affectedLayers.add(layer);
6051
- };
6052
- for (const { owner, changed } of changes) {
6053
- if (owner instanceof Element && owner.isActive) {
6054
- const layer = owner.layer;
6055
- if (this.ownsLayer(layer)) affectedLayers.add(layer);
6199
+ for (const { owner, changed } of changes) for (const node of changed) {
6200
+ if (node.isLayerNode()) {
6201
+ layerOrderChanged = true;
6202
+ continue;
6056
6203
  }
6057
- for (const node of changed) collect(node);
6204
+ if (!(node instanceof Element) || node.parent !== owner || !node.isActive || !this.ownsLayer(node.layer)) continue;
6205
+ if (node.transform.needsCommit) node.layer.invalidateLayout(node);
6206
+ else node.layer.invalidatePaint(node);
6058
6207
  }
6059
- for (const layer of affectedLayers) {
6060
- layer.commitStructureOrder();
6061
- layer.invalidateAll();
6062
- }
6063
- for (const { owner, changed } of changes) for (const node of changed) if (node instanceof Element && node.parent === owner && node.isActive && node.transform.needsCommit) node.layer.invalidateLayout(node);
6064
6208
  if (layerOrderChanged) this.sortLayers();
6065
6209
  this.scheduleHoverRefresh();
6066
6210
  }
6067
- /** @internal 返回结构提交后记录的 Layer 内 paint preorder。 */
6068
- getPaintOrder(element) {
6069
- return element.committedPaintOrder < 0 ? void 0 : element.committedPaintOrder;
6070
- }
6071
- /** @internal 返回跨 Layer 可直接比较的 committed paint key。 */
6072
- getPaintOrderKey(element) {
6073
- const layer = this.registeredLayers.indexOf(element.layer);
6074
- const order = this.getPaintOrder(element);
6075
- return layer < 0 || order === void 0 ? void 0 : {
6076
- layer,
6077
- element: order
6078
- };
6211
+ /**
6212
+ * @internal 按跨 Layer 的已提交绘制顺序比较两个活动元素;小于 0 表示 `left` 先绘制(在下方)。
6213
+ */
6214
+ comparePaintOrder(left, right) {
6215
+ return this.registeredLayers.indexOf(left.layer) - this.registeredLayers.indexOf(right.layer) || compareTreeOrder(left, right);
6079
6216
  }
6080
6217
  /** @internal Layer zIndex 变化后重排 Canvas 并刷新 hover。 */
6081
6218
  commitLayerOrderChange() {
@@ -6413,6 +6550,8 @@ var Layer = class Layer extends Element {
6413
6550
  static FULL_REPAINT_RATIO = .5;
6414
6551
  /** 候选命中达到空间项此比例时直接完整重绘。 */
6415
6552
  static CANDIDATE_FULL_REPAINT_RATIO = .9;
6553
+ /** 完整重绘的 viewport 候选达到空间项此比例时改为逐 child 判断可见性。 */
6554
+ static VIEWPORT_CANDIDATE_RATIO = .15;
6416
6555
  /** 空间项变更超过现有项此比例时重建整个 RBush。 */
6417
6556
  static RBUSH_REBUILD_RATIO = .3;
6418
6557
  /** 将零散 damage 合并为有限数量矩形的网格。 */
@@ -6444,7 +6583,6 @@ var Layer = class Layer extends Element {
6444
6583
  root.container.appendChild(this.canvasEl);
6445
6584
  if (this.debugSurface) root.container.appendChild(this.debugSurface.canvas);
6446
6585
  root.registerLayer(this);
6447
- this.commitStructureOrder();
6448
6586
  this.pendingWork.dirtyNodes.add(this);
6449
6587
  this.invalidateAll();
6450
6588
  }
@@ -6566,7 +6704,7 @@ var Layer = class Layer extends Element {
6566
6704
  queryCommittedElements(area, order = "paint") {
6567
6705
  const elements = this.searchCommittedElements(area);
6568
6706
  if (order === "none") return elements;
6569
- return elements.sort((a, b) => (this.root.getPaintOrder(b) ?? -1) - (this.root.getPaintOrder(a) ?? -1));
6707
+ return elements.sort((a, b) => compareTreeOrder(b, a));
6570
6708
  }
6571
6709
  /** @internal Copy the last visual bounds committed to this Layer index. */
6572
6710
  getCommittedVisualBounds(node) {
@@ -6582,7 +6720,7 @@ var Layer = class Layer extends Element {
6582
6720
  */
6583
6721
  *iterateCommittedElements(area) {
6584
6722
  const items = this.searchCommittedItems(area);
6585
- items.sort((a, b) => (this.root.getPaintOrder(b.element) ?? -1) - (this.root.getPaintOrder(a.element) ?? -1));
6723
+ items.sort((a, b) => compareTreeOrder(b.element, a.element));
6586
6724
  for (const item of items) yield item.element;
6587
6725
  }
6588
6726
  /** 直接查询 RBush 中与 world AABB 相交的已提交元素。 */
@@ -6727,10 +6865,13 @@ var Layer = class Layer extends Element {
6727
6865
  for (const child of node.children) stack.push(child);
6728
6866
  }
6729
6867
  }
6730
- /** 清空并重新绘制整个 Layer Canvas。 */
6868
+ /**
6869
+ * 清空并重新绘制整个 Layer Canvas。dirty-rect Layer 的元素只绘制在 visual bounds 内,
6870
+ * 因此直接用 viewport 的 RBush 候选组织绘制树;候选密度达到阈值时逐 child 判断可见性。
6871
+ */
6731
6872
  fullRepaint() {
6732
6873
  const previousDirtyPaintChildren = this.dirtyPaintChildren;
6733
- this.dirtyPaintChildren = null;
6874
+ this.dirtyPaintChildren = this.enableDirtyRect ? this.buildDirtyPaintChildren([this.root.viewport.getWorldRectView()], Layer.VIEWPORT_CANDIDATE_RATIO) : null;
6734
6875
  try {
6735
6876
  this.clear();
6736
6877
  this.paint(this.ctx);
@@ -6738,40 +6879,33 @@ var Layer = class Layer extends Element {
6738
6879
  this.dirtyPaintChildren = previousDirtyPaintChildren;
6739
6880
  }
6740
6881
  }
6741
- /** 树结构变化后提交 Layer 内用于命中排序的 preorder。
6742
- *
6743
- * @internal
6744
- */
6745
- commitStructureOrder() {
6746
- let order = 0;
6747
- const visit = (element) => {
6748
- for (const child of element.children) {
6749
- child.committedPaintOrder = order++;
6750
- visit(child);
6751
- }
6752
- };
6753
- visit(this);
6754
- }
6755
- /** 从最终 damage 的 RBush hits 构建一次绘制期有序邻接表。 */
6756
- buildDirtyPaintChildren(worldRects) {
6757
- const hits = /* @__PURE__ */ new Set();
6882
+ /** 从最终 damage 的 RBush hits 构建一次绘制期有序邻接表;达到候选密度时返回 `null`。 */
6883
+ buildDirtyPaintChildren(worldRects, fullRepaintRatio = Layer.CANDIDATE_FULL_REPAINT_RATIO) {
6884
+ const spatialCount = this.spatialItems.size;
6885
+ const limit = spatialCount > 0 ? spatialCount * fullRepaintRatio : Infinity;
6758
6886
  const queryPad = 1 / (this.root.viewport.scale * this.root.viewport.dpr);
6759
- for (const rect of worldRects) {
6760
- const padded = {
6761
- left: rect.left - queryPad,
6762
- top: rect.top - queryPad,
6763
- width: rect.width + queryPad * 2,
6764
- height: rect.height + queryPad * 2
6765
- };
6766
- for (const hit of this.searchCommittedElements(padded)) hits.add(hit);
6887
+ const search = (rect) => this.searchCommittedElements({
6888
+ left: rect.left - queryPad,
6889
+ top: rect.top - queryPad,
6890
+ width: rect.width + queryPad * 2,
6891
+ height: rect.height + queryPad * 2
6892
+ });
6893
+ let hits;
6894
+ if (worldRects.length === 1) {
6895
+ hits = search(worldRects[0]);
6896
+ if (hits.length >= limit) return null;
6897
+ } else {
6898
+ const unique = /* @__PURE__ */ new Set();
6899
+ for (const rect of worldRects) {
6900
+ for (const hit of search(rect)) unique.add(hit);
6901
+ if (unique.size >= limit) return null;
6902
+ }
6903
+ hits = [...unique];
6767
6904
  }
6768
- const spatialCount = this.spatialItems.size;
6769
- if (spatialCount > 0 && (hits.size === spatialCount || hits.size >= spatialCount * Layer.CANDIDATE_FULL_REPAINT_RATIO)) return null;
6770
6905
  const childrenByParent = /* @__PURE__ */ new Map();
6771
- if (hits.size === 0) return childrenByParent;
6772
- const orderedHits = hits.size < 2 ? hits : [...hits].sort((left, right) => left.committedPaintOrder - right.committedPaintOrder);
6906
+ if (hits.length === 0) return childrenByParent;
6773
6907
  const included = /* @__PURE__ */ new Set();
6774
- for (const hit of orderedHits) {
6908
+ for (const hit of hits) {
6775
6909
  let child = hit;
6776
6910
  while (child !== this) {
6777
6911
  if (included.has(child)) break;
@@ -6783,6 +6917,7 @@ var Layer = class Layer extends Element {
6783
6917
  child = parent;
6784
6918
  }
6785
6919
  }
6920
+ for (const children of childrenByParent.values()) if (children.length > 1) children.sort((left, right) => left.siblingOrder - right.siblingOrder);
6786
6921
  return childrenByParent;
6787
6922
  }
6788
6923
  /** 裁剪到 damage 矩形,并消费已经完成组织的候选绘制树。 */
@@ -6998,4 +7133,4 @@ var Layer = class Layer extends Element {
6998
7133
  }
6999
7134
  };
7000
7135
  //#endregion
7001
- export { ChangeImpact, CustomEvent, DEFAULT_CONNECTION_PORT_SCHEMA, EVENT_NAMES, Element, ElementProperties, ElementTransform, EventEmitter, FrameStabilizationError, Layer, LayerProperties, LayerTransform, Node, NodeLifecycleEvent, NodeProperties, Root, RootFrameRuntime, RootInputController, SKIN_DEFAULTS, SceneRegistry, Shape, ShapeProperties, ShapeTransform, Skin, TransformProperties, Viewport, createAuthoredLineSubpath, createGeometryQuery, createGeometrySnapshot, createLineSubpath, createPathLocalId, evaluatePathSegmentPoint, getElementConnectionPort, getElementConnectionPortPoint, getElementConnectionPortPoints, isFormControlTarget, isReparentTransformIntent, mergeOwnerPropertyChanges, projectConnectionPortPoint, resolveAuthoredGeometryFramePatch, resolveAuthoredSubpath, resolveOrigin, resolveReferenceBoundsTranslation, resolveReferenceTransform, resolveReferenceTransformTarget, splitPathSegment };
7136
+ export { ChangeImpact, CustomEvent, DEFAULT_CONNECTION_PORT_SCHEMA, EVENT_NAMES, Element, ElementProperties, ElementTransform, EventEmitter, FrameStabilizationError, Layer, LayerProperties, LayerTransform, Node, NodeLifecycleEvent, NodeProperties, Root, RootFrameRuntime, RootInputController, SKIN_DEFAULTS, SceneRegistry, Shape, ShapeProperties, ShapeTransform, Skin, TransformProperties, Viewport, createAuthoredLineSubpath, createGeometryQuery, createGeometrySnapshot, createLineSubpath, createPathLocalId, diffChildren, evaluatePathSegmentPoint, getElementConnectionPort, getElementConnectionPortPoint, getElementConnectionPortPoints, isFormControlTarget, isReparentTransformIntent, mergeOwnerPropertyChanges, projectConnectionPortPoint, resolveAuthoredGeometryFramePatch, resolveAuthoredSubpath, resolveOrigin, resolveReferenceBoundsTranslation, resolveReferenceTransform, resolveReferenceTransformTarget, splitPathSegment };