@fulate/core 1.0.14 → 1.0.19

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,223 @@ 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 Map()
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 Map();
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) {
618
+ let placement = placementNodes.get(node);
619
+ if (!placement) {
620
+ placement = [node.parent, void 0];
621
+ placementNodes.set(node, placement);
622
+ }
623
+ if (beforeIndex < 0) placement[1] = owner;
624
+ }
625
+ }
626
+ changes.push({
627
+ owner,
628
+ children,
629
+ before,
630
+ start: diff.start,
631
+ end: diff.end,
632
+ changed
633
+ });
634
+ }
635
+ if (changes.length === 0) return NO_STRUCTURE_BATCH;
636
+ return {
637
+ changes,
638
+ placementNodes
639
+ };
640
+ }
641
+ /** @internal 直接安装 affected raw links。 */
642
+ function installStructureLinks(batch) {
643
+ for (const node of batch.placementNodes.keys()) node.detachBatchParent();
644
+ for (const { owner, children, start, end } of batch.changes) owner.installBatchChildren(children, start, end);
645
+ }
646
+ /**
647
+ * @internal 所有 fields/raw links 安装及 History 记录后,自上而下同步每个 placement 节点;
648
+ * parent 先完成自身迁移,同批进入它的 children 再按 parent 的最终 context 同步。
649
+ */
650
+ function syncStructureLifecycles(nodes) {
651
+ if (nodes.size === 0) return;
652
+ const depths = /* @__PURE__ */ new Map();
653
+ for (const node of nodes.keys()) {
654
+ let depth = 0;
655
+ for (let parent = node.parent; parent; parent = parent.parent) depth++;
656
+ depths.set(node, depth);
657
+ }
658
+ const ordered = [...nodes.keys()].sort((left, right) => depths.get(left) - depths.get(right));
659
+ for (const node of ordered) node.syncPlacementLifecycle();
660
+ }
661
+ //#endregion
662
+ //#region packages/core/src/mutation/change-batch.ts
663
+ /** @internal 合并 raw owner effects;单个 patch 直接借用,仅合并同 owner 字段时分配。 */
664
+ function mergeOwnerPropertyChanges(ownerEffects) {
665
+ const slots = /* @__PURE__ */ new Map();
666
+ let mergedOwners = null;
667
+ for (const { owner, patch } of ownerEffects) {
668
+ const current = slots.get(owner);
669
+ if (!current) {
670
+ slots.set(owner, patch);
671
+ continue;
672
+ }
673
+ let finalPatch;
674
+ if (mergedOwners?.has(owner)) finalPatch = current;
675
+ else {
676
+ finalPatch = {};
677
+ for (const key of Object.keys(current)) finalPatch[key] = current[key];
678
+ slots.set(owner, finalPatch);
679
+ (mergedOwners ??= /* @__PURE__ */ new Set()).add(owner);
680
+ }
681
+ for (const key of Object.keys(patch)) finalPatch[key] = patch[key];
682
+ }
683
+ return slots;
684
+ }
685
+ /**
686
+ * 同步应用一份 trusted change batch。
687
+ *
688
+ * owner effects 先按对象身份合并最终 patch;所有 fields/raw links 安装完成后才运行
689
+ * History、lifecycle、hooks、dirty 和最多一次 scene delivery;纯 paint 变化不通知 scene。
690
+ * 本函数不提供 rollback、
691
+ * retry、receipt 或 rejected 结果。返回本批次是否实际安装属性或结构变化。
692
+ */
693
+ function applyChangeBatch(root, ownerEffects, structureEffects = [], history) {
694
+ if (ownerEffects.length === 0 && structureEffects.length === 0) return false;
695
+ const slots = mergeOwnerPropertyChanges(ownerEffects);
696
+ const properties = [];
697
+ for (const [owner, patch] of slots) {
698
+ const commit = owner.preparePropertyCommit(patch);
699
+ if (commit) properties.push({
700
+ owner,
701
+ commit
702
+ });
703
+ }
704
+ const structureBatch = prepareStructureBatch(structureEffects);
705
+ const structure = structureBatch.changes;
706
+ if (properties.length === 0 && structure.length === 0) return false;
707
+ for (const { owner, commit } of properties) owner.installPropertyCommit(commit);
708
+ installStructureLinks(structureBatch);
709
+ if (history) {
710
+ for (const { owner, commit } of properties) for (const field of commit.update.fields) {
711
+ if (!field.sourceChanged) continue;
712
+ history.recordPropertyChange(owner, field.key, field.beforeSource);
713
+ }
714
+ for (const { owner, before } of structure) history.recordStructureChange(owner, before);
715
+ }
716
+ for (const [node, [previousParent, expectedParent]] of structureBatch.placementNodes) node.notifyBatchParentChanged(previousParent, expectedParent);
717
+ syncStructureLifecycles(structureBatch.placementNodes);
718
+ for (const { owner, commit } of properties) owner.syncPropertyCommitEvents(commit);
719
+ for (const { owner, commit } of properties) owner.runPropertyCommitHook(commit);
720
+ for (const { owner } of structure) owner.runBatchStructureHook();
721
+ for (const { owner, commit } of properties) owner.notifyPortsCommit(commit);
722
+ let layerOrderChanged = false;
723
+ let hoverChanged = false;
724
+ const observesScene = root?.sceneRegistry.hasSceneChangeObservers === true;
725
+ let sceneAffected;
726
+ for (const { owner, commit } of properties) {
727
+ if (owner.publishPropertyCommit(commit, false, false) && observesScene) (sceneAffected ??= /* @__PURE__ */ new Set()).add(owner);
728
+ if (commit.impact & ChangeImpact.LayerOrder) layerOrderChanged = true;
729
+ else if (commit.impact & ChangeImpact.Hover) hoverChanged = true;
730
+ }
731
+ for (const { owner } of structure) owner.publishBatchStructureDirty();
732
+ if (observesScene) for (const { owner, changed } of structure) {
733
+ (sceneAffected ??= /* @__PURE__ */ new Set()).add(owner);
734
+ for (const node of changed) sceneAffected.add(node);
735
+ }
736
+ if (structure.length) root?.commitBatchStructureChanges(structure, layerOrderChanged);
737
+ else if (layerOrderChanged) root?.commitLayerOrderChange();
738
+ else if (hoverChanged) root?.scheduleHoverRefresh();
739
+ if (sceneAffected) root?.sceneRegistry.notifySceneChange(void 0, [...sceneAffected]);
740
+ for (const { owner, commit } of properties) owner.dispatchPortsChange(commit);
741
+ return true;
742
+ }
743
+ //#endregion
527
744
  //#region packages/core/src/node/node.ts
528
745
  var nodeKeyPrefix = Date.now().toString(36);
529
746
  var nodeKeySequence = 0;
@@ -536,6 +753,63 @@ function setProvidesParent(node, parentProvides) {
536
753
  if (Object.getPrototypeOf(node.provides) !== parentProvides) Object.setPrototypeOf(node.provides, parentProvides);
537
754
  }
538
755
  var NO_LIFECYCLE_ERROR = Symbol("no lifecycle error");
756
+ /** 中间插入把相邻标签间隔压到该值以下时,重排所在 owner 的全部 children 标签。 */
757
+ var MIN_SIBLING_ORDER_GAP = 1e-6;
758
+ /**
759
+ * 为 `children[start, end)` 分配递增的 sibling 标签。窗口两侧是未变化的邻居,标签落在它们之间;
760
+ * 首尾插入向外延伸,间隔耗尽时只重排这一个 owner。
761
+ */
762
+ function assignSiblingOrders(children, start, end) {
763
+ const count = end - start;
764
+ if (count === 0) return;
765
+ const lower = start > 0 ? children[start - 1].siblingOrder : void 0;
766
+ const upper = end < children.length ? children[end].siblingOrder : void 0;
767
+ let first;
768
+ let step = 1;
769
+ if (lower === void 0) first = upper === void 0 ? 0 : upper - count;
770
+ else if (upper === void 0) first = lower + 1;
771
+ else {
772
+ step = (upper - lower) / (count + 1);
773
+ if (step < MIN_SIBLING_ORDER_GAP) {
774
+ for (let index = 0; index < children.length; index++) children[index].siblingOrder = index;
775
+ return;
776
+ }
777
+ first = lower + step;
778
+ }
779
+ for (let index = 0; index < count; index++) children[start + index].siblingOrder = first + index * step;
780
+ }
781
+ /** 返回节点到所在树根的 parent 跳数。 */
782
+ function treeDepth(node) {
783
+ let depth = 0;
784
+ for (let parent = node.parent; parent; parent = parent.parent) depth++;
785
+ return depth;
786
+ }
787
+ /**
788
+ * @internal 按同一棵树的 preorder 比较两个节点;祖先排在后代之前。只沿两条 parent 链走到
789
+ * 最近公共祖先,比较其下两个 child 的 sibling 标签。
790
+ */
791
+ function compareTreeOrder(left, right) {
792
+ if (left === right) return 0;
793
+ let leftDepth = treeDepth(left);
794
+ let rightDepth = treeDepth(right);
795
+ let leftBranch = left;
796
+ let rightBranch = right;
797
+ while (leftDepth > rightDepth) {
798
+ leftBranch = leftBranch.parent;
799
+ leftDepth--;
800
+ }
801
+ if (leftBranch === right) return 1;
802
+ while (rightDepth > leftDepth) {
803
+ rightBranch = rightBranch.parent;
804
+ rightDepth--;
805
+ }
806
+ if (rightBranch === left) return -1;
807
+ while (leftBranch.parent !== rightBranch.parent) {
808
+ leftBranch = leftBranch.parent;
809
+ rightBranch = rightBranch.parent;
810
+ }
811
+ return leftBranch.siblingOrder - rightBranch.siblingOrder;
812
+ }
539
813
  var LifecycleState = /* @__PURE__ */ function(LifecycleState) {
540
814
  LifecycleState["New"] = "new";
541
815
  LifecycleState["Inactive"] = "inactive";
@@ -592,6 +866,8 @@ var Node = class extends EventEmitter {
592
866
  nextSibling = null;
593
867
  /** 上一个 sibling;只读使用,通过树操作维护。 */
594
868
  previousSibling = null;
869
+ /** @internal 在当前 parent children 中递增的顺序标签;只在同一 parent 的 children 间可比较。 */
870
+ siblingOrder = 0;
595
871
  /** 是否已完成首次 mount 且尚未卸载。 */
596
872
  get isMounted() {
597
873
  return this.lifecycleState === LifecycleState.Inactive || this.lifecycleState === LifecycleState.Active;
@@ -635,38 +911,37 @@ var Node = class extends EventEmitter {
635
911
  super();
636
912
  this.#key = options.key ?? generateNodeKey();
637
913
  this.propertyState = properties;
638
- if (children) this.installChildren(this.adoptIncoming(children), false);
914
+ if (children) this.installChildren(this.adoptIncoming(children));
639
915
  }
640
- /** 安装最终 children 引用,并在一次循环内更新全部 raw links。 */
641
- installChildren(children, notifyParentChanges = true) {
916
+ /**
917
+ * 安装最终 children 引用,只更新 `[start, end)` 窗口及其两侧邻居的 raw links;
918
+ * 窗口外的公共前后缀与旧 children 相同。
919
+ */
920
+ installChildren(children, start = 0, end = children.length) {
642
921
  this.childNodes = children;
643
- for (let index = 0; index < children.length; index++) {
922
+ assignSiblingOrders(children, start, end);
923
+ const last = Math.min(end, children.length - 1);
924
+ for (let index = Math.max(0, start - 1); index <= last; index++) {
644
925
  const child = children[index];
645
926
  child.previousSibling = children[index - 1] ?? null;
646
927
  child.nextSibling = children[index + 1] ?? null;
647
- this.linkChild(child, notifyParentChanges);
648
928
  }
929
+ for (let index = start; index < end; index++) this.linkChild(children[index]);
649
930
  }
650
931
  /** 建立结构所有权、上下文原型链和事件冒泡 parent。 */
651
- linkChild(child, notifyParentChange) {
652
- if (child.parent !== this) {
653
- child.parent = this;
654
- if (notifyParentChange) child.onParentChanged();
655
- }
932
+ linkChild(child) {
933
+ if (child.parent !== this) child.parent = this;
656
934
  setProvidesParent(child, this.provides);
657
935
  }
658
936
  /** 解除结构所有权、sibling、上下文和事件冒泡关系。 */
659
937
  unlinkFromParent() {
660
- if (!isUndefined(this.parent)) {
661
- this.parent = void 0;
662
- this.onParentChanged();
663
- }
938
+ if (!isUndefined(this.parent)) this.parent = void 0;
664
939
  this.previousSibling = null;
665
940
  this.nextSibling = null;
666
941
  setProvidesParent(this, null);
667
942
  }
668
943
  /** raw parent link 改变后的派生 owner 接缝。 */
669
- onParentChanged() {}
944
+ onParentChanged(_previousParent) {}
670
945
  /** 直接 children 事务提交后的扩展点;构造期 children 不触发。 */
671
946
  onChildrenChanged() {}
672
947
  /** 全部 raw links 安装后的结构 dirty publication 扩展点。 */
@@ -675,48 +950,71 @@ var Node = class extends EventEmitter {
675
950
  markStructureDirty(changed) {
676
951
  const expected = this.childNodes;
677
952
  this.onChildrenChanged();
678
- if (this.childNodes !== expected) return;
679
- this.onStructureDirty();
680
- if (this.childNodes !== expected) return;
953
+ if (this.childNodes === expected) this.onStructureDirty();
954
+ this.publishStructureChange(changed);
955
+ }
956
+ /**
957
+ * 向 Root 发布已安装的 placement 变化。hook 重入提交更新 children 后,外层提交仍发布
958
+ * 自己已安装的变化;Root 按每个节点当前的 parent 与 lifecycle 过滤。
959
+ */
960
+ publishStructureChange(changed) {
681
961
  if (this.isActive) this.activeRoot?.commitStructureChange(this, changed);
682
962
  }
683
963
  /** 安装一次最终 children,并在当前提交仍有效时发布结构变化。 */
684
- commitChildren(next, entered = [], left = [], deactivateLeft = false, changed = [...entered, ...left]) {
685
- const previous = this.childNodes;
686
- if (previous.length === next.length && previous.every((child, index) => child === next[index])) return false;
687
- for (const child of left) {
688
- child.unlinkFromParent();
689
- if (this.childNodes !== previous) return true;
690
- }
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;
695
- }
696
- if (this.isActive) for (const child of entered) {
697
- if (this.childNodes !== next) return true;
698
- 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;
964
+ commitChildren(next, entered = [], left = [], deactivateLeft = false) {
965
+ let previousParents;
966
+ for (const child of entered) if (child.parent && child.parent !== this) (previousParents ??= /* @__PURE__ */ new Set()).add(child.parent);
967
+ if (previousParents) {
968
+ const moving = new Set(entered);
969
+ const structure = [];
970
+ let root = this.activeRoot ?? void 0;
971
+ for (const owner of previousParents) {
972
+ root ??= owner.activeRoot ?? void 0;
973
+ structure.push({
974
+ owner,
975
+ children: owner.children.filter((child) => !moving.has(child))
976
+ });
977
+ }
978
+ structure.push({
979
+ owner: this,
980
+ children: next
981
+ });
982
+ return applyChangeBatch(root, [], structure);
709
983
  }
710
- this.markStructureDirty(changed);
984
+ const previous = this.childNodes;
985
+ const diff = diffChildren(previous, next);
986
+ if (diff.changes.length === 0) return false;
987
+ for (const child of left) child.unlinkFromParent();
988
+ this.installChildren(next, diff.start, diff.end);
989
+ for (const child of left) if (!child.parent) child.onParentChanged(this);
990
+ for (const child of entered) if (child.parent === this) child.onParentChanged(void 0);
991
+ this.syncCommittedLifecycles(entered, left, deactivateLeft);
992
+ const changed = diff.changes.map(({ node }) => node);
993
+ if (this.childNodes === next) this.markStructureDirty(changed);
994
+ else this.publishStructureChange(changed);
711
995
  return true;
712
996
  }
997
+ /**
998
+ * 同步本次进入与离开节点的 lifecycle。lifecycle 回调可以同步重入修改结构,因此每个节点都按
999
+ * 自己与当前 owner 的实时 parent 和 lifecycle 判断,不因 children 被新提交替换而遗漏其余节点。
1000
+ */
1001
+ syncCommittedLifecycles(entered, left, deactivateLeft) {
1002
+ if (deactivateLeft) {
1003
+ for (const child of left) if (!child.parent && child.isActive) child.transitionLifecycle(LifecycleState.Inactive);
1004
+ }
1005
+ for (const child of entered) if (child.parent === this) child.syncPlacementLifecycle();
1006
+ }
713
1007
  /** @internal trusted batch 解除真实变化节点的旧 placement。 */
714
1008
  detachBatchParent() {
715
1009
  this.unlinkFromParent();
716
1010
  }
717
- /** @internal 接收 trusted batch 转移所有权的最终 children 快照。 */
718
- installBatchChildren(children) {
719
- this.installChildren(children);
1011
+ /** @internal 接收 trusted batch 转移所有权的最终 children 与其变化窗口。 */
1012
+ installBatchChildren(children, start, end) {
1013
+ this.installChildren(children, start, end);
1014
+ }
1015
+ /** @internal 完整安装后的 parent hook;重入提交已改写归属时跳过旧结果。 */
1016
+ notifyBatchParentChanged(previousParent, expectedParent) {
1017
+ if (this.parent === expectedParent && this.parent !== previousParent) this.onParentChanged(previousParent);
720
1018
  }
721
1019
  /** @internal 按当前 parent 同步最终 lifecycle context。 */
722
1020
  syncPlacementLifecycle() {
@@ -726,7 +1024,7 @@ var Node = class extends EventEmitter {
726
1024
  const targetLayer = this.isLayerNode() ? this : parent?.inject("layer") ?? null;
727
1025
  if (!shouldBeActive || this.activeLayer !== targetLayer) this.transitionLifecycle(LifecycleState.Inactive);
728
1026
  }
729
- if (shouldBeActive && !this.isActive) this.transitionLifecycle(LifecycleState.Active);
1027
+ if (this.parent?.isActive === true && !this.isActive) this.transitionLifecycle(LifecycleState.Active);
730
1028
  }
731
1029
  /** @internal tree 已完整安装后登记当前 owner 的 dirty path。 */
732
1030
  publishBatchStructureDirty() {
@@ -745,27 +1043,27 @@ var Node = class extends EventEmitter {
745
1043
  next.splice(index, 1);
746
1044
  return this.commitChildren(next, [], [child], detach);
747
1045
  }
748
- /** 从旧 owner 分离 incoming child,并确认同步回调没有再次接管它。 */
749
- detachFromParent(child) {
750
- const oldParent = child.parent;
751
- if (!oldParent || oldParent === this) return true;
752
- let keepsContext = false;
753
- if (this.isActive) {
754
- const inheritedLayer = this.inject("layer") ?? null;
755
- keepsContext = child.isActive && child.activeLayer === inheritedLayer;
756
- }
757
- oldParent.removeOwnChild(child, false);
758
- if (child.parent === oldParent) return false;
759
- if (!keepsContext && isUndefined(child.parent)) child.transitionLifecycle(LifecycleState.Inactive);
760
- return isUndefined(child.parent);
761
- }
762
- /** 分离 incoming nodes;只有同步回调改写归属时才创建过滤后的数组。 */
1046
+ /** 构造期采用 children,回调已建立的新归属不再由旧输入接管。 */
763
1047
  adoptIncoming(nodes) {
1048
+ let hasPreviousParent = false;
1049
+ for (const child of nodes) if (child.parent && child.parent !== this) {
1050
+ hasPreviousParent = true;
1051
+ break;
1052
+ }
1053
+ if (!hasPreviousParent) return nodes;
1054
+ const expectedParents = nodes.map((child) => child.parent);
1055
+ for (let index = 0; index < nodes.length; index++) {
1056
+ const child = nodes[index];
1057
+ const previousParent = expectedParents[index];
1058
+ if (child.parent !== previousParent || !previousParent || previousParent === this) continue;
1059
+ previousParent.removeOwnChild(child, false);
1060
+ expectedParents[index] = void 0;
1061
+ if (!child.parent && child.isActive) child.transitionLifecycle(LifecycleState.Inactive);
1062
+ }
764
1063
  let adopted = null;
765
1064
  for (let index = 0; index < nodes.length; index++) {
766
1065
  const child = nodes[index];
767
- const oldParent = child.parent;
768
- if (!oldParent || oldParent === this || this.detachFromParent(child)) adopted?.push(child);
1066
+ if (!child.isUnmounted && child.parent === expectedParents[index] && (!child.parent || child.parent === this)) adopted?.push(child);
769
1067
  else if (!adopted) adopted = nodes.slice(0, index);
770
1068
  }
771
1069
  return adopted ?? nodes;
@@ -773,14 +1071,19 @@ var Node = class extends EventEmitter {
773
1071
  /** 统一实现 append/prepend/before/after 的移动和插入事务。 */
774
1072
  insertAt(nodes, getIndex) {
775
1073
  if (nodes.length === 0) return this;
776
- const adopted = this.adoptIncoming(nodes);
777
- if (adopted.length === 0) return this;
778
- const moving = new Set(adopted);
779
- const next = [...this.childNodes].filter((child) => !moving.has(child));
1074
+ let next;
1075
+ if (nodes.length === 1) {
1076
+ next = this.childNodes.slice();
1077
+ const current = next.indexOf(nodes[0]);
1078
+ if (current !== -1) next.splice(current, 1);
1079
+ } else {
1080
+ const moving = new Set(nodes);
1081
+ next = this.childNodes.filter((child) => !moving.has(child));
1082
+ }
780
1083
  const index = clamp(getIndex(next), 0, next.length);
781
- next.splice(index, 0, ...adopted);
782
- const entered = adopted.filter((child) => child.parent !== this);
783
- this.commitChildren(next, entered, [], false, adopted);
1084
+ next.splice(index, 0, ...nodes);
1085
+ const entered = nodes.filter((child) => child.parent !== this);
1086
+ this.commitChildren(next, entered);
784
1087
  return this;
785
1088
  }
786
1089
  /** 将节点移动或追加到 children 尾部。 */
@@ -810,16 +1113,13 @@ var Node = class extends EventEmitter {
810
1113
  nextChildren.splice(oldIndex, 1, newChild);
811
1114
  return this.replaceChildren(...nextChildren);
812
1115
  }
813
- /** 原子替换完整 children 序列。 */
1116
+ /** 替换完整 children 序列,完整安装后发布变化。 */
814
1117
  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];
818
- const committed = this.adoptIncoming(children);
819
- const committedSet = new Set(committed);
820
- const left = previous.filter((child) => !committedSet.has(child));
821
- const entered = committed.filter((child) => child.parent !== this);
822
- this.commitChildren(committed, entered, left, true, [...committed, ...left]);
1118
+ const previous = this.childNodes;
1119
+ const childrenSet = new Set(children);
1120
+ const left = previous.filter((child) => !childrenSet.has(child));
1121
+ const entered = children.filter((child) => child.parent !== this);
1122
+ this.commitChildren(children, entered, left, true);
823
1123
  return this;
824
1124
  }
825
1125
  /** 将节点移动到当前节点之前。 */
@@ -917,7 +1217,10 @@ var Node = class extends EventEmitter {
917
1217
  this.lifecycleState = LifecycleState.Inactive;
918
1218
  if (!rootIsUnmounting) root?.sceneRegistry.unregisterNodeKey(this);
919
1219
  if (!layer?.isUnmounted) layer?.detachNode(this);
920
- if (deactivateChildren) for (const child of this.children) child.transitionLifecycle(LifecycleState.Inactive);
1220
+ if (deactivateChildren) for (const child of this.children) {
1221
+ if (child.parent !== this) continue;
1222
+ child.transitionLifecycle(LifecycleState.Inactive);
1223
+ }
921
1224
  if (!rootIsUnmounting) root?.clearHoverFor(this);
922
1225
  this.onDeactivate(root, layer);
923
1226
  }
@@ -950,10 +1253,13 @@ var Node = class extends EventEmitter {
950
1253
  } catch (error) {
951
1254
  firstError = error;
952
1255
  }
953
- for (const child of terminalChildren) try {
954
- child.transitionLifecycle(LifecycleState.Unmounted);
955
- } catch (error) {
956
- if (firstError === NO_LIFECYCLE_ERROR) firstError = error;
1256
+ for (const child of terminalChildren) {
1257
+ if (child.parent !== this) continue;
1258
+ try {
1259
+ child.transitionLifecycle(LifecycleState.Unmounted);
1260
+ } catch (error) {
1261
+ if (firstError === NO_LIFECYCLE_ERROR) firstError = error;
1262
+ }
957
1263
  }
958
1264
  if (wasActive) try {
959
1265
  this.leaveActiveContext(this.activeRoot, this.activeLayer, false);
@@ -1023,14 +1329,16 @@ var EMPTY_LAYOUT_BOUNDS$1 = {
1023
1329
  width: 0,
1024
1330
  height: 0
1025
1331
  };
1026
- var snapshotHasGeometry = /* @__PURE__ */ new WeakMap();
1027
- function registerSnapshot(snapshot, hasGeometry) {
1028
- snapshotHasGeometry.set(snapshot, hasGeometry);
1029
- return snapshot;
1030
- }
1332
+ var SnapshotGeometryFlags = /* @__PURE__ */ function(SnapshotGeometryFlags) {
1333
+ SnapshotGeometryFlags[SnapshotGeometryFlags["HasGeometry"] = 1] = "HasGeometry";
1334
+ SnapshotGeometryFlags[SnapshotGeometryFlags["ExactReferenceBounds"] = 2] = "ExactReferenceBounds";
1335
+ return SnapshotGeometryFlags;
1336
+ }(SnapshotGeometryFlags || {});
1337
+ var snapshotGeometryFlags = /* @__PURE__ */ new WeakMap();
1031
1338
  /** @internal 读取通用 snapshot 的非空元数据。 */
1032
1339
  function genericSnapshotHasGeometry(snapshot) {
1033
- return snapshotHasGeometry.get(snapshot) ?? snapshot.subpaths.some((subpath) => subpath.vertices.length > 0);
1340
+ const flags = snapshotGeometryFlags.get(snapshot);
1341
+ return flags === void 0 ? snapshot.subpaths.some((subpath) => subpath.vertices.length > 0) : (flags & SnapshotGeometryFlags.HasGeometry) !== 0;
1034
1342
  }
1035
1343
  /** @internal 保持极大/极小坐标计算的共同缩放。 */
1036
1344
  function nonzeroScale(...values) {
@@ -1285,34 +1593,23 @@ function scaledCubicPowerCoefficients(start, control1, control2, end, scale, off
1285
1593
  coefficients[0] -= offset / scale;
1286
1594
  return coefficients;
1287
1595
  }
1288
- function boundSegment(record) {
1289
- let minX = Infinity;
1290
- let minY = Infinity;
1291
- let maxX = -Infinity;
1292
- let maxY = -Infinity;
1596
+ function includeSegmentBounds(bounds, start, shape, end) {
1293
1597
  const include = (point) => {
1294
- minX = Math.min(minX, point.x);
1295
- minY = Math.min(minY, point.y);
1296
- maxX = Math.max(maxX, point.x);
1297
- maxY = Math.max(maxY, point.y);
1598
+ bounds.minX = Math.min(bounds.minX, point.x);
1599
+ bounds.minY = Math.min(bounds.minY, point.y);
1600
+ bounds.maxX = Math.max(bounds.maxX, point.x);
1601
+ bounds.maxY = Math.max(bounds.maxY, point.y);
1298
1602
  };
1299
- include(record.start);
1300
- include(record.end);
1301
- if (record.shape.kind === "cubic") {
1302
- const xScale = nonzeroScale(record.start.x, record.shape.control1.x, record.shape.control2.x, record.end.x);
1303
- const yScale = nonzeroScale(record.start.y, record.shape.control1.y, record.shape.control2.y, record.end.y);
1304
- const x = scaledCubicPowerCoefficients(record.start.x, record.shape.control1.x, record.shape.control2.x, record.end.x, xScale);
1305
- const y = scaledCubicPowerCoefficients(record.start.y, record.shape.control1.y, record.shape.control2.y, record.end.y, yScale);
1603
+ include(start);
1604
+ include(end);
1605
+ if (shape.kind === "cubic") {
1606
+ const xScale = nonzeroScale(start.x, shape.control1.x, shape.control2.x, end.x);
1607
+ const yScale = nonzeroScale(start.y, shape.control1.y, shape.control2.y, end.y);
1608
+ const x = scaledCubicPowerCoefficients(start.x, shape.control1.x, shape.control2.x, end.x, xScale);
1609
+ const y = scaledCubicPowerCoefficients(start.y, shape.control1.y, shape.control2.y, end.y, yScale);
1306
1610
  const extrema = [...rootsInUnitInterval(derivativePolynomial(x)), ...rootsInUnitInterval(derivativePolynomial(y))];
1307
- for (const t of extrema) if (t > 0 && t < 1) include(pointAt(record, t));
1611
+ for (const t of extrema) if (t > 0 && t < 1) include(evaluatePathSegmentPoint(start, shape, end, t));
1308
1612
  }
1309
- return {
1310
- record,
1311
- minX,
1312
- minY,
1313
- maxX,
1314
- maxY
1315
- };
1316
1613
  }
1317
1614
  function buildGeometryBounds(subpaths, recordsBySubpath) {
1318
1615
  const boundedSegments = [];
@@ -1340,7 +1637,14 @@ function buildGeometryBounds(subpaths, recordsBySubpath) {
1340
1637
  maxY = Math.max(maxY, vertex.point.y);
1341
1638
  }
1342
1639
  for (const record of recordsBySubpath[subpathIndex]) {
1343
- const bounded = boundSegment(record);
1640
+ const bounded = {
1641
+ record,
1642
+ minX: Infinity,
1643
+ minY: Infinity,
1644
+ maxX: -Infinity,
1645
+ maxY: -Infinity
1646
+ };
1647
+ includeSegmentBounds(bounded, record.start, record.shape, record.end);
1344
1648
  boundedSegments.push(bounded);
1345
1649
  includeBounds(bounded);
1346
1650
  }
@@ -1372,16 +1676,63 @@ function buildGeometryBounds(subpaths, recordsBySubpath) {
1372
1676
  bounds
1373
1677
  };
1374
1678
  }
1679
+ function includeSubpathBounds(bounds, vertices, shapes, segmentCount) {
1680
+ for (const { point } of vertices) {
1681
+ bounds.minX = Math.min(bounds.minX, point.x);
1682
+ bounds.minY = Math.min(bounds.minY, point.y);
1683
+ bounds.maxX = Math.max(bounds.maxX, point.x);
1684
+ bounds.maxY = Math.max(bounds.maxY, point.y);
1685
+ }
1686
+ for (let index = 0; index < segmentCount; index++) {
1687
+ const shape = shapes[index];
1688
+ if (shape.kind === "cubic") includeSegmentBounds(bounds, vertices[index].point, shape, vertices[(index + 1) % vertices.length].point);
1689
+ }
1690
+ }
1691
+ function layoutBoundsFromBBox(bounds) {
1692
+ return bounds.minX === Infinity ? EMPTY_LAYOUT_BOUNDS$1 : {
1693
+ left: bounds.minX,
1694
+ top: bounds.minY,
1695
+ width: bounds.maxX - bounds.minX,
1696
+ height: bounds.maxY - bounds.minY
1697
+ };
1698
+ }
1375
1699
  function exactBounds(subpaths) {
1376
- return buildGeometryBounds(subpaths, buildSegmentRecords(subpaths).segmentsBySubpath).bounds;
1700
+ const bounds = {
1701
+ minX: Infinity,
1702
+ minY: Infinity,
1703
+ maxX: -Infinity,
1704
+ maxY: -Infinity
1705
+ };
1706
+ for (const subpath of subpaths) includeSubpathBounds(bounds, subpath.vertices, subpath.segmentShapes, subpath.segmentShapes.length);
1707
+ return layoutBoundsFromBBox(bounds);
1708
+ }
1709
+ /** 直接读取 authored anchors 的精确 line/cubic bounds,不创建 resolved 投影。 */
1710
+ function getAuthoredPathLayoutBounds(subpaths) {
1711
+ const bounds = {
1712
+ minX: Infinity,
1713
+ minY: Infinity,
1714
+ maxX: -Infinity,
1715
+ maxY: -Infinity
1716
+ };
1717
+ for (const subpath of subpaths) {
1718
+ const { anchors, closed } = subpath;
1719
+ includeSubpathBounds(bounds, anchors, anchors, anchors.length < 2 ? 0 : closed ? anchors.length : anchors.length - 1);
1720
+ }
1721
+ return layoutBoundsFromBBox(bounds);
1377
1722
  }
1378
1723
  /**
1379
1724
  * 直接采用输入对象及其 subpath、point、control、标量 authored ID 和 bounds 引用。
1380
1725
  * 省略 bounds 时在同一输入对象上安装一次派生结果;不创建 GeometryQuery index。
1381
1726
  */
1382
1727
  function createGeometrySnapshot(input) {
1383
- if (input.layoutReferenceBounds === void 0) input.layoutReferenceBounds = exactBounds(input.subpaths) ?? EMPTY_LAYOUT_BOUNDS$1;
1384
- return registerSnapshot(input, input.subpaths.some((subpath) => subpath.vertices.length > 0));
1728
+ let flags = input.subpaths.some((subpath) => subpath.vertices.length > 0) ? SnapshotGeometryFlags.HasGeometry : 0;
1729
+ if (input.layoutReferenceBounds === void 0) {
1730
+ input.layoutReferenceBounds = exactBounds(input.subpaths);
1731
+ flags |= SnapshotGeometryFlags.ExactReferenceBounds;
1732
+ }
1733
+ const snapshot = input;
1734
+ snapshotGeometryFlags.set(snapshot, flags);
1735
+ return snapshot;
1385
1736
  }
1386
1737
  function pointDistance(left, right) {
1387
1738
  const scale = nonzeroScale(left.x, left.y, right.x, right.y);
@@ -1499,7 +1850,7 @@ function rayWinding(record, previous, point) {
1499
1850
  /** @internal 通用 line/cubic canonical query。 */
1500
1851
  var SnapshotGeometryQuery = class {
1501
1852
  snapshot;
1502
- /** 第一次真实 query 前保持 `null`。 */
1853
+ /** 第一次需要 segment 的 query 前保持 `null`。 */
1503
1854
  index = null;
1504
1855
  debugStats = null;
1505
1856
  constructor(snapshot) {
@@ -1543,6 +1894,8 @@ var SnapshotGeometryQuery = class {
1543
1894
  return { ...this.debugStats };
1544
1895
  }
1545
1896
  getBounds() {
1897
+ const flags = snapshotGeometryFlags.get(this.snapshot) ?? 0;
1898
+ if (flags & SnapshotGeometryFlags.ExactReferenceBounds) return flags & SnapshotGeometryFlags.HasGeometry ? this.snapshot.layoutReferenceBounds : null;
1546
1899
  return this.getBoundsData().bounds;
1547
1900
  }
1548
1901
  getPathPoint(position) {
@@ -1786,6 +2139,10 @@ function createAuthoredLineSubpath(points, closed) {
1786
2139
  function geometrySnapshotHasGeometry(snapshot) {
1787
2140
  return snapshot instanceof RectangleGeometrySnapshot || genericSnapshotHasGeometry(snapshot);
1788
2141
  }
2142
+ /** @internal 普通矩形 canonical snapshot 返回其矩形;其他几何返回 `null`,不强制惰性 subpaths。 */
2143
+ function geometrySnapshotRectangle(snapshot) {
2144
+ return snapshot instanceof RectangleGeometrySnapshot ? snapshot.layoutReferenceBounds : null;
2145
+ }
1789
2146
  /** 创建尚未建立内部 index 的唯一 canonical snapshot query。 */
1790
2147
  function createGeometryQuery(snapshot) {
1791
2148
  return snapshot instanceof RectangleGeometrySnapshot ? new RectangleSnapshotGeometryQuery(snapshot) : new SnapshotGeometryQuery(snapshot);
@@ -1825,7 +2182,7 @@ function matrixChanged(matrix, previousA, previousB, previousC, previousD, previ
1825
2182
  var VISUAL_GEOMETRY_IMPACT$1 = ChangeImpact.LocalGeometry | ChangeImpact.WorldTransform | ChangeImpact.VisualBounds;
1826
2183
  var GEOMETRY_CACHE_IMPACT = ChangeImpact.LocalGeometry | ChangeImpact.WorldTransform | ChangeImpact.VisualBounds | ChangeImpact.HitBounds;
1827
2184
  var CHILD_LAYOUT_IMPACT = ChangeImpact.LocalGeometry | ChangeImpact.WorldTransform;
1828
- var IDENTITY_ELEMENT_TRANSFORM = new DOMMatrix();
2185
+ var IDENTITY_ELEMENT_TRANSFORM = new Matrix2D();
1829
2186
  /**
1830
2187
  * 一个 Element 唯一的变换、几何、damage 与子树派生状态 owner。
1831
2188
  *
@@ -1851,7 +2208,7 @@ var ElementTransform = class {
1851
2208
  /** 自身 reference 或 child world space 是否要求 descendants 重算布局。 */
1852
2209
  childLayoutDirty = false;
1853
2210
  /** 当前最后一次提交的 own world matrix。 */
1854
- worldMatrix = new DOMMatrix();
2211
+ worldMatrix = new Matrix2D();
1855
2212
  /** worldMatrix 的惰性逆矩阵。 */
1856
2213
  inverseWorldMatrix;
1857
2214
  /** 提供给 children 的 world 坐标空间逆矩阵。 */
@@ -1896,6 +2253,7 @@ var ElementTransform = class {
1896
2253
  }
1897
2254
  /** raw parent link 改变后只标记本地 world commit;publication 在结构阶段统一执行。 @internal */
1898
2255
  markParentChanged() {
2256
+ if ((!this.needsCommit || this.hitOnlyInvalidation) && this.element.isActive) this.captureCurrentVisualBounds();
1899
2257
  this.needsCommit = true;
1900
2258
  this.hitOnlyInvalidation = false;
1901
2259
  this.childLayoutDirty = true;
@@ -2115,7 +2473,7 @@ var ElementTransform = class {
2115
2473
  const offsetX = bounds ? bounds.left + (resolveOrigin(element.originX) + .5) * bounds.width : 0;
2116
2474
  const offsetY = bounds ? bounds.top + (resolveOrigin(element.originY) + .5) * bounds.height : 0;
2117
2475
  matrix.translateSelf(offsetX, offsetY);
2118
- if (hasAngle) matrix.rotateSelf(0, 0, element.angle);
2476
+ if (hasAngle) matrix.rotateSelf(element.angle);
2119
2477
  if (hasSkew) {
2120
2478
  if (element.skewX) matrix.skewXSelf(element.skewX);
2121
2479
  if (element.skewY) matrix.skewYSelf(element.skewY);
@@ -2134,18 +2492,16 @@ var ElementTransform = class {
2134
2492
  const previousF = this.worldMatrix.f;
2135
2493
  const authored = this.buildWorldMatrix();
2136
2494
  if (authored) {
2137
- this.worldMatrix = DOMMatrix.fromMatrix(authored);
2495
+ this.worldMatrix = Matrix2D.from(authored);
2138
2496
  return this.finishWorldMatrixCommit(previousA, previousB, previousC, previousD, previousE, previousF);
2139
2497
  }
2140
- let matrix = this.worldMatrix;
2141
- if (!matrix.is2D) matrix = this.worldMatrix = new DOMMatrix();
2142
2498
  const parent = this.element.parent;
2143
- this.writeScalarMatrix(matrix, parent?.transform?.getChildWorldMatrixView());
2499
+ this.writeScalarMatrix(this.worldMatrix, parent?.transform?.getChildWorldMatrixView());
2144
2500
  return this.finishWorldMatrixCommit(previousA, previousB, previousC, previousD, previousE, previousF);
2145
2501
  }
2146
2502
  /** 返回已提交的 world 矩阵副本,不包含 Viewport 和 DPR。 */
2147
2503
  getWorldMatrix() {
2148
- return DOMMatrix.fromMatrix(this.worldMatrix);
2504
+ return Matrix2D.from(this.worldMatrix);
2149
2505
  }
2150
2506
  /** 借用已提交矩阵;调用方不得修改或保留。 @internal */
2151
2507
  getWorldMatrixView() {
@@ -2160,7 +2516,7 @@ var ElementTransform = class {
2160
2516
  this.inverseChildWorldMatrix = inverse;
2161
2517
  return inverse;
2162
2518
  }
2163
- return this.inverseChildWorldMatrix = DOMMatrix.fromMatrix(childWorldMatrix).inverse();
2519
+ return this.inverseChildWorldMatrix = childWorldMatrix.inverse();
2164
2520
  }
2165
2521
  /** 返回已解析尺寸中心对应的 world 坐标。 */
2166
2522
  getWorldCenter() {
@@ -2362,6 +2718,7 @@ var ElementTransform = class {
2362
2718
  }
2363
2719
  this.invalidateCache(impact);
2364
2720
  } else this.invalidate(impact);
2721
+ this.element.activeRoot?.scheduleHoverRefresh();
2365
2722
  return true;
2366
2723
  }
2367
2724
  /** @internal 提交由布局解析得到的尺寸。 */
@@ -2461,7 +2818,7 @@ var ElementTransform = class {
2461
2818
  collectContentBoundsInReference(parentMatrix, referenceWorldInverse) {
2462
2819
  if (!this.element.visible || !this.contributesToAncestorContentBounds()) return null;
2463
2820
  const independentWorldMatrix = this.buildWorldMatrix();
2464
- const matrix = independentWorldMatrix ? referenceWorldInverse.multiply(independentWorldMatrix) : this.writeScalarMatrix(new DOMMatrix(), parentMatrix);
2821
+ const matrix = independentWorldMatrix ? referenceWorldInverse.multiply(independentWorldMatrix) : this.writeScalarMatrix(new Matrix2D(), parentMatrix);
2465
2822
  const ownBounds = this.hasGeometry() ? this.toBounds(matrix, this.getOwnContentBoundsView()) : null;
2466
2823
  let childParentMatrix = matrix;
2467
2824
  const childWorldMatrix = this.getChildWorldMatrixView();
@@ -2532,8 +2889,8 @@ var ElementTransform = class {
2532
2889
  collectDirtySubtreeBounds(memo) {
2533
2890
  let bounds = this.getPreviousVisualBounds();
2534
2891
  if (this.hasGeometry()) {
2535
- const current = this.getWorldVisualBounds();
2536
- bounds = bounds ? bounds.merge(current) : current;
2892
+ const current = this.getWorldVisualBoundsView();
2893
+ bounds = bounds ? bounds.merge(current) : new Bound(current.minX, current.minY, current.maxX, current.maxY);
2537
2894
  }
2538
2895
  for (const child of this.element.children) {
2539
2896
  const childBounds = memo ? child.transform.getDirtyRect(memo) : child.transform.getDirtyRect();
@@ -2592,8 +2949,7 @@ var ElementTransform = class {
2592
2949
  hasInView() {
2593
2950
  const element = this.element;
2594
2951
  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();
2952
+ const { left: viewLeft, top: viewTop, width: viewWidth, height: viewHeight } = element.root.viewport.getWorldRectView();
2597
2953
  const bounds = element.children.length === 0 ? this.hasGeometry() ? this.getWorldVisualBoundsView() : null : this.getRenderCoverageBoundsView();
2598
2954
  if (!bounds) return false;
2599
2955
  return bounds.left + bounds.width > viewLeft && bounds.left < viewLeft + viewWidth && bounds.top + bounds.height > viewTop && bounds.top < viewTop + viewHeight;
@@ -3068,8 +3424,6 @@ var Element = class Element extends Node {
3068
3424
  type = "element";
3069
3425
  /** 当前 Element 唯一的变换与几何运行时。 */
3070
3426
  transform;
3071
- /** @internal Layer 内用于绘制顺序命中的已提交树序号。 */
3072
- committedPaintOrder = -1;
3073
3427
  /** hover 时使用的 CSS cursor。 */
3074
3428
  get cursor() {
3075
3429
  return this.propertyState.cursor;
@@ -3200,7 +3554,7 @@ var Element = class Element extends Node {
3200
3554
  this.syncOptionEvents(properties, Object.keys(options));
3201
3555
  }
3202
3556
  /** raw parent link 变化只标记 transform local commit。 */
3203
- onParentChanged() {
3557
+ onParentChanged(_previousParent) {
3204
3558
  this.transform.markParentChanged();
3205
3559
  }
3206
3560
  /** raw children 完整安装后的 transform hook。 */
@@ -3305,13 +3659,15 @@ var Element = class Element extends Node {
3305
3659
  publishPropertyCommit(commit, notifyScene, publishRootImpact = true) {
3306
3660
  const { changes } = commit.update;
3307
3661
  const { impact, previousVisualBounds } = commit;
3308
- if (!changes.size) return;
3662
+ if (!changes.size) return false;
3309
3663
  const visibilityChanged = changes.has("visible");
3310
3664
  if (visibilityChanged) this.transform.invalidateRenderCoverageBounds();
3311
3665
  if ((impact & GEOMETRY_IMPACT) !== 0) this.transform.invalidate(impact, previousVisualBounds);
3312
3666
  else if (visibilityChanged) this.transform.markVisibilityDirty();
3313
3667
  if (impact) this.invalidate(impact, publishRootImpact);
3314
- if (notifyScene && ((impact & GEOMETRY_IMPACT) !== 0 || (impact & ChangeImpact.LayerOrder) !== 0 || changes.has("visible") || changes.has("selectable") || changes.has("silent") || changes.has("pickable"))) this.activeRoot?.sceneRegistry.notifySceneChange(this);
3668
+ const affectsScene = (impact & (GEOMETRY_IMPACT | ChangeImpact.LayerOrder)) !== 0 || changes.has("visible") || changes.has("selectable") || changes.has("silent") || changes.has("pickable");
3669
+ if (notifyScene && affectsScene) this.activeRoot?.sceneRegistry.notifySceneChange(this);
3670
+ return affectsScene;
3315
3671
  }
3316
3672
  /** 应用一份 direct configured/runtime update 并完成一次成功路径 publication。 */
3317
3673
  commitPreparedProperty(commit) {
@@ -3421,15 +3777,18 @@ var Element = class Element extends Node {
3421
3777
  for (let i = 1; i < coords.length; i++) ctx.lineTo(coords[i].x, coords[i].y);
3422
3778
  ctx.closePath();
3423
3779
  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
3780
  ctx.strokeStyle = this.activeRoot?.skin.selection ?? SKIN_DEFAULTS.selection;
3429
3781
  ctx.lineWidth = 2 / scale;
3430
3782
  ctx.stroke();
3431
3783
  ctx.restore();
3432
3784
  }
3785
+ /**
3786
+ * @internal 把与 `paintHover()` 等价的轮廓追加到当前 path,由调用方统一描边。
3787
+ * 返回 `false` 时调用方改用 `paintHover()` 独立绘制。
3788
+ */
3789
+ traceHoverOutline(_ctx, _scale) {
3790
+ return false;
3791
+ }
3433
3792
  /** 从当前 live owner 直接解析一次可连接 Ports。 */
3434
3793
  getConnectionPorts() {
3435
3794
  this.resolveCurrentConnectionPortProjection();
@@ -3696,7 +4055,8 @@ var Element = class Element extends Node {
3696
4055
  };
3697
4056
  //#endregion
3698
4057
  //#region packages/core/src/node/reference-transform.ts
3699
- var IDENTITY_REFERENCE_TRANSFORM = new DOMMatrix();
4058
+ var IDENTITY_REFERENCE_TRANSFORM = new Matrix2D();
4059
+ var SCALE_EPSILON = 1e-9;
3700
4060
  /**
3701
4061
  * 纯 world translation 且 parent 线性变换未改变时,只生成真实变化的 left/top。
3702
4062
  * 这条结果与通用矩阵分解等价,但不 materialize 未变化的 pose/size fields。
@@ -3715,6 +4075,15 @@ function resolveSparseReferenceTranslation(baseline, intent, targetParentWorldMa
3715
4075
  authoredLocalDelta: IDENTITY_REFERENCE_TRANSFORM
3716
4076
  };
3717
4077
  }
4078
+ /**
4079
+ * 目标轴向尺度相对 authored 尺度的比例。与 1 的相对差不超过 {@link SCALE_EPSILON} 时视为尺寸
4080
+ * 不变,移动、旋转和翻转等刚体变换因此精确保留 authored width/height。
4081
+ */
4082
+ function resolveAuthoredScale(target, authored) {
4083
+ if (authored === 0) return 1;
4084
+ const ratio = Math.abs(target / authored);
4085
+ return Math.abs(ratio - 1) <= SCALE_EPSILON ? 1 : ratio;
4086
+ }
3718
4087
  function sameMatrix(left, right) {
3719
4088
  return sameLinearMatrix(left, right) && left.e === right.e && left.f === right.f;
3720
4089
  }
@@ -3722,7 +4091,7 @@ function sameLinearMatrix(left, right) {
3722
4091
  return left.a === right.a && left.b === right.b && left.c === right.c && left.d === right.d;
3723
4092
  }
3724
4093
  function createFrameLinearMatrix(frame) {
3725
- return new DOMMatrix().rotate(0, 0, frame.angle).skewX(frame.skewX).skewY(frame.skewY).scale(frame.scaleX, frame.scaleY);
4094
+ return new Matrix2D().rotateSelf(frame.angle).skewXSelf(frame.skewX).skewYSelf(frame.skewY).scaleSelf(frame.scaleX, frame.scaleY);
3726
4095
  }
3727
4096
  function transformReferenceBounds(bounds, matrix) {
3728
4097
  const right = bounds.left + bounds.width;
@@ -3774,14 +4143,7 @@ function resolveBakedAuthoredGeometryTransform(baseline, target) {
3774
4143
  const determinant = frameLinear.a * frameLinear.d - frameLinear.b * frameLinear.c;
3775
4144
  if (!Number.isFinite(determinant) || determinant === 0) return null;
3776
4145
  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
- ]);
4146
+ const targetLinear = new Matrix2D(targetLocal.a, targetLocal.b, targetLocal.c, targetLocal.d, 0, 0);
3785
4147
  const authoredLocalDelta = frameLinear.inverse().multiply(targetLinear);
3786
4148
  const nextBounds = transformReferenceBounds(baseline.referenceBounds, authoredLocalDelta);
3787
4149
  const offsetX = nextBounds.left + (resolveOrigin(baseline.frame.originX) + .5) * nextBounds.width;
@@ -3805,7 +4167,7 @@ function resolveBakedAuthoredGeometryTransform(baseline, target) {
3805
4167
  * 新几何后把真实 bounds 交回这里,保持 frame world matrix 与目标一致。
3806
4168
  */
3807
4169
  function resolveAuthoredGeometryFramePatch(baseline, resolution, authoredBounds) {
3808
- if (isIdentityMatrix(resolution.authoredLocalDelta)) return resolution.framePatch;
4170
+ if (resolution.authoredLocalDelta.isIdentity) return resolution.framePatch;
3809
4171
  const approximateBounds = transformReferenceBounds(baseline.referenceBounds, resolution.authoredLocalDelta);
3810
4172
  return {
3811
4173
  ...resolution.framePatch,
@@ -3845,7 +4207,7 @@ function resolveTargetParentWorldMatrix(baseline, intent) {
3845
4207
  function targetsFrozenReference(baseline, intent) {
3846
4208
  const delta = intent.worldDelta;
3847
4209
  const targetParentWorldMatrix = resolveTargetParentWorldMatrix(baseline, intent);
3848
- return isIdentityMatrix(delta) && sameMatrix(baseline.startParentWorldMatrix, targetParentWorldMatrix);
4210
+ return delta.isIdentity && sameMatrix(baseline.startParentWorldMatrix, targetParentWorldMatrix);
3849
4211
  }
3850
4212
  /** 从已持有的最终 world pose 纯计算 frame/authored delta。 */
3851
4213
  function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwnedGeometry, unwrappedRotationDelta, bakeGeometry = false) {
@@ -3855,8 +4217,8 @@ function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwned
3855
4217
  }
3856
4218
  const targetDecomposition = qrDecompose(target.parentInverseMatrix.multiply(target.worldMatrix));
3857
4219
  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);
4220
+ const authoredScaleX = preserveOwnedGeometry ? 1 : resolveAuthoredScale(targetDecomposition.scaleX, baseline.frame.scaleX);
4221
+ const authoredScaleY = preserveOwnedGeometry ? 1 : resolveAuthoredScale(targetDecomposition.scaleY, baseline.frame.scaleY);
3860
4222
  const nextScaleX = preserveOwnedGeometry ? targetDecomposition.scaleX : baseline.frame.scaleX === 0 ? targetDecomposition.scaleX : Math.sign(targetDecomposition.scaleX) * Math.abs(baseline.frame.scaleX);
3861
4223
  const nextScaleY = preserveOwnedGeometry ? targetDecomposition.scaleY : baseline.frame.scaleY === 0 ? targetDecomposition.scaleY : Math.sign(targetDecomposition.scaleY) * Math.abs(baseline.frame.scaleY);
3862
4224
  const nextBoundsLeft = baseline.referenceBounds.left * authoredScaleX;
@@ -3868,7 +4230,7 @@ function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwned
3868
4230
  const offsetY = nextBoundsTop + (resolveOrigin(baseline.frame.originY) + .5) * nextBoundsHeight;
3869
4231
  const centerX = nextBoundsLeft + nextBoundsWidth / 2;
3870
4232
  const centerY = nextBoundsTop + nextBoundsHeight / 2;
3871
- const pose = new DOMMatrix().rotate(0, 0, targetAngle).skewX(targetDecomposition.skewX).scale(nextScaleX, nextScaleY);
4233
+ const pose = new Matrix2D().rotateSelf(targetAngle).skewXSelf(targetDecomposition.skewX).scaleSelf(nextScaleX, nextScaleY);
3872
4234
  const relativeCenterX = centerX - offsetX;
3873
4235
  const relativeCenterY = centerY - offsetY;
3874
4236
  const posedCenterX = offsetX + pose.a * relativeCenterX + pose.c * relativeCenterY;
@@ -3887,7 +4249,7 @@ function resolveReferenceTransformTargetWithMode(baseline, target, preserveOwned
3887
4249
  height: baseline.frame.height * authoredScaleY
3888
4250
  } : {}
3889
4251
  },
3890
- authoredLocalDelta: baseline.writeMode === "authored-geometry" && !preserveOwnedGeometry ? new DOMMatrix().scale(authoredScaleX, authoredScaleY) : IDENTITY_REFERENCE_TRANSFORM
4252
+ authoredLocalDelta: baseline.writeMode === "authored-geometry" && !preserveOwnedGeometry ? new Matrix2D().scaleSelf(authoredScaleX, authoredScaleY) : IDENTITY_REFERENCE_TRANSFORM
3891
4253
  };
3892
4254
  }
3893
4255
  /**
@@ -4178,10 +4540,15 @@ var Shape = class extends Element {
4178
4540
  getConnectionPortPosition(edge, ratio, edgePosition) {
4179
4541
  return (edgePosition ?? this.getEdgePosition(edge, ratio)).pos;
4180
4542
  }
4181
- /** Replay the committed line/cubic snapshot into the current Canvas path. */
4543
+ /** Replay committed geometry without expanding ordinary rectangle subpaths. */
4182
4544
  buildResolvedPath(ctx) {
4183
4545
  const snapshot = this.transform.getGeometrySnapshot();
4184
4546
  ctx.beginPath();
4547
+ const rectangle = geometrySnapshotRectangle(snapshot);
4548
+ if (rectangle) {
4549
+ ctx.rect(rectangle.left, rectangle.top, rectangle.width, rectangle.height);
4550
+ return;
4551
+ }
4185
4552
  for (const subpath of snapshot.subpaths) {
4186
4553
  const first = subpath.vertices[0];
4187
4554
  if (!first) continue;
@@ -4222,6 +4589,16 @@ var Shape = class extends Element {
4222
4589
  buildBorderPath(ctx) {
4223
4590
  this.buildPath(ctx);
4224
4591
  }
4592
+ /**
4593
+ * canonical geometry 是普通矩形时,向当前 path 追加向内偏移 `inset` 的等距矩形。
4594
+ * 直边内缩描边与轮廓裁剪逐像素一致;其他几何返回 `false`,由调用方使用轮廓裁剪。
4595
+ */
4596
+ traceInsetRectangle(ctx, inset) {
4597
+ const rectangle = geometrySnapshotRectangle(this.transform.getGeometrySnapshot());
4598
+ if (!rectangle || rectangle.width < inset * 2 || rectangle.height < inset * 2) return false;
4599
+ ctx.rect(rectangle.left + inset, rectangle.top + inset, rectangle.width - inset * 2, rectangle.height - inset * 2);
4600
+ return true;
4601
+ }
4225
4602
  /** 使用 Shape 的实际路径裁剪 children。 */
4226
4603
  applyChildClip(ctx) {
4227
4604
  this.buildPath(ctx);
@@ -4252,10 +4629,20 @@ var Shape = class extends Element {
4252
4629
  if (!borderColor || !this.borderWidth) return;
4253
4630
  if (isGradient(borderColor)) ctx.strokeStyle = createCanvasGradient(ctx, borderColor, this.width ?? 0, this.height ?? 0);
4254
4631
  else ctx.strokeStyle = borderColor;
4632
+ const inside = this.borderPosition === "inside";
4633
+ if (inside) {
4634
+ ctx.beginPath();
4635
+ if (this.traceInsetRectangle(ctx, this.borderWidth / 2)) {
4636
+ ctx.lineJoin = "miter";
4637
+ ctx.lineWidth = this.borderWidth;
4638
+ ctx.stroke();
4639
+ return;
4640
+ }
4641
+ }
4255
4642
  ctx.save();
4256
4643
  try {
4257
4644
  this.buildPath(ctx);
4258
- if (this.borderPosition === "inside") ctx.clip(this.fillRule);
4645
+ if (inside) ctx.clip(this.fillRule);
4259
4646
  else {
4260
4647
  const bounds = this.transform.getLayoutReferenceBoundsView();
4261
4648
  const outset = this.getBorderOutset();
@@ -4282,17 +4669,34 @@ var Shape = class extends Element {
4282
4669
  ctx.shadowOffsetX = 0;
4283
4670
  ctx.shadowOffsetY = 0;
4284
4671
  }
4672
+ /** 在轮廓内侧绘制 `1 / scale` 宽的 hover 轮廓。 */
4285
4673
  paintHover(ctx, scale) {
4286
4674
  ctx.save();
4287
4675
  this.applyPaintTransform(ctx);
4288
- this.buildPath(ctx);
4289
- ctx.clip(this.fillRule);
4290
- this.buildPath(ctx);
4291
4676
  ctx.strokeStyle = this.activeRoot?.skin.selection ?? SKIN_DEFAULTS.selection;
4292
- ctx.lineWidth = 2 / scale;
4677
+ ctx.beginPath();
4678
+ if (this.traceInsetRectangle(ctx, .5 / scale)) {
4679
+ ctx.lineJoin = "miter";
4680
+ ctx.lineWidth = 1 / scale;
4681
+ } else {
4682
+ this.buildPath(ctx);
4683
+ ctx.clip(this.fillRule);
4684
+ ctx.lineWidth = 2 / scale;
4685
+ }
4293
4686
  ctx.stroke();
4294
4687
  ctx.restore();
4295
4688
  }
4689
+ /**
4690
+ * @internal 普通矩形几何且 world 矩阵保持长度时,把与 `paintHover()` 相同的内侧轮廓追加到
4691
+ * 当前 path;调用方随后在 Viewport 变换下以 `1 / scale` 线宽统一描边。
4692
+ * 覆写 `paintHover()` 的子类同时覆写本方法,返回 `false` 或追加自身的等价轮廓。
4693
+ */
4694
+ traceHoverOutline(ctx, scale) {
4695
+ const { a, b, c, d } = this.transform.getWorldMatrixView();
4696
+ 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;
4697
+ this.applyPaintTransform(ctx);
4698
+ return this.traceInsetRectangle(ctx, .5 / scale);
4699
+ }
4296
4700
  };
4297
4701
  //#endregion
4298
4702
  //#region packages/core/src/root/hit-test.ts
@@ -4396,7 +4800,7 @@ function* iteratePointElements(root, point, options = {}) {
4396
4800
  for (let index = root.layers.length - 1; index >= 0; index--) {
4397
4801
  const layer = root.layers[index];
4398
4802
  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;
4803
+ if (!element.isActive || element.isUnmounted || element.activeRoot !== root || element.layer !== layer) continue;
4400
4804
  if (options.exclude?.has(element.key)) continue;
4401
4805
  if (scope && !isStrictDescendant(element, scope)) continue;
4402
4806
  if (!isPointerTargetWithinAncestorClips(root, element, point)) continue;
@@ -4496,7 +4900,7 @@ function queryAreaElements(root, area, options = {}) {
4496
4900
  }
4497
4901
  //#endregion
4498
4902
  //#region packages/core/src/root/input-controller.ts
4499
- /** 同一 Document 当前拥有空格键盘输入的 Root。 */
4903
+ /** 同一 Document 最近接收焦点或指针的 Root。 */
4500
4904
  var activeInputByDocument = /* @__PURE__ */ new WeakMap();
4501
4905
  /** 判断键盘事件目标是否应保留浏览器原生空格输入。 */
4502
4906
  function isFormControlTarget(target) {
@@ -4540,6 +4944,13 @@ var RootInputController = class {
4540
4944
  get isPointerInside() {
4541
4945
  return this.pointerInside;
4542
4946
  }
4947
+ /** 当前 DOM 焦点决定键盘归属;无元素焦点时采用最近的 Root 指针归属。 */
4948
+ get isKeyboardOwner() {
4949
+ const document = this.ownerDocument;
4950
+ const focused = this.root.container.getRootNode().activeElement ?? document.activeElement;
4951
+ if (focused && focused !== document.body && focused !== document.documentElement) return this.root.container.contains(focused);
4952
+ return activeInputByDocument.get(document) === this;
4953
+ }
4543
4954
  /** @internal 安装当前 Root 的键盘、指针、滚轮和焦点监听。 */
4544
4955
  activate() {
4545
4956
  if (this.abortController) return;
@@ -4696,7 +5107,7 @@ var RootInputController = class {
4696
5107
  }
4697
5108
  /** 进入空格平移模式,并清除普通 hover。 */
4698
5109
  onKeyDown = (event) => {
4699
- if (activeInputByDocument.get(this.ownerDocument) !== this || event.code !== "Space" || event.repeat || isFormControlTarget(event.target)) return;
5110
+ if (!this.isKeyboardOwner || event.code !== "Space" || event.repeat || isFormControlTarget(event.target)) return;
4700
5111
  event.preventDefault();
4701
5112
  if (!isNull(this.activePointerId)) return;
4702
5113
  this.isSpacePressed = true;
@@ -5323,7 +5734,7 @@ var RootFrameRuntime = class {
5323
5734
  /** 安装或移除 Root 生命周期内唯一的无调度 participant。 */
5324
5735
  setParticipant(participant) {
5325
5736
  this.participant = participant;
5326
- if (participant?.hasPendingWork() || participant?.hasPendingSpatialWork?.() || participant?.hasPendingOverlayWork?.() || participant?.hasPendingCompletionWork?.()) this.requestFrame();
5737
+ if (this.needsAnotherFrame()) this.requestFrame();
5327
5738
  }
5328
5739
  /** 判断 Layer 是否仍由当前活动 Root 拥有。 */
5329
5740
  ownsLayer(layer) {
@@ -5331,7 +5742,7 @@ var RootFrameRuntime = class {
5331
5742
  }
5332
5743
  /** 激活后为已存在的 animation、Layer 或 participant 工作请求帧。 */
5333
5744
  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();
5745
+ if (this.needsAnotherFrame()) this.requestFrame();
5335
5746
  }
5336
5747
  /** Layer 离开 Root 时丢弃其尚未消费的帧登记。 */
5337
5748
  forgetLayer(layer) {
@@ -5399,8 +5810,8 @@ var RootFrameRuntime = class {
5399
5810
  const scheduleAfterCompletionError = this.completionFollowUpFrameRequested;
5400
5811
  this.completionFollowUpFrameRequested = false;
5401
5812
  if (frameError) this.rejectNextTick(frameError);
5813
+ else if (!this.hasPendingSynchronousWork()) this.resolveNextTick();
5402
5814
  if ((!frameError || scheduleAfterCompletionError) && this.needsAnotherFrame()) this.requestFrame();
5403
- else if (!frameError) this.resolveNextTick();
5404
5815
  }
5405
5816
  });
5406
5817
  if (this.animationFrameScheduled) this.animationFrameId = id;
@@ -5435,7 +5846,7 @@ var RootFrameRuntime = class {
5435
5846
  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
5847
  }
5437
5848
  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));
5849
+ return this.hasPendingSynchronousWork() || this.root.isActive && !this.root.isUnmounted && hasRunningTweens(this.animationGroup);
5439
5850
  }
5440
5851
  runFrame(time) {
5441
5852
  if (time !== void 0) this.animationGroup.update(time);
@@ -5494,11 +5905,13 @@ var RootFrameRuntime = class {
5494
5905
  return this.participant?.resolveCursor?.(point, contentCursor) ?? contentCursor;
5495
5906
  }
5496
5907
  consumeDirtyTransforms() {
5908
+ if (this.pendingDirtyTransforms.size === 0) return;
5497
5909
  const current = this.pendingDirtyTransforms;
5498
5910
  this.pendingDirtyTransforms = /* @__PURE__ */ new Set();
5499
5911
  for (const transform of current) transform.clearDirtyDescendantState(this.root);
5500
5912
  }
5501
5913
  flushLayouts() {
5914
+ if (this.pendingLayouts.size === 0) return;
5502
5915
  const current = this.pendingLayouts;
5503
5916
  this.pendingLayouts = /* @__PURE__ */ new Set();
5504
5917
  const affected = this.root.sceneRegistry.hasSceneChangeObservers ? [] : void 0;
@@ -5508,12 +5921,6 @@ var RootFrameRuntime = class {
5508
5921
  }
5509
5922
  if (affected && affected.length > 0) this.root.sceneRegistry.notifySceneChange(void 0, affected);
5510
5923
  }
5511
- takePendingLayers() {
5512
- const pending = /* @__PURE__ */ new Set();
5513
- for (const layer of this.pendingLayers) if (this.ownsLayer(layer)) pending.add(layer);
5514
- this.pendingLayers.clear();
5515
- return pending;
5516
- }
5517
5924
  dirtyOwnerKeys(lastRound) {
5518
5925
  const keys = new Set(this.participant?.getDirtyOwnerKeys?.() ?? []);
5519
5926
  for (const owner of this.pendingLayouts) keys.add(owner.key);
@@ -5526,13 +5933,15 @@ var RootFrameRuntime = class {
5526
5933
  try {
5527
5934
  const frameWorkByLayer = /* @__PURE__ */ new Map();
5528
5935
  let rounds = 0;
5529
- let lastRound = [];
5936
+ let lastRound = frameWorkByLayer;
5530
5937
  while (this.pendingLayers.size > 0 || this.pendingLayouts.size > 0 || this.participant?.hasPendingWork() === true) {
5531
- if (++rounds > MAX_STABILIZATION_ROUNDS) throw new FrameStabilizationError(this.dirtyOwnerKeys(lastRound));
5938
+ if (++rounds > MAX_STABILIZATION_ROUNDS) throw new FrameStabilizationError(this.dirtyOwnerKeys(lastRound.values()));
5532
5939
  this.participant?.flushMutationPhase();
5533
5940
  this.flushLayouts();
5534
5941
  const roundWorkByLayer = /* @__PURE__ */ new Map();
5535
- for (const layer of this.takePendingLayers()) {
5942
+ const pendingLayers = this.pendingLayers;
5943
+ this.pendingLayers = /* @__PURE__ */ new Set();
5944
+ for (const layer of pendingLayers) {
5536
5945
  if (!this.ownsLayer(layer)) continue;
5537
5946
  const work = layer.takeFrameWork();
5538
5947
  if (!work) continue;
@@ -5541,7 +5950,7 @@ var RootFrameRuntime = class {
5541
5950
  if (accumulated) mergeFrameWork(accumulated, work);
5542
5951
  else frameWorkByLayer.set(layer, work);
5543
5952
  }
5544
- lastRound = [...roundWorkByLayer.values()];
5953
+ lastRound = roundWorkByLayer;
5545
5954
  this.consumeDirtyTransforms();
5546
5955
  for (const [layer, work] of roundWorkByLayer) if (this.ownsLayer(layer)) layer.flushGeometry(work);
5547
5956
  }
@@ -5583,7 +5992,7 @@ var RootFrameRuntime = class {
5583
5992
  this.nextTickReject = null;
5584
5993
  reject?.(error);
5585
5994
  }
5586
- /** 返回在当前已安排帧完成后结算的共享 Promise。 */
5995
+ /** 返回在当前帧及其同步新增工作稳定后结算的共享 Promise;持续动画不阻塞。 */
5587
5996
  nextTick() {
5588
5997
  if (!this.root.isActive || !this.animationFrameScheduled && 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) return Promise.resolve();
5589
5998
  if (!this.nextTickPromise) this.nextTickPromise = new Promise((resolve, reject) => {
@@ -5704,173 +6113,6 @@ var SceneRegistry = class {
5704
6113
  }
5705
6114
  };
5706
6115
  //#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
- //#region packages/core/src/mutation/change-batch.ts
5800
- /** @internal 合并 raw owner effects;单个 patch 直接借用,仅合并同 owner 字段时分配。 */
5801
- function mergeOwnerPropertyChanges(ownerEffects) {
5802
- const slots = /* @__PURE__ */ new Map();
5803
- let mergedOwners = null;
5804
- for (const { owner, patch } of ownerEffects) {
5805
- const current = slots.get(owner);
5806
- if (!current) {
5807
- slots.set(owner, patch);
5808
- continue;
5809
- }
5810
- let finalPatch;
5811
- if (mergedOwners?.has(owner)) finalPatch = current;
5812
- else {
5813
- finalPatch = {};
5814
- for (const key of Object.keys(current)) finalPatch[key] = current[key];
5815
- slots.set(owner, finalPatch);
5816
- (mergedOwners ??= /* @__PURE__ */ new Set()).add(owner);
5817
- }
5818
- for (const key of Object.keys(patch)) finalPatch[key] = patch[key];
5819
- }
5820
- return slots;
5821
- }
5822
- /**
5823
- * 同步应用一份 trusted change batch。
5824
- *
5825
- * owner effects 先按对象身份合并最终 patch;所有 fields/raw links 安装完成后才运行
5826
- * History、lifecycle、hooks、dirty 和一次 scene delivery。本函数不提供 rollback、
5827
- * retry、receipt 或 rejected 结果。返回本批次是否实际安装属性或结构变化。
5828
- */
5829
- function applyChangeBatch(root, ownerEffects, structureEffects = [], history) {
5830
- if (ownerEffects.length === 0 && structureEffects.length === 0) return false;
5831
- const slots = mergeOwnerPropertyChanges(ownerEffects);
5832
- const properties = [];
5833
- for (const [owner, patch] of slots) {
5834
- const commit = owner.preparePropertyCommit(patch);
5835
- if (commit) properties.push({
5836
- owner,
5837
- commit
5838
- });
5839
- }
5840
- const structureBatch = prepareStructureBatch(structureEffects);
5841
- const structure = structureBatch.changes;
5842
- if (properties.length === 0 && structure.length === 0) return false;
5843
- const placements = history ? preparePlacementChanges(structure) : null;
5844
- for (const { owner, commit } of properties) owner.installPropertyCommit(commit);
5845
- const lifecycleRoots = installStructureLinks(structureBatch);
5846
- if (history) {
5847
- for (const { owner, commit } of properties) for (const field of commit.update.fields) {
5848
- if (!field.sourceChanged) continue;
5849
- history.recordPropertyChange(owner, field.key, field.beforeSource);
5850
- }
5851
- for (const placement of placements) history.recordPlacementChange(placement.node, placement.beforeOwner, placement.beforeIndex);
5852
- }
5853
- syncStructureLifecycles(lifecycleRoots);
5854
- for (const { owner, commit } of properties) owner.syncPropertyCommitEvents(commit);
5855
- for (const { owner, commit } of properties) owner.runPropertyCommitHook(commit);
5856
- for (const { owner } of structure) owner.runBatchStructureHook();
5857
- for (const { owner, commit } of properties) owner.notifyPortsCommit(commit);
5858
- let layerOrderChanged = false;
5859
- let hoverChanged = false;
5860
- for (const { owner, commit } of properties) {
5861
- owner.publishPropertyCommit(commit, false, false);
5862
- if (commit.impact & ChangeImpact.LayerOrder) layerOrderChanged = true;
5863
- else if (commit.impact & ChangeImpact.Hover) hoverChanged = true;
5864
- }
5865
- for (const { owner } of structure) owner.publishBatchStructureDirty();
5866
- if (structure.length) root.commitBatchStructureChanges(structure, layerOrderChanged);
5867
- else if (layerOrderChanged) root.commitLayerOrderChange();
5868
- else if (hoverChanged) root.scheduleHoverRefresh();
5869
- if (root.sceneRegistry.hasSceneChangeObservers) root.sceneRegistry.notifySceneChange(void 0, [...properties.map(({ owner }) => owner), ...structure.flatMap(({ owner, changed }) => [owner, ...changed])]);
5870
- for (const { owner, commit } of properties) owner.dispatchPortsChange(commit);
5871
- return true;
5872
- }
5873
- //#endregion
5874
6116
  //#region packages/core/src/root/index.ts
5875
6117
  /** 场景树根节点,统一管理 Layer、Viewport、输入、查询和帧提交。 */
5876
6118
  var Root = class extends Node {
@@ -6028,54 +6270,36 @@ var Root = class extends Node {
6028
6270
  }
6029
6271
  /** @internal 在 children 事务提交后刷新 Layer 顺序、布局、绘制和 hover。 */
6030
6272
  commitStructureChange(owner, changed) {
6031
- this.commitStructureChanges([{
6273
+ this.commitBatchStructureChanges([{
6032
6274
  owner,
6033
6275
  changed
6034
6276
  }]);
6035
6277
  if (this.sceneRegistry.hasSceneChangeObservers) this.sceneRegistry.notifySceneChange(void 0, [owner, ...changed]);
6036
6278
  }
6037
- /** @internal trusted batch 只消费受影响 owners/subgraph,并合并 Layer 工作。 */
6279
+ /**
6280
+ * @internal 只消费受影响 owners/subgraph,并合并 Layer 工作。离开的节点已在停用时
6281
+ * 登记旧区域;仍在 owner 下的进入或移动节点只重绘自身子树。绘制顺序由安装期的 sibling
6282
+ * 标签直接给出,不需要重排整层。
6283
+ */
6038
6284
  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
6285
  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);
6286
+ for (const { owner, changed } of changes) for (const node of changed) {
6287
+ if (node.isLayerNode()) {
6288
+ layerOrderChanged = true;
6289
+ continue;
6056
6290
  }
6057
- for (const node of changed) collect(node);
6058
- }
6059
- for (const layer of affectedLayers) {
6060
- layer.commitStructureOrder();
6061
- layer.invalidateAll();
6291
+ if (!(node instanceof Element) || node.parent !== owner || !node.isActive || !this.ownsLayer(node.layer)) continue;
6292
+ if (node.transform.needsCommit) node.layer.invalidateLayout(node);
6293
+ else node.layer.invalidatePaint(node);
6062
6294
  }
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
6295
  if (layerOrderChanged) this.sortLayers();
6065
6296
  this.scheduleHoverRefresh();
6066
6297
  }
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
- };
6298
+ /**
6299
+ * @internal 按跨 Layer 的已提交绘制顺序比较两个活动元素;小于 0 表示 `left` 先绘制(在下方)。
6300
+ */
6301
+ comparePaintOrder(left, right) {
6302
+ return this.registeredLayers.indexOf(left.layer) - this.registeredLayers.indexOf(right.layer) || compareTreeOrder(left, right);
6079
6303
  }
6080
6304
  /** @internal Layer zIndex 变化后重排 Canvas 并刷新 hover。 */
6081
6305
  commitLayerOrderChange() {
@@ -6105,7 +6329,7 @@ var Root = class extends Node {
6105
6329
  }
6106
6330
  /**
6107
6331
  * 等待当前 frame-final completion 及其监听器同步新增的帧工作。
6108
- * 监听器抛错时以同一个 error reject;没有待处理帧时立即完成。
6332
+ * 持续动画不延迟本次完成。监听器抛错时以同一个 error reject;没有待处理帧时立即完成。
6109
6333
  */
6110
6334
  nextTick() {
6111
6335
  return this.frameRuntime.nextTick();
@@ -6413,6 +6637,8 @@ var Layer = class Layer extends Element {
6413
6637
  static FULL_REPAINT_RATIO = .5;
6414
6638
  /** 候选命中达到空间项此比例时直接完整重绘。 */
6415
6639
  static CANDIDATE_FULL_REPAINT_RATIO = .9;
6640
+ /** 完整重绘的 viewport 候选达到空间项此比例时改为逐 child 判断可见性。 */
6641
+ static VIEWPORT_CANDIDATE_RATIO = .15;
6416
6642
  /** 空间项变更超过现有项此比例时重建整个 RBush。 */
6417
6643
  static RBUSH_REBUILD_RATIO = .3;
6418
6644
  /** 将零散 damage 合并为有限数量矩形的网格。 */
@@ -6444,7 +6670,6 @@ var Layer = class Layer extends Element {
6444
6670
  root.container.appendChild(this.canvasEl);
6445
6671
  if (this.debugSurface) root.container.appendChild(this.debugSurface.canvas);
6446
6672
  root.registerLayer(this);
6447
- this.commitStructureOrder();
6448
6673
  this.pendingWork.dirtyNodes.add(this);
6449
6674
  this.invalidateAll();
6450
6675
  }
@@ -6564,9 +6789,9 @@ var Layer = class Layer extends Element {
6564
6789
  * @param order `paint` 按前到后排序,`none` 保留空间索引返回顺序。
6565
6790
  */
6566
6791
  queryCommittedElements(area, order = "paint") {
6567
- const elements = this.searchCommittedElements(area);
6792
+ const elements = this.searchCommittedItems(area).map(({ element }) => element);
6568
6793
  if (order === "none") return elements;
6569
- return elements.sort((a, b) => (this.root.getPaintOrder(b) ?? -1) - (this.root.getPaintOrder(a) ?? -1));
6794
+ return elements.sort((a, b) => compareTreeOrder(b, a));
6570
6795
  }
6571
6796
  /** @internal Copy the last visual bounds committed to this Layer index. */
6572
6797
  getCommittedVisualBounds(node) {
@@ -6582,13 +6807,9 @@ var Layer = class Layer extends Element {
6582
6807
  */
6583
6808
  *iterateCommittedElements(area) {
6584
6809
  const items = this.searchCommittedItems(area);
6585
- items.sort((a, b) => (this.root.getPaintOrder(b.element) ?? -1) - (this.root.getPaintOrder(a.element) ?? -1));
6810
+ items.sort((a, b) => compareTreeOrder(b.element, a.element));
6586
6811
  for (const item of items) yield item.element;
6587
6812
  }
6588
- /** 直接查询 RBush 中与 world AABB 相交的已提交元素。 */
6589
- searchCommittedElements(area) {
6590
- return this.searchCommittedItems(area).map(({ element }) => element);
6591
- }
6592
6813
  /** 直接查询 RBush 中与 world AABB 相交的已提交空间项。 */
6593
6814
  searchCommittedItems(area) {
6594
6815
  const x = area.left;
@@ -6727,10 +6948,13 @@ var Layer = class Layer extends Element {
6727
6948
  for (const child of node.children) stack.push(child);
6728
6949
  }
6729
6950
  }
6730
- /** 清空并重新绘制整个 Layer Canvas。 */
6731
- fullRepaint() {
6951
+ /**
6952
+ * 清空并重新绘制整个 Layer Canvas。dirty-rect Layer 的元素只绘制在 visual bounds 内,
6953
+ * 因此直接用 viewport 的 RBush 候选组织绘制树;候选密度达到阈值时逐 child 判断可见性。
6954
+ */
6955
+ fullRepaint(dirtyPaintChildren = this.enableDirtyRect ? this.buildDirtyPaintChildren([this.root.viewport.getWorldRectView()], Layer.VIEWPORT_CANDIDATE_RATIO) : null) {
6732
6956
  const previousDirtyPaintChildren = this.dirtyPaintChildren;
6733
- this.dirtyPaintChildren = null;
6957
+ this.dirtyPaintChildren = dirtyPaintChildren;
6734
6958
  try {
6735
6959
  this.clear();
6736
6960
  this.paint(this.ctx);
@@ -6738,40 +6962,37 @@ var Layer = class Layer extends Element {
6738
6962
  this.dirtyPaintChildren = previousDirtyPaintChildren;
6739
6963
  }
6740
6964
  }
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();
6965
+ /** 从最终 damage 的 RBush hits 构建一次绘制期有序邻接表;达到候选密度时返回 `null`。 */
6966
+ buildDirtyPaintChildren(worldRects, fullRepaintRatio = Layer.CANDIDATE_FULL_REPAINT_RATIO) {
6967
+ const spatialCount = this.spatialItems.size;
6968
+ const limit = spatialCount > 0 ? spatialCount * fullRepaintRatio : Infinity;
6758
6969
  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);
6970
+ const search = (rect) => this.searchCommittedItems({
6971
+ left: rect.left - queryPad,
6972
+ top: rect.top - queryPad,
6973
+ width: rect.width + queryPad * 2,
6974
+ height: rect.height + queryPad * 2
6975
+ });
6976
+ let hits;
6977
+ let hitCount;
6978
+ if (worldRects.length === 1) {
6979
+ const items = search(worldRects[0]);
6980
+ hitCount = items.length;
6981
+ if (hitCount >= limit) return null;
6982
+ hits = items;
6983
+ } else {
6984
+ const unique = /* @__PURE__ */ new Set();
6985
+ for (const rect of worldRects) {
6986
+ for (const hit of search(rect)) unique.add(hit);
6987
+ if (unique.size >= limit) return null;
6988
+ }
6989
+ hitCount = unique.size;
6990
+ hits = unique;
6767
6991
  }
6768
- const spatialCount = this.spatialItems.size;
6769
- if (spatialCount > 0 && (hits.size === spatialCount || hits.size >= spatialCount * Layer.CANDIDATE_FULL_REPAINT_RATIO)) return null;
6770
6992
  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);
6993
+ if (hitCount === 0) return childrenByParent;
6773
6994
  const included = /* @__PURE__ */ new Set();
6774
- for (const hit of orderedHits) {
6995
+ for (const { element: hit } of hits) {
6775
6996
  let child = hit;
6776
6997
  while (child !== this) {
6777
6998
  if (included.has(child)) break;
@@ -6783,6 +7004,7 @@ var Layer = class Layer extends Element {
6783
7004
  child = parent;
6784
7005
  }
6785
7006
  }
7007
+ for (const children of childrenByParent.values()) if (children.length > 1) children.sort((left, right) => left.siblingOrder - right.siblingOrder);
6786
7008
  return childrenByParent;
6787
7009
  }
6788
7010
  /** 裁剪到 damage 矩形,并消费已经完成组织的候选绘制树。 */
@@ -6887,40 +7109,37 @@ var Layer = class Layer extends Element {
6887
7109
  if (this.enableDirtyRect && hasDirty) {
6888
7110
  const { scale, x, y } = this.root.viewport;
6889
7111
  const worldPad = 2 / scale;
6890
- const worldRects = [...damageRects];
6891
- if (dirtyNodes.size > 0 || paintDirtyNodes.size > 0) {
6892
- const dirtyBoundsMemo = dirtyNodes.size + paintDirtyNodes.size > 1 ? /* @__PURE__ */ new Map() : void 0;
6893
- const addPadded = (node) => {
6894
- if (!node.isActive || node.layer !== this) return;
6895
- const r = dirtyBoundsMemo ? node.transform.getDirtyRect(dirtyBoundsMemo) : node.transform.getDirtyRect();
6896
- if (!r || r.width <= 0 || r.height <= 0) return;
6897
- worldRects.push({
6898
- left: r.left - worldPad,
6899
- top: r.top - worldPad,
6900
- width: r.width + worldPad * 2,
6901
- height: r.height + worldPad * 2
6902
- });
6903
- };
6904
- for (const node of dirtyNodes) addPadded(node);
6905
- for (const node of paintDirtyNodes) addPadded(node);
6906
- }
6907
7112
  const visibleWorldW = paintOwner.width / scale;
6908
7113
  const visibleWorldH = paintOwner.height / scale;
6909
7114
  const visibleArea = visibleWorldW * visibleWorldH;
6910
7115
  const viewLeft = -x / scale;
6911
7116
  const viewTop = -y / scale;
6912
7117
  const visibleWorldRects = [];
6913
- for (const rect of worldRects) {
6914
- const left = Math.max(rect.left, viewLeft);
6915
- const top = Math.max(rect.top, viewTop);
6916
- const right = Math.min(rect.left + rect.width, viewLeft + visibleWorldW);
6917
- const bottom = Math.min(rect.top + rect.height, viewTop + visibleWorldH);
7118
+ const addVisible = (rect, pad = 0) => {
7119
+ const rectLeft = rect.left - pad;
7120
+ const rectTop = rect.top - pad;
7121
+ const left = Math.max(rectLeft, viewLeft);
7122
+ const top = Math.max(rectTop, viewTop);
7123
+ const right = Math.min(rectLeft + (rect.width + pad * 2), viewLeft + visibleWorldW);
7124
+ const bottom = Math.min(rectTop + (rect.height + pad * 2), viewTop + visibleWorldH);
6918
7125
  if (right > left && bottom > top) visibleWorldRects.push({
6919
7126
  left,
6920
7127
  top,
6921
7128
  width: right - left,
6922
7129
  height: bottom - top
6923
7130
  });
7131
+ };
7132
+ for (const rect of damageRects) addVisible(rect);
7133
+ if (dirtyNodes.size > 0 || paintDirtyNodes.size > 0) {
7134
+ const dirtyBoundsMemo = dirtyNodes.size + paintDirtyNodes.size > 1 ? /* @__PURE__ */ new Map() : void 0;
7135
+ const addPadded = (node) => {
7136
+ if (!node.isActive || node.layer !== this) return;
7137
+ const r = dirtyBoundsMemo ? node.transform.getDirtyRect(dirtyBoundsMemo) : node.transform.getDirtyRect();
7138
+ if (!r || r.width <= 0 || r.height <= 0) return;
7139
+ addVisible(r, worldPad);
7140
+ };
7141
+ for (const node of dirtyNodes) addPadded(node);
7142
+ for (const node of paintDirtyNodes) addPadded(node);
6924
7143
  }
6925
7144
  const { rects: mergedWorldRects } = this.dirtyGrid.merge(visibleWorldRects, visibleArea, Layer.FULL_REPAINT_RATIO);
6926
7145
  if (!mergedWorldRects) {
@@ -6933,7 +7152,7 @@ var Layer = class Layer extends Element {
6933
7152
  } else {
6934
7153
  const dirtyPaintChildren = this.buildDirtyPaintChildren(mergedWorldRects);
6935
7154
  if (!dirtyPaintChildren) {
6936
- this.fullRepaint();
7155
+ this.fullRepaint(null);
6937
7156
  didFullRepaint = true;
6938
7157
  this.flashFullRepaint();
6939
7158
  } else {
@@ -6998,4 +7217,4 @@ var Layer = class Layer extends Element {
6998
7217
  }
6999
7218
  };
7000
7219
  //#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 };
7220
+ 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, getAuthoredPathLayoutBounds, getElementConnectionPort, getElementConnectionPortPoint, getElementConnectionPortPoints, isFormControlTarget, isReparentTransformIntent, mergeOwnerPropertyChanges, projectConnectionPortPoint, resolveAuthoredGeometryFramePatch, resolveAuthoredSubpath, resolveOrigin, resolveReferenceBoundsTranslation, resolveReferenceTransform, resolveReferenceTransformTarget, splitPathSegment };