@onekeyfe/react-native-native-list 6.7.0-17 → 6.7.0-18

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.
@@ -1609,6 +1609,7 @@ class NativeListView(
1609
1609
  structuralScrollInterrupted = false
1610
1610
  structuralFooterCompensatedHeightPx = null
1611
1611
  recyclerView.itemAnimator = null
1612
+ acceptRowIndex(next, previous)
1612
1613
  config = next
1613
1614
  pruneMeasuredRowExtents(next.items)
1614
1615
  updateContainerSlots()
@@ -1705,7 +1706,11 @@ class NativeListView(
1705
1706
  }
1706
1707
  }
1707
1708
 
1708
- private fun updatePrefixTailSnapshot(previous: NativeListConfig, next: NativeListConfig): Boolean {
1709
+ private fun updatePrefixTailSnapshot(
1710
+ previous: NativeListConfig,
1711
+ next: NativeListConfig,
1712
+ acceptIndex: Boolean = false,
1713
+ ): Boolean {
1709
1714
  val tail = structuralTail ?: return false
1710
1715
  if (structuralTailPreparing || structuralTailFinalizing ||
1711
1716
  structuralTailRowsInAdapterPx > 0 ||
@@ -1728,6 +1733,7 @@ class NativeListView(
1728
1733
  explicitTailRowSpacingPx(after, next.itemSpacing))
1729
1734
  return false
1730
1735
  }
1736
+ if (acceptIndex) acceptRowIndex(next, previous)
1731
1737
  config = next
1732
1738
  adapter.selectedKeys = next.selectedKeys
1733
1739
  adapter.submitList(next.items.take(tail.prefixCount)) {
@@ -2109,6 +2115,17 @@ class NativeListView(
2109
2115
  private var lastMarketPaginationAnchorLogAtMs = 0L
2110
2116
  private var disposed = false
2111
2117
  private var resourcesDisposed = false
2118
+ private var acceptedKeyIndex: Map<String, Int>? = null
2119
+
2120
+ private fun acceptRowIndex(next: NativeListConfig, previous: NativeListConfig?) {
2121
+ if (previous != null && acceptedKeyIndex != null &&
2122
+ previous.generation == next.generation && previous.items.size == next.items.size &&
2123
+ previous.items.indices.all { index ->
2124
+ previous.items[index].key == next.items[index].key &&
2125
+ previous.items[index].type == next.items[index].type
2126
+ }) return
2127
+ acceptedKeyIndex = next.items.withIndex().associate { it.value.key to it.index }
2128
+ }
2112
2129
 
2113
2130
  init {
2114
2131
  orientation = VERTICAL
@@ -2469,7 +2486,9 @@ class NativeListView(
2469
2486
  if (structuralTail != null) {
2470
2487
  if (!disclosureGeometryInvalid && !animateStructure && oldKeys == nextKeys &&
2471
2488
  (Build.VERSION.SDK_INT < 26 || ValueAnimator.areAnimatorsEnabled()) &&
2472
- previous != null && updatePrefixTailSnapshot(previous, next)) return
2489
+ previous != null && updatePrefixTailSnapshot(previous, next, acceptIndex = true)) {
2490
+ return
2491
+ }
2473
2492
  heldTailEpoch = holdStructuralTailUntilListCommit()
2474
2493
  // Keep the accepted presentation until the full adapter list has committed.
2475
2494
  animateStructure = false
@@ -2522,6 +2541,7 @@ class NativeListView(
2522
2541
  previous.items[index].content != next.items[index].content
2523
2542
  }
2524
2543
  }.toSet()
2544
+ acceptRowIndex(next, previous)
2525
2545
  config = next
2526
2546
  if (heldTailEpoch == null) {
2527
2547
  disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
@@ -2580,6 +2600,7 @@ class NativeListView(
2580
2600
  layoutManager.getDecoratedTop(it) - recyclerView.paddingTop
2581
2601
  }
2582
2602
  } else null
2603
+ acceptRowIndex(next, previous)
2583
2604
  config = next
2584
2605
  if (heldTailEpoch == null) {
2585
2606
  disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
@@ -2914,20 +2935,22 @@ class NativeListView(
2914
2935
 
2915
2936
  fun applyPatches(patchesJson: String) {
2916
2937
  val current = config ?: return
2938
+ val indexByKey = acceptedKeyIndex ?: return
2917
2939
  val patches = try {
2918
2940
  JSONArray(patchesJson)
2919
2941
  } catch (_: Exception) {
2920
2942
  return
2921
2943
  }
2922
- val indexByKey = current.items.withIndex().associate { it.value.key to it.index }
2923
2944
  val pending = ArrayList<Pair<Int, JSONObject>>(patches.length())
2924
2945
  val seen = HashSet<String>()
2925
2946
  for (index in 0 until patches.length()) {
2926
2947
  val patch = patches.optJSONObject(index) ?: return
2927
2948
  val key = patch.optString("key")
2928
2949
  val itemIndex = indexByKey[key] ?: return
2950
+ val item = current.items.getOrNull(itemIndex) ?: return
2951
+ if (item.key != key) return
2929
2952
  if (!seen.add(key)) return
2930
- if (patch.optString("type") != current.items[itemIndex].type) return
2953
+ if (patch.optString("type") != item.type) return
2931
2954
  val changes = patch.optJSONObject("changes") ?: return
2932
2955
  pending.add(itemIndex to changes)
2933
2956
  }
@@ -3465,6 +3488,7 @@ class NativeListView(
3465
3488
  fun dispose() {
3466
3489
  if (disposed) return
3467
3490
  disposed = true
3491
+ acceptedKeyIndex = null
3468
3492
  if (structuralTail != null) discardStructuralTail()
3469
3493
  val cancelTag = R.id.onekey_native_scroll_coordinator_command_cancel_listener
3470
3494
  if (recyclerView.getTag(cancelTag) === coordinatorCommandCancelListener) recyclerView.setTag(cancelTag, null)
@@ -4501,6 +4525,7 @@ class NativeListView(
4501
4525
  if (from != RecyclerView.NO_POSITION && to != RecyclerView.NO_POSITION && from != to && reordered != null) {
4502
4526
  val moved = reordered.getOrNull(to)
4503
4527
  if (moved != null) {
4528
+ acceptedKeyIndex = reordered.withIndex().associate { it.value.key to it.index }
4504
4529
  config = config?.copy(items = reordered)
4505
4530
  val payload = JSONObject()
4506
4531
  .put("key", moved.key)
package/docs/SPEC.md CHANGED
@@ -418,6 +418,16 @@ section index titles retain their separate development-only
418
418
  no-surrounding-whitespace assertion.
419
419
  The 256-code-unit key limit is a development assertion, not a production limit.
420
420
 
421
+ Each iOS and Android host retains an index from accepted logical row keys to
422
+ row positions. An accepted complete snapshot reuses that index only when its
423
+ generation and ordered `(key, type)` sequence match the prior accepted
424
+ snapshot; otherwise it replaces the index. Reorder commits rebuild it and
425
+ disposal clears it. Patch batches reuse the index and never include retiring
426
+ presentation rows in it. They validate the whole batch against the current
427
+ accepted row models before changing config or presentation; invalid batches
428
+ leave both unchanged. iOS updates only changed accepted entries in its
429
+ presentation lookup after a valid patch, preserving any retiring rows.
430
+
421
431
  ### Validation environments and rejected input
422
432
 
423
433
  Development builds (`__DEV__ === true`) run the complete snapshot and patch
@@ -444,6 +454,24 @@ validators or Web behavior.
444
454
  An `undefined` value in an eligible field stays on the changed-row path only
445
455
  when that field was already `undefined`; clearing a present value uses the
446
456
  complete-snapshot path.
457
+
458
+ `planNativeListPatches(previous, next)` is an explicit, pure public helper for
459
+ callers that own two valid, immutable snapshots. It returns a readonly empty
460
+ batch for equal snapshots, value-only `identity` or `dataRow` row patches when
461
+ only eligible values change, and `undefined` when the caller must deliver a
462
+ complete snapshot. It never dispatches, accepts or validates an update, and
463
+ does not deep-copy, freeze or cache caller input. Returned patches may refer
464
+ to `next`'s immutable values; the caller retains baseline and commit ownership.
465
+ The component does not automatically invoke this planner for prop snapshots. Any
466
+ change outside `rows`, including generation, selection, layout, list style, empty state or
467
+ footer, requires a complete snapshot. Row keys, order and types must match.
468
+ `identity` may patch `subtitle`, `subtitleSegments` and `trailing`; `dataRow`
469
+ may patch non-asset columns and `trailing` while preserving the first asset
470
+ column. Changes to other row fields or to the presence of optional patch
471
+ fields require a complete snapshot. Comparison is by JSON value, ignores
472
+ object property order and properties whose value is `undefined`, and keeps
473
+ array order significant.
474
+
447
475
  Rejection emits a diagnostic without including row keys, text or image URLs.
448
476
  Explicit calls to the exported validation functions still throw on rejected
449
477
  input, so development tooling can inspect the full contract failure. Rejection
@@ -1040,7 +1068,7 @@ data adapter; adapter binding indices stay local while layout-manager positions
1040
1068
  are explicitly translated. Slots span all grid columns, do not select/reorder,
1041
1069
  and do not emit row actions, visible-row indices, or image-prefetch work.
1042
1070
 
1043
- ### Native disclosure slots and settlement (source implemented; limited runtime verification)
1071
+ ### Disclosure slots and settlement (source implemented; limited runtime verification)
1044
1072
 
1045
1073
  Native callers may opt in with `snapshot.disclosure: { expanded: boolean,
1046
1074
  expandedTrailingInset?: number }`, `listExpandedContent`, and
@@ -1048,9 +1076,18 @@ expandedTrailingInset?: number }`, `listExpandedContent`, and
1048
1076
  row count, the expanded slot's measured height, and the one-shot structural
1049
1077
  transition command. `expandedTrailingInset` defaults to zero and must be a
1050
1078
  finite, non-negative number of logical pixels. Without `disclosure`, the
1051
- existing four-slot and structural-transition behavior is unchanged. Web,
1052
- Desktop, and extension retain their existing structural presentation; these
1053
- native slots do not change the Web scroll-owner contract.
1079
+ existing four-slot and structural-transition behavior is unchanged. On Web,
1080
+ `C` and `T` occupy the existing single React footer band after the list rows,
1081
+ followed by the expanded trailing inset and the caller's footer `F`. `C` is
1082
+ mounted on first expansion and may remain mounted for that scope after collapse.
1083
+ Without an accepted `disclosure`, supplied `C` and `T` are hidden and inert.
1084
+ At the collapsed endpoint `C` has zero layout height and is hidden from pointer,
1085
+ keyboard, and accessibility interaction; `T` remains mounted and interactive
1086
+ through rapid reversals. Web does not use the native settlement callback to
1087
+ release `C`. The Web engine continues to measure that one footer band and to
1088
+ own its existing structural-tail animation and external scroll-host correction;
1089
+ its per-frame presentation need not match the native clip geometry. Desktop
1090
+ and extension retain their existing structural presentation.
1054
1091
 
1055
1092
  The native slot order is 0 header, 1 empty, 2 existing footer `F`, 3 sidecar,
1056
1093
  4 expanded content `C`, and 5 stable structure toggle `T`; the optional iOS
@@ -1097,8 +1134,14 @@ structural transition. An initial collapsed snapshot may omit or mount an
1097
1134
  empty `C` root; later collapse keeps its mounted instance through settlement.
1098
1135
 
1099
1136
  For each newly consumed `structuralTransition.id` with `disclosure`, native
1100
- emits `onStructuralTransitionSettled` once for the latest non-superseded id,
1101
- with JSON `{ transitionId: string, status: 'completed' | 'interrupted',
1137
+ emits `onStructuralTransitionSettled` once for the latest non-superseded id
1138
+ when a listener is registered. Without a listener, native still settles the
1139
+ command and releases its pending transition state, but does not serialize or
1140
+ cross the callback boundary. Adding or replacing a listener does not replay a
1141
+ settled id; removing it stops delivery for subsequent settlements. The caller
1142
+ may keep `C` mounted after settlement; native still controls its visibility,
1143
+ interaction, and accessibility. The callback carries JSON
1144
+ `{ transitionId: string, status: 'completed' | 'interrupted',
1102
1145
  settledExpanded: boolean }`. `settledExpanded` describes the accepted target
1103
1146
  after native geometry and scroll ownership have reached that state, never a
1104
1147
  guess from measured `C` height. Natural animation completion, reduced motion,
@@ -1112,8 +1155,9 @@ The caller guards the callback by its latest id and current list/account/network
1112
1155
  owner; a matching numeric id from a prior owner must not unmount current `C`.
1113
1156
  An already settled id
1114
1157
  does not re-emit on a same-id patch. Disposal drops the callback with its
1115
- owner. An unsupported or immediately settled new id must still acknowledge;
1116
- otherwise a caller could retain `C` indefinitely after collapse.
1158
+ owner. An unsupported or immediately settled new id must still acknowledge
1159
+ when a listener is registered; otherwise a caller could retain `C`
1160
+ indefinitely after collapse.
1117
1161
 
1118
1162
  On Android, mounting/unmounting a slot or changing its actual rounded native
1119
1163
  height MUST request one coalesced RecyclerView measurement/layout repair. The
@@ -119,7 +119,14 @@ final class HybridNativeList: HybridNativeListSpec {
119
119
  var onSelectionDelta: ((_ payloadJson: String) -> Void)?
120
120
  var onReorder: ((_ payloadJson: String) -> Void)?
121
121
  var onEndReached: ((_ payloadJson: String) -> Void)?
122
- var onStructuralTransitionSettled: ((_ payloadJson: String) -> Void)?
122
+ var onStructuralTransitionSettled: ((_ payloadJson: String) -> Void)? {
123
+ didSet {
124
+ runOnMain { [weak self] in
125
+ guard let self else { return }
126
+ self.hostView?.onStructuralTransitionSettled = self.onStructuralTransitionSettled
127
+ }
128
+ }
129
+ }
123
130
  var onVisibleRangeChanged: ((_ payloadJson: String) -> Void)? {
124
131
  didSet {
125
132
  runOnMain { [weak self] in
@@ -136,9 +143,6 @@ final class HybridNativeList: HybridNativeListSpec {
136
143
  hostView?.onSelectionDelta = { [weak self] in self?.onSelectionDelta?($0) }
137
144
  hostView?.onReorder = { [weak self] in self?.onReorder?($0) }
138
145
  hostView?.onEndReached = { [weak self] in self?.onEndReached?($0) }
139
- hostView?.onStructuralTransitionSettled = { [weak self] in
140
- self?.onStructuralTransitionSettled?($0)
141
- }
142
146
  }
143
147
 
144
148
  func applySnapshot(snapshotJson: String) throws {
@@ -654,7 +654,16 @@ final class NativeListView: UIView {
654
654
  private var sectionIndexHostHeightConstraint: NSLayoutConstraint?
655
655
  private var footerHeightConstraint: NSLayoutConstraint!
656
656
  private var dataSource: UICollectionViewDiffableDataSource<Int, String>!
657
+ private final class AcceptedRowIndex {
658
+ let byKey: [String: Int]
659
+
660
+ init(items: [NativeListItem]) {
661
+ byKey = Dictionary(uniqueKeysWithValues: items.enumerated().map { ($1.key, $0) })
662
+ }
663
+ }
664
+
657
665
  private var config: NativeListConfig?
666
+ private var acceptedRowIndex: AcceptedRowIndex?
658
667
  private var itemsByKey: [String: NativeListItem] = [:]
659
668
  private var endReachedGeneration: Int?
660
669
  private var lastVisibleRange: (first: Int, last: Int, firstKey: String?, lastKey: String?)?
@@ -996,6 +1005,18 @@ final class NativeListView: UIView {
996
1005
  }
997
1006
  }
998
1007
 
1008
+ private func acceptRowIndex(for next: NativeListConfig, replacing previous: NativeListConfig?) {
1009
+ if let previous, acceptedRowIndex != nil,
1010
+ previous.generation == next.generation,
1011
+ previous.items.count == next.items.count,
1012
+ zip(previous.items, next.items).allSatisfy({ old, new in
1013
+ old.key == new.key && old.type == new.type
1014
+ }) {
1015
+ return
1016
+ }
1017
+ acceptedRowIndex = AcceptedRowIndex(items: next.items)
1018
+ }
1019
+
999
1020
  func applySnapshotJson(_ json: String) {
1000
1021
  guard let next = try? NativeListConfig.parse(json: json) else { return }
1001
1022
  let transition = next.structuralTransition
@@ -1140,6 +1161,7 @@ final class NativeListView: UIView {
1140
1161
  if let current = config, !newDisclosureCommand,
1141
1162
  structuralRemovedItems.isEmpty, structuralTail == nil,
1142
1163
  isControlledSelectionSnapshotUpdate(from: current, to: next) {
1164
+ acceptRowIndex(for: next, replacing: current)
1143
1165
  config = next
1144
1166
  itemsByKey = Dictionary(uniqueKeysWithValues: next.items.map { ($0.key, $0) })
1145
1167
  // OneKey patch: A controlled selection echo is fully handled by the
@@ -1178,6 +1200,7 @@ final class NativeListView: UIView {
1178
1200
  }
1179
1201
  } ?? false
1180
1202
  if config?.generation != next.generation { endReachedGeneration = nil }
1203
+ acceptRowIndex(for: next, replacing: config)
1181
1204
  config = next
1182
1205
  if structuralTail == nil {
1183
1206
  disclosureCVisibleHeight = next.disclosure?.expanded == true ? containerSlotHeights[4] : 0
@@ -1367,7 +1390,8 @@ final class NativeListView: UIView {
1367
1390
  consumedStructuralTransitionID == pending.id,
1368
1391
  config?.disclosure?.expanded == pending.expanded else { return }
1369
1392
  pendingDisclosureSettlement = nil
1370
- emit(onStructuralTransitionSettled, [
1393
+ guard let callback = onStructuralTransitionSettled else { return }
1394
+ emit(callback, [
1371
1395
  "transitionId": pending.id,
1372
1396
  "status": status,
1373
1397
  "settledExpanded": pending.expanded,
@@ -1479,14 +1503,16 @@ final class NativeListView: UIView {
1479
1503
 
1480
1504
  func applyPatchesJson(_ json: String) {
1481
1505
  guard var current = config,
1506
+ let indexByKey = acceptedRowIndex?.byKey,
1482
1507
  let bytes = json.data(using: .utf8),
1483
1508
  let patches = try? JSONSerialization.jsonObject(with: bytes) as? [[String: Any]] else { return }
1484
- let indexByKey = Dictionary(uniqueKeysWithValues: current.items.enumerated().map { ($1.key, $0) })
1485
1509
  var seen = Set<String>()
1486
1510
  var pending: [(Int, [String: Any])] = []
1487
1511
  for patch in patches {
1488
1512
  let key = patch.string("key")
1489
1513
  guard let index = indexByKey[key],
1514
+ current.items.indices.contains(index),
1515
+ current.items[index].key == key,
1490
1516
  seen.insert(key).inserted,
1491
1517
  patch.string("type") == current.items[index].type,
1492
1518
  let changes = patch.dictionary("changes") else { return }
@@ -1535,12 +1561,9 @@ final class NativeListView: UIView {
1535
1561
  cancelInteractiveReorderForStructuralUpdate()
1536
1562
  }
1537
1563
  config = current
1538
- itemsByKey = Dictionary(uniqueKeysWithValues: current.items.map { ($0.key, $0) })
1539
- itemsByKey.merge(structuralRemovedItems) { current, _ in current }
1540
- if let tail = structuralTail, !tail.retiringKeys.isEmpty {
1541
- itemsByKey.merge(Dictionary(uniqueKeysWithValues: tail.items.map { ($0.key, $0) })) {
1542
- current, _ in current
1543
- }
1564
+ for (index, _) in pending {
1565
+ let item = current.items[index]
1566
+ itemsByKey[item.key] = item
1544
1567
  }
1545
1568
  if let tail = structuralTail {
1546
1569
  for key in changedKeys.union(marketQuoteKeys) {
@@ -2150,6 +2173,7 @@ final class NativeListView: UIView {
2150
2173
  let toIndex = keys.firstIndex(of: source.key),
2151
2174
  items.count == keys.count else { return }
2152
2175
  current.items = items
2176
+ acceptedRowIndex = AcceptedRowIndex(items: items)
2153
2177
  config = current
2154
2178
  guard source.index != toIndex else { return }
2155
2179
  var payload: [String: Any] = [
@@ -2841,6 +2865,7 @@ final class NativeListView: UIView {
2841
2865
  let selectionChanged = current.selectionMode != next.selectionMode ||
2842
2866
  current.selectedKeys != next.selectedKeys
2843
2867
  if current.generation != next.generation { endReachedGeneration = nil }
2868
+ acceptRowIndex(for: next, replacing: current)
2844
2869
  config = next
2845
2870
  itemsByKey = Dictionary(uniqueKeysWithValues: next.items.map { ($0.key, $0) })
2846
2871
  let changedKeys = next.items.compactMap { item -> String? in
@@ -3041,6 +3066,7 @@ final class NativeListView: UIView {
3041
3066
  dataSource = nil
3042
3067
 
3043
3068
  config = nil
3069
+ acceptedRowIndex = nil
3044
3070
  pagerStickyHeights.removeAllObjects()
3045
3071
  for slot in reactContainerSlots { slot.host.layer.mask = nil }
3046
3072
  stopStructuralAnimation()
@@ -3457,6 +3483,7 @@ extension NativeListView: UICollectionViewDragDelegate, UICollectionViewDropDele
3457
3483
  guard sourceItem.isReorderable, targetItem.isReorderable, sourceItem.sectionKey == targetItem.sectionKey else { return }
3458
3484
  current.items.remove(at: source.item)
3459
3485
  current.items.insert(sourceItem, at: destination.item)
3486
+ acceptedRowIndex = AcceptedRowIndex(items: current.items)
3460
3487
  config = current
3461
3488
  itemsByKey = Dictionary(uniqueKeysWithValues: current.items.map { ($0.key, $0) })
3462
3489
  var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
@@ -4,6 +4,81 @@ import XCTest
4
4
 
5
5
  @MainActor
6
6
  final class NativeListLifecycleTests: XCTestCase {
7
+ func testAcceptedRowIndexReusesStableShapeAndRejectsLateInvalidPatch() throws {
8
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
9
+ func snapshot(_ keys: [String], generation: Int, title: String = "Old") throws -> String {
10
+ let rows: [[String: Any]] = keys.map { key in
11
+ ["key": key, "type": "action", "title": title, "actionKey": "open"]
12
+ }
13
+ let value: [String: Any] = ["schemaVersion": 1, "generation": generation,
14
+ "layout": ["kind": "linear"], "rows": rows]
15
+ return String(decoding: try JSONSerialization.data(withJSONObject: value), as: UTF8.self)
16
+ }
17
+ func index() throws -> (ObjectIdentifier, [String: Int]) {
18
+ let optional = try XCTUnwrap(Mirror(reflecting: view).descendant("acceptedRowIndex"))
19
+ let value = try XCTUnwrap(Mirror(reflecting: optional).children.first?.value)
20
+ let byKey = try XCTUnwrap(Mirror(reflecting: value).descendant("byKey") as? [String: Int])
21
+ return (ObjectIdentifier(value as AnyObject), byKey)
22
+ }
23
+ func title(_ key: String) throws -> String {
24
+ let items = try XCTUnwrap(Mirror(reflecting: view).descendant("itemsByKey")
25
+ as? [String: NativeListItem])
26
+ return try XCTUnwrap(items[key]?.data["title"] as? String)
27
+ }
28
+ func patch(_ rows: [[String: Any]]) throws {
29
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: rows),
30
+ as: UTF8.self))
31
+ }
32
+
33
+ view.applySnapshotJson(try snapshot(["alpha", "beta"], generation: 1))
34
+ let initial = try index()
35
+ XCTAssertEqual(initial.1, ["alpha": 0, "beta": 1])
36
+ view.applySnapshotJson(try snapshot(["alpha", "beta"], generation: 1, title: "New"))
37
+ XCTAssertEqual(try index().0, initial.0)
38
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "Patched"]],
39
+ ["key": "missing", "type": "action", "changes": ["title": "Invalid"]]])
40
+ XCTAssertEqual(try title("alpha"), "New")
41
+ XCTAssertEqual(try title("beta"), "New")
42
+ XCTAssertEqual(try index().0, initial.0)
43
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "Patched"]]])
44
+ XCTAssertEqual(try title("alpha"), "Patched")
45
+ XCTAssertEqual(try index().0, initial.0)
46
+
47
+ view.applySnapshotJson(try snapshot(["beta", "alpha"], generation: 1))
48
+ let reordered = try index()
49
+ XCTAssertNotEqual(reordered.0, initial.0)
50
+ XCTAssertEqual(reordered.1, ["beta": 0, "alpha": 1])
51
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "After reorder"]]])
52
+ XCTAssertEqual(try title("alpha"), "After reorder")
53
+ view.applySnapshotJson(try snapshot(["beta", "gamma", "alpha"], generation: 1))
54
+ let inserted = try index()
55
+ XCTAssertNotEqual(inserted.0, reordered.0)
56
+ XCTAssertEqual(inserted.1, ["beta": 0, "gamma": 1, "alpha": 2])
57
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "After insert"]]])
58
+ XCTAssertEqual(try title("alpha"), "After insert")
59
+ view.applySnapshotJson(try snapshot(["beta", "alpha"], generation: 1))
60
+ let deleted = try index()
61
+ XCTAssertNotEqual(deleted.0, inserted.0)
62
+ XCTAssertEqual(deleted.1, ["beta": 0, "alpha": 1])
63
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "After delete"]]])
64
+ XCTAssertEqual(try title("alpha"), "After delete")
65
+ view.applySnapshotJson(try snapshot(["beta", "alpha"], generation: 2))
66
+ XCTAssertNotEqual(try index().0, deleted.0)
67
+ let beforeTypeChange = try index().0
68
+ let typeChanged: [String: Any] = ["schemaVersion": 1, "generation": 2,
69
+ "layout": ["kind": "linear"], "rows": [
70
+ ["key": "beta", "type": "identity", "title": "Beta",
71
+ "leading": ["kind": "icon", "name": "coin"]],
72
+ ["key": "alpha", "type": "action", "title": "Alpha", "actionKey": "open"],
73
+ ]]
74
+ view.applySnapshotJson(String(decoding: try JSONSerialization.data(withJSONObject: typeChanged),
75
+ as: UTF8.self))
76
+ XCTAssertNotEqual(try index().0, beforeTypeChange)
77
+ view.dispose()
78
+ XCTAssertEqual(Mirror(reflecting: try XCTUnwrap(Mirror(reflecting: view)
79
+ .descendant("acceptedRowIndex"))).children.count, 0)
80
+ }
81
+
7
82
  func testScrollEdgeStylesPreserveOverlayGeometryAndRestoreOriginalStyle() throws {
8
83
  guard #available(iOS 26.0, *) else {
9
84
  throw XCTSkip("Scroll-edge styles require iOS 26 or newer")
@@ -1557,6 +1632,73 @@ final class NativeListLifecycleTests: XCTestCase {
1557
1632
  }
1558
1633
  }
1559
1634
 
1635
+ func testHybridSettlementListenerFollowsRegistration() throws {
1636
+ let hybrid = HybridNativeList()
1637
+ let host = try XCTUnwrap(hybrid.view as? NativeListView)
1638
+ var first: [String] = []
1639
+ var second: [String] = []
1640
+ XCTAssertNil(host.onStructuralTransitionSettled)
1641
+
1642
+ hybrid.onStructuralTransitionSettled = { first.append($0) }
1643
+ host.onStructuralTransitionSettled?("first")
1644
+ XCTAssertEqual(first, ["first"])
1645
+
1646
+ hybrid.onStructuralTransitionSettled = { second.append($0) }
1647
+ host.onStructuralTransitionSettled?("second")
1648
+ XCTAssertEqual(first, ["first"])
1649
+ XCTAssertEqual(second, ["second"])
1650
+
1651
+ hybrid.onStructuralTransitionSettled = nil
1652
+ XCTAssertNil(host.onStructuralTransitionSettled)
1653
+ hybrid.dispose()
1654
+ }
1655
+
1656
+ func testDisclosureWithoutListenerStillSettlesWithoutReplay() throws {
1657
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1658
+ let controller = UIViewController()
1659
+ window.rootViewController = controller
1660
+ let view = NativeListView(frame: window.bounds)
1661
+ controller.view.addSubview(view)
1662
+ window.isHidden = false
1663
+ defer {
1664
+ view.dispose()
1665
+ view.removeFromSuperview()
1666
+ window.isHidden = true
1667
+ window.rootViewController = nil
1668
+ }
1669
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
1670
+ view.setContainerSlotHeightsJson("[0,0,60,0,100,40]")
1671
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1672
+ disclosureExpanded: false))
1673
+ view.layoutIfNeeded()
1674
+
1675
+ let first = try structuralRowsSnapshot(count: 6, generation: 2,
1676
+ transitionID: "without-listener", durationMs: 0, disclosureExpanded: true)
1677
+ view.applySnapshotJson(first)
1678
+ drainMainQueue()
1679
+ XCTAssertEqual(Mirror(reflecting: view).descendant("pendingDisclosureSettlement")
1680
+ .map { Mirror(reflecting: $0).children.count }, 0)
1681
+
1682
+ var settlements: [[String: Any]] = []
1683
+ view.onStructuralTransitionSettled = { payload in
1684
+ guard let data = payload.data(using: .utf8),
1685
+ let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1686
+ return
1687
+ }
1688
+ settlements.append(value)
1689
+ }
1690
+ view.applySnapshotJson(first)
1691
+ drainMainQueue()
1692
+ XCTAssertTrue(settlements.isEmpty)
1693
+
1694
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
1695
+ transitionID: "with-listener", durationMs: 0, disclosureExpanded: false))
1696
+ drainMainQueue()
1697
+ XCTAssertEqual(settlements.count, 1)
1698
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "with-listener")
1699
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
1700
+ }
1701
+
1560
1702
  func testDisclosureInitialEndpoints() throws {
1561
1703
  let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1562
1704
  let controller = UIViewController()
@@ -2552,6 +2694,13 @@ final class NativeListLifecycleTests: XCTestCase {
2552
2694
  XCTAssertGreaterThan(heightBeforePatch, 1500)
2553
2695
  let retiring = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 25, section: 0)) as? NativeListRowHost)
2554
2696
  XCTAssertEqual(retiring.bounds.height, 60, accuracy: 1)
2697
+ func storedContent(_ key: String) throws -> String {
2698
+ let items = try XCTUnwrap(Mirror(reflecting: view).descendant("itemsByKey")
2699
+ as? [String: NativeListItem])
2700
+ return try XCTUnwrap(items[key]).content
2701
+ }
2702
+ let oldAcceptedContent = try storedContent("row-20")
2703
+ let retiredContent = try storedContent("row-25")
2555
2704
  let patch: [[String: Any]] = [[
2556
2705
  "key": "row-20", "type": "dataRow", "changes": [
2557
2706
  "revision": 2,
@@ -2559,8 +2708,16 @@ final class NativeListLifecycleTests: XCTestCase {
2559
2708
  ["key": "price", "text": "$123.45"]],
2560
2709
  ],
2561
2710
  ]]
2711
+ let invalidRetiredPatch: [String: Any] = ["key": "row-25", "type": "dataRow",
2712
+ "changes": ["revision": 2]]
2713
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(
2714
+ withJSONObject: patch + [invalidRetiredPatch]), as: UTF8.self))
2715
+ XCTAssertEqual(try storedContent("row-20"), oldAcceptedContent)
2716
+ XCTAssertEqual(try storedContent("row-25"), retiredContent)
2562
2717
  view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patch),
2563
2718
  as: UTF8.self))
2719
+ XCTAssertNotEqual(try storedContent("row-20"), oldAcceptedContent)
2720
+ XCTAssertEqual(try storedContent("row-25"), retiredContent)
2564
2721
  list.layoutIfNeeded()
2565
2722
  let patched = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0)))
2566
2723
  XCTAssertTrue(labels(in: patched).contains { $0.text == "$123.45" })
@@ -12,6 +12,9 @@ import { applyOwnedNativePatches, captureNativeListInput, containNativeListInput
12
12
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
13
13
  const NativeListConfig = require('../nitrogen/generated/shared/json/NativeListConfig.json');
14
14
  const NativeListHost = getHostComponent('NativeList', () => NativeListConfig);
15
+ const clearedStructuralTransitionSettled = {
16
+ f: undefined
17
+ };
15
18
  const disclosureSlotMeasurementStyle = {
16
19
  alignSelf: 'stretch'
17
20
  };
@@ -478,6 +481,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
478
481
  viewProps.onLayout?.(event);
479
482
  },
480
483
  ...nativeCallbacks,
484
+ onStructuralTransitionSettled: onStructuralTransitionSettled ? nativeCallbacks.onStructuralTransitionSettled : clearedStructuralTransitionSettled,
481
485
  fontFamiliesJson: fontFamiliesJson,
482
486
  snapshotJson: snapshotJson,
483
487
  containerSlotHeightsJson: containerSlotHeightsJson,
@@ -8,6 +8,9 @@ import { applyRowPatches, containNativeListInput, emptyNativeListSnapshot, valid
8
8
  import { NativeListWebEngine } from "./web/NativeListWebEngine.js";
9
9
  import { acquireNativeListAvatar, canonicalNativeListAvatarUri } from "./web/NativeListWebAvatarCache.js";
10
10
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
11
+ const collapsedExpandedContentStyle = {
12
+ display: 'none'
13
+ };
11
14
  export function preloadNativeListAvatarImages(sources) {
12
15
  if (typeof document === 'undefined') return Promise.resolve(false);
13
16
  const uris = [...new Set(sources.map(source => canonicalNativeListAvatarUri(source.uri)).filter(uri => uri !== undefined))];
@@ -26,8 +29,8 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
26
29
  listHeader,
27
30
  listEmpty,
28
31
  listFooter,
29
- listExpandedContent: _listExpandedContent,
30
- listStructureToggle: _listStructureToggle,
32
+ listExpandedContent,
33
+ listStructureToggle,
31
34
  listSidecar,
32
35
  sidecarLayout,
33
36
  topOverlay: _topOverlay,
@@ -69,23 +72,8 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
69
72
  const hasEmptySlot = listEmpty !== undefined;
70
73
  const hasEmptySlotRef = useRef(hasEmptySlot);
71
74
  hasEmptySlotRef.current = hasEmptySlot;
72
- const [slotState, setSlotState] = useState(() => ({
73
- hasRows: snapshot.rows.length > 0,
74
- emptyBottomPadding: !snapshot.rows.length && hasEmptySlot ? snapshot.layout.contentPaddingBottom ?? snapshot.layout.contentPadding ?? 0 : 0,
75
- padding: snapshot.layout.contentPaddingHorizontal ?? snapshot.layout.contentPadding ?? 0
76
- }));
77
75
  const [viewportWidth, setViewportWidth] = useState(0);
78
76
  const [sidecarHeight, setSidecarHeight] = useState(0);
79
- const synchronizeSlots = next => {
80
- const hasRows = next.rows.length > 0;
81
- const padding = next.layout.contentPaddingHorizontal ?? next.layout.contentPadding ?? 0;
82
- const emptyBottomPadding = !hasRows && hasEmptySlotRef.current ? next.layout.contentPaddingBottom ?? next.layout.contentPadding ?? 0 : 0;
83
- setSlotState(previous => previous.hasRows === hasRows && previous.padding === padding && previous.emptyBottomPadding === emptyBottomPadding ? previous : {
84
- hasRows,
85
- padding,
86
- emptyBottomPadding
87
- });
88
- };
89
77
  const normalizeWebSnapshot = (next, hasReactEmpty = hasEmptySlotRef.current, hasSlotLayout = useSlotLayoutRef.current) => {
90
78
  if (hasSlotLayout && next.layout.orientation === 'horizontal') throw new Error('Web parent scrolling and container slots support vertical lists only');
91
79
  const emptySlot = hasReactEmpty && next.rows.length === 0;
@@ -107,6 +95,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
107
95
  const useSlotLayoutRef = useRef(false);
108
96
  useSlotLayoutRef.current ||= webScrollHost !== undefined || listHeader !== undefined || listEmpty !== undefined || listFooter !== undefined;
109
97
  useSlotLayoutRef.current ||= listSidecar !== undefined;
98
+ useSlotLayoutRef.current ||= listExpandedContent !== undefined || listStructureToggle !== undefined;
110
99
  const useSlotLayout = useSlotLayoutRef.current;
111
100
  const resolvedScrollHost = webScrollHost === undefined ? useSlotLayout ? ownedScrollHost : undefined : webScrollHost;
112
101
  const engineRef = useRef(undefined);
@@ -124,6 +113,30 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
124
113
  }
125
114
  return normalizeWebSnapshot(snapshot, hasEmptySlot, useSlotLayout);
126
115
  }) ?? acceptedSnapshotRef.current, [snapshot, hasEmptySlot, useSlotLayout, listSidecar, sidecarLayout]);
116
+ const [slotState, setSlotState] = useState(() => ({
117
+ hasRows: validatedSnapshot.rows.length > 0,
118
+ emptyBottomPadding: !validatedSnapshot.rows.length && hasEmptySlot ? validatedSnapshot.layout.contentPaddingBottom ?? validatedSnapshot.layout.contentPadding ?? 0 : 0,
119
+ padding: validatedSnapshot.layout.contentPaddingHorizontal ?? validatedSnapshot.layout.contentPadding ?? 0,
120
+ disclosurePresent: validatedSnapshot.disclosure !== undefined,
121
+ disclosureExpanded: validatedSnapshot.disclosure?.expanded === true,
122
+ expandedTrailingInset: validatedSnapshot.disclosure?.expandedTrailingInset ?? 0
123
+ }));
124
+ const synchronizeSlots = next => {
125
+ const hasRows = next.rows.length > 0;
126
+ const padding = next.layout.contentPaddingHorizontal ?? next.layout.contentPadding ?? 0;
127
+ const emptyBottomPadding = !hasRows && hasEmptySlotRef.current ? next.layout.contentPaddingBottom ?? next.layout.contentPadding ?? 0 : 0;
128
+ const disclosurePresent = next.disclosure !== undefined;
129
+ const disclosureExpanded = next.disclosure?.expanded === true;
130
+ const expandedTrailingInset = next.disclosure?.expandedTrailingInset ?? 0;
131
+ setSlotState(previous => previous.hasRows === hasRows && previous.padding === padding && previous.emptyBottomPadding === emptyBottomPadding && previous.disclosurePresent === disclosurePresent && previous.disclosureExpanded === disclosureExpanded && previous.expandedTrailingInset === expandedTrailingInset ? previous : {
132
+ hasRows,
133
+ padding,
134
+ emptyBottomPadding,
135
+ disclosurePresent,
136
+ disclosureExpanded,
137
+ expandedTrailingInset
138
+ });
139
+ };
127
140
  const snapshotRef = useRef(validatedSnapshot);
128
141
  const snapshotPropRef = useRef(validatedSnapshot);
129
142
  // An imperative snapshot survives host mounting until the snapshot prop changes.
@@ -131,7 +144,7 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
131
144
  snapshotPropRef.current = validatedSnapshot;
132
145
  snapshotRef.current = validatedSnapshot;
133
146
  acceptedSnapshotRef.current = validatedSnapshot;
134
- synchronizeSlots(snapshot);
147
+ synchronizeSlots(validatedSnapshot);
135
148
  }
136
149
  if (!initializedSnapshot.current) {
137
150
  acceptedSnapshotRef.current = validatedSnapshot;
@@ -315,6 +328,13 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
315
328
  ref: setHostRef
316
329
  });
317
330
  const padding = slotState.padding;
331
+ const footerBandStyle = {
332
+ paddingHorizontal: padding
333
+ };
334
+ const trailingInsetStyle = {
335
+ height: slotState.disclosureExpanded ? slotState.expandedTrailingInset : 0
336
+ };
337
+ const hasFooterBand = listFooter !== undefined || listExpandedContent !== undefined || listStructureToggle !== undefined;
318
338
  const content = /*#__PURE__*/_jsxs(View, {
319
339
  ref: sidecarLayout ? undefined : setBoundsRef,
320
340
  style: {
@@ -339,12 +359,25 @@ export const NativeList = /*#__PURE__*/forwardRef(function NativeList({
339
359
  paddingBottom: slotState.emptyBottomPadding
340
360
  },
341
361
  children: listEmpty
342
- }) : null, listFooter !== undefined ? /*#__PURE__*/_jsx(View, {
362
+ }) : null, hasFooterBand ? /*#__PURE__*/_jsxs(View, {
343
363
  testID: "native-list-footer-slot",
344
- style: {
345
- paddingHorizontal: padding
346
- },
347
- children: listFooter
364
+ style: footerBandStyle,
365
+ children: [listExpandedContent !== undefined ? /*#__PURE__*/_jsx(View, {
366
+ testID: "native-list-expanded-content-slot",
367
+ "aria-hidden": !slotState.disclosureExpanded,
368
+ pointerEvents: slotState.disclosureExpanded ? 'auto' : 'none',
369
+ style: slotState.disclosureExpanded ? undefined : collapsedExpandedContentStyle,
370
+ children: listExpandedContent
371
+ }) : null, listStructureToggle !== undefined ? /*#__PURE__*/_jsx(View, {
372
+ testID: "native-list-structure-toggle-slot",
373
+ "aria-hidden": !slotState.disclosurePresent,
374
+ pointerEvents: slotState.disclosurePresent ? 'auto' : 'none',
375
+ style: slotState.disclosurePresent ? undefined : collapsedExpandedContentStyle,
376
+ children: listStructureToggle
377
+ }) : null, slotState.expandedTrailingInset > 0 && (listExpandedContent !== undefined || listStructureToggle !== undefined) ? /*#__PURE__*/_jsx(View, {
378
+ testID: "native-list-trailing-inset-slot",
379
+ style: trailingInsetStyle
380
+ }) : null, listFooter]
348
381
  }) : null]
349
382
  });
350
383
  const bandWidth = sidecarLayout ? Math.min(viewportWidth, sidecarLayout.maxContentWidth) : 0;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  export { NativeList, preloadNativeListAvatarImages } from './NativeList';
4
- export { applyRowPatches, serializePatches, serializeSnapshot, validatePatches, validateSnapshot } from "./validation.js";
4
+ export { applyRowPatches, planNativeListPatches, serializePatches, serializeSnapshot, validatePatches, validateSnapshot } from "./validation.js";
5
5
  export { checkboxStateForKeys, checkboxStateForSection, isSelectableRow, reduceSelection, selectionStateFromSnapshot } from "./selection.js";
6
6
  export { configureNativeListFonts } from "./fonts.js";
7
7
  export { ScrollEdgeEffect } from "./ScrollEdgeEffect.js";
@@ -1669,6 +1669,96 @@ function normalizePatchStyles(patches) {
1669
1669
  });
1670
1670
  return changed ? next : patches;
1671
1671
  }
1672
+ const EMPTY_ROW_PATCHES = Object.freeze([]);
1673
+ function sameJsonValue(left, right) {
1674
+ if (left === right) return true;
1675
+ if (left === null || right === null) return false;
1676
+ if (typeof left !== 'object' || typeof right !== 'object') return false;
1677
+ if (Array.isArray(left) || Array.isArray(right)) {
1678
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => sameJsonValue(value, right[index]));
1679
+ }
1680
+ const leftObject = left;
1681
+ const rightObject = right;
1682
+ const leftKeys = Object.keys(leftObject).filter(key => leftObject[key] !== undefined);
1683
+ const rightKeys = Object.keys(rightObject).filter(key => rightObject[key] !== undefined);
1684
+ return leftKeys.length === rightKeys.length && leftKeys.every(key => sameJsonValue(leftObject[key], rightObject[key]));
1685
+ }
1686
+ function sameOptionalPresence(left, right) {
1687
+ return left === undefined === (right === undefined);
1688
+ }
1689
+
1690
+ /** Plan value-only patches; callers own valid immutable snapshots and commit state. */
1691
+ export function planNativeListPatches(previous, next) {
1692
+ if (previous === next) return EMPTY_ROW_PATCHES;
1693
+ const {
1694
+ rows: previousRows,
1695
+ ...previousMetadata
1696
+ } = previous;
1697
+ const {
1698
+ rows: nextRows,
1699
+ ...nextMetadata
1700
+ } = next;
1701
+ if (previousRows.length !== nextRows.length || !sameJsonValue(previousMetadata, nextMetadata)) return undefined;
1702
+ if (previousRows === nextRows) return EMPTY_ROW_PATCHES;
1703
+ const patches = [];
1704
+ for (let index = 0; index < nextRows.length; index += 1) {
1705
+ const oldRow = previousRows[index];
1706
+ const row = nextRows[index];
1707
+ if (oldRow.key !== row.key || oldRow.type !== row.type) return undefined;
1708
+ if (oldRow === row) continue;
1709
+ if (oldRow.type === 'identity' && row.type === 'identity') {
1710
+ const {
1711
+ subtitle: oldSubtitle,
1712
+ subtitleSegments: oldSubtitleSegments,
1713
+ trailing: oldTrailing,
1714
+ ...oldMetadata
1715
+ } = oldRow;
1716
+ const {
1717
+ subtitle,
1718
+ subtitleSegments,
1719
+ trailing,
1720
+ ...metadata
1721
+ } = row;
1722
+ if (!sameOptionalPresence(oldSubtitle, subtitle) || !sameOptionalPresence(oldSubtitleSegments, subtitleSegments) || !sameOptionalPresence(oldTrailing, trailing) || !sameJsonValue(oldMetadata, metadata)) return undefined;
1723
+ if (!sameJsonValue(oldSubtitle, subtitle) || !sameJsonValue(oldSubtitleSegments, subtitleSegments) || !sameJsonValue(oldTrailing, trailing)) {
1724
+ patches.push({
1725
+ type: 'identity',
1726
+ key: row.key,
1727
+ changes: {
1728
+ subtitle,
1729
+ subtitleSegments,
1730
+ trailing
1731
+ }
1732
+ });
1733
+ }
1734
+ } else if (oldRow.type === 'dataRow' && row.type === 'dataRow') {
1735
+ const {
1736
+ columns: oldColumns,
1737
+ trailing: oldTrailing,
1738
+ ...oldMetadata
1739
+ } = oldRow;
1740
+ const {
1741
+ columns,
1742
+ trailing,
1743
+ ...metadata
1744
+ } = row;
1745
+ if (!sameOptionalPresence(oldTrailing, trailing) || !sameJsonValue(oldMetadata, metadata) || !sameJsonValue(oldColumns[0], columns[0])) return undefined;
1746
+ if (!sameJsonValue(oldColumns.slice(1), columns.slice(1)) || !sameJsonValue(oldTrailing, trailing)) {
1747
+ patches.push({
1748
+ type: 'dataRow',
1749
+ key: row.key,
1750
+ changes: {
1751
+ columns,
1752
+ trailing
1753
+ }
1754
+ });
1755
+ }
1756
+ } else if (!sameJsonValue(oldRow, row)) {
1757
+ return undefined;
1758
+ }
1759
+ }
1760
+ return patches.length === 0 ? EMPTY_ROW_PATCHES : patches;
1761
+ }
1672
1762
  export function applyRowPatches(snapshot, patches) {
1673
1763
  const normalizedPatches = validatePatches(patches);
1674
1764
  const patchByKey = new Map(normalizedPatches.map(patch => [patch.key, patch]));
@@ -1,7 +1,7 @@
1
1
  export { NativeList, preloadNativeListAvatarImages } from './NativeList';
2
2
  export type { ActionAnchorState, NativeListKeyboardDismissMode, NativeListKeyboardShouldPersistTaps, NativeListProps, NativeListRef, ScrollAlignment, ScrollPositionOptions, ScrollToEndParams, ScrollToIndexFailedInfo, ScrollToIndexParams, ScrollToItemParams, ScrollToKeyParams, ScrollToLocationParams, ScrollToOffsetParams, StructuralTransitionSettledEvent, } from './NativeList';
3
3
  export type * from './models';
4
- export { applyRowPatches, serializePatches, serializeSnapshot, validatePatches, validateSnapshot, } from './validation';
4
+ export { applyRowPatches, planNativeListPatches, serializePatches, serializeSnapshot, validatePatches, validateSnapshot, } from './validation';
5
5
  export { checkboxStateForKeys, checkboxStateForSection, isSelectableRow, reduceSelection, selectionStateFromSnapshot, } from './selection';
6
6
  export type { SelectionAction, SelectionResult, SelectionState, } from './selection';
7
7
  export { configureNativeListFonts } from './fonts';
@@ -8,6 +8,8 @@ export declare function captureNativeListInput<T>(value: T): T;
8
8
  /** Private native-wrapper ownership; exported validators keep their public identity. */
9
9
  export declare function ownValidatedNativeSnapshot(snapshot: NativeListSnapshot): NativeListSnapshot;
10
10
  export declare function validatePatches(patches: readonly RowPatch[]): readonly RowPatch[];
11
+ /** Plan value-only patches; callers own valid immutable snapshots and commit state. */
12
+ export declare function planNativeListPatches(previous: NativeListSnapshot, next: NativeListSnapshot): readonly RowPatch[] | undefined;
11
13
  export declare function applyRowPatches(snapshot: NativeListSnapshot, patches: readonly RowPatch[]): NativeListSnapshot;
12
14
  /** Native wrapper only: preserve full public validation for unsupported patches. */
13
15
  export declare function applyOwnedNativePatches(snapshot: NativeListSnapshot, patches: readonly RowPatch[]): {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-native-list",
3
- "version": "6.7.0-17",
3
+ "version": "6.7.0-18",
4
4
  "description": "Template-driven native RecyclerView and UICollectionView for React Native",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./lib/module/index.js",
@@ -86,8 +86,8 @@
86
86
  "typescript": "^5.9.2"
87
87
  },
88
88
  "peerDependencies": {
89
- "@onekeyfe/react-native-image": "6.7.0-17",
90
- "@onekeyfe/react-native-native-logger": "6.7.0-17",
89
+ "@onekeyfe/react-native-image": "6.7.0-18",
90
+ "@onekeyfe/react-native-native-logger": "6.7.0-18",
91
91
  "react": "*",
92
92
  "react-native": "*",
93
93
  "react-native-nitro-modules": "0.37.0"
@@ -82,6 +82,7 @@ const NativeListHost = getHostComponent<
82
82
  NativeListNativeProps,
83
83
  NativeListMethods
84
84
  >('NativeList', () => NativeListConfig);
85
+ const clearedStructuralTransitionSettled = { f: undefined } as const;
85
86
  const disclosureSlotMeasurementStyle = { alignSelf: 'stretch' } as const;
86
87
 
87
88
  export function preloadNativeListAvatarImages(
@@ -795,6 +796,11 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
795
796
  viewProps.onLayout?.(event);
796
797
  }}
797
798
  {...nativeCallbacks}
799
+ onStructuralTransitionSettled={
800
+ onStructuralTransitionSettled
801
+ ? nativeCallbacks.onStructuralTransitionSettled
802
+ : clearedStructuralTransitionSettled
803
+ }
798
804
  fontFamiliesJson={fontFamiliesJson}
799
805
  snapshotJson={snapshotJson}
800
806
  containerSlotHeightsJson={containerSlotHeightsJson}
@@ -37,6 +37,8 @@ import {
37
37
  canonicalNativeListAvatarUri,
38
38
  } from './web/NativeListWebAvatarCache';
39
39
 
40
+ const collapsedExpandedContentStyle = { display: 'none' } as const;
41
+
40
42
  export type { NativeListProps, NativeListRef } from './NativeList.types';
41
43
  export type {
42
44
  ActionAnchorState,
@@ -93,8 +95,8 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
93
95
  listHeader,
94
96
  listEmpty,
95
97
  listFooter,
96
- listExpandedContent: _listExpandedContent,
97
- listStructureToggle: _listStructureToggle,
98
+ listExpandedContent,
99
+ listStructureToggle,
98
100
  listSidecar,
99
101
  sidecarLayout,
100
102
  topOverlay: _topOverlay,
@@ -148,37 +150,8 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
148
150
  const hasEmptySlot = listEmpty !== undefined;
149
151
  const hasEmptySlotRef = useRef(hasEmptySlot);
150
152
  hasEmptySlotRef.current = hasEmptySlot;
151
- const [slotState, setSlotState] = useState(() => ({
152
- hasRows: snapshot.rows.length > 0,
153
- emptyBottomPadding:
154
- !snapshot.rows.length && hasEmptySlot
155
- ? snapshot.layout.contentPaddingBottom ??
156
- snapshot.layout.contentPadding ??
157
- 0
158
- : 0,
159
- padding:
160
- snapshot.layout.contentPaddingHorizontal ??
161
- snapshot.layout.contentPadding ??
162
- 0,
163
- }));
164
153
  const [viewportWidth, setViewportWidth] = useState(0);
165
154
  const [sidecarHeight, setSidecarHeight] = useState(0);
166
- const synchronizeSlots = (next: NativeListSnapshot) => {
167
- const hasRows = next.rows.length > 0;
168
- const padding =
169
- next.layout.contentPaddingHorizontal ?? next.layout.contentPadding ?? 0;
170
- const emptyBottomPadding =
171
- !hasRows && hasEmptySlotRef.current
172
- ? next.layout.contentPaddingBottom ?? next.layout.contentPadding ?? 0
173
- : 0;
174
- setSlotState((previous) =>
175
- previous.hasRows === hasRows &&
176
- previous.padding === padding &&
177
- previous.emptyBottomPadding === emptyBottomPadding
178
- ? previous
179
- : { hasRows, padding, emptyBottomPadding }
180
- );
181
- };
182
155
  const normalizeWebSnapshot = (
183
156
  next: NativeListSnapshot,
184
157
  hasReactEmpty = hasEmptySlotRef.current,
@@ -213,6 +186,8 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
213
186
  listEmpty !== undefined ||
214
187
  listFooter !== undefined;
215
188
  useSlotLayoutRef.current ||= listSidecar !== undefined;
189
+ useSlotLayoutRef.current ||=
190
+ listExpandedContent !== undefined || listStructureToggle !== undefined;
216
191
  const useSlotLayout = useSlotLayoutRef.current;
217
192
  const resolvedScrollHost =
218
193
  webScrollHost === undefined
@@ -247,6 +222,52 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
247
222
  }) ?? acceptedSnapshotRef.current,
248
223
  [snapshot, hasEmptySlot, useSlotLayout, listSidecar, sidecarLayout]
249
224
  );
225
+ const [slotState, setSlotState] = useState(() => ({
226
+ hasRows: validatedSnapshot.rows.length > 0,
227
+ emptyBottomPadding:
228
+ !validatedSnapshot.rows.length && hasEmptySlot
229
+ ? validatedSnapshot.layout.contentPaddingBottom ??
230
+ validatedSnapshot.layout.contentPadding ??
231
+ 0
232
+ : 0,
233
+ padding:
234
+ validatedSnapshot.layout.contentPaddingHorizontal ??
235
+ validatedSnapshot.layout.contentPadding ??
236
+ 0,
237
+ disclosurePresent: validatedSnapshot.disclosure !== undefined,
238
+ disclosureExpanded: validatedSnapshot.disclosure?.expanded === true,
239
+ expandedTrailingInset:
240
+ validatedSnapshot.disclosure?.expandedTrailingInset ?? 0,
241
+ }));
242
+ const synchronizeSlots = (next: NativeListSnapshot) => {
243
+ const hasRows = next.rows.length > 0;
244
+ const padding =
245
+ next.layout.contentPaddingHorizontal ?? next.layout.contentPadding ?? 0;
246
+ const emptyBottomPadding =
247
+ !hasRows && hasEmptySlotRef.current
248
+ ? next.layout.contentPaddingBottom ?? next.layout.contentPadding ?? 0
249
+ : 0;
250
+ const disclosurePresent = next.disclosure !== undefined;
251
+ const disclosureExpanded = next.disclosure?.expanded === true;
252
+ const expandedTrailingInset = next.disclosure?.expandedTrailingInset ?? 0;
253
+ setSlotState((previous) =>
254
+ previous.hasRows === hasRows &&
255
+ previous.padding === padding &&
256
+ previous.emptyBottomPadding === emptyBottomPadding &&
257
+ previous.disclosurePresent === disclosurePresent &&
258
+ previous.disclosureExpanded === disclosureExpanded &&
259
+ previous.expandedTrailingInset === expandedTrailingInset
260
+ ? previous
261
+ : {
262
+ hasRows,
263
+ padding,
264
+ emptyBottomPadding,
265
+ disclosurePresent,
266
+ disclosureExpanded,
267
+ expandedTrailingInset,
268
+ }
269
+ );
270
+ };
250
271
  const snapshotRef = useRef(validatedSnapshot);
251
272
  const snapshotPropRef = useRef(validatedSnapshot);
252
273
  // An imperative snapshot survives host mounting until the snapshot prop changes.
@@ -254,7 +275,7 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
254
275
  snapshotPropRef.current = validatedSnapshot;
255
276
  snapshotRef.current = validatedSnapshot;
256
277
  acceptedSnapshotRef.current = validatedSnapshot;
257
- synchronizeSlots(snapshot);
278
+ synchronizeSlots(validatedSnapshot);
258
279
  }
259
280
  if (!initializedSnapshot.current) {
260
281
  acceptedSnapshotRef.current = validatedSnapshot;
@@ -523,6 +544,16 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
523
544
  );
524
545
  if (!useSlotLayout) return <View {...viewProps} ref={setHostRef} />;
525
546
  const padding = slotState.padding;
547
+ const footerBandStyle = { paddingHorizontal: padding };
548
+ const trailingInsetStyle = {
549
+ height: slotState.disclosureExpanded
550
+ ? slotState.expandedTrailingInset
551
+ : 0,
552
+ };
553
+ const hasFooterBand =
554
+ listFooter !== undefined ||
555
+ listExpandedContent !== undefined ||
556
+ listStructureToggle !== undefined;
526
557
  const content = (
527
558
  <View
528
559
  ref={sidecarLayout ? undefined : setBoundsRef}
@@ -542,11 +573,44 @@ export const NativeList = forwardRef<NativeListRef, NativeListProps>(
542
573
  {listEmpty}
543
574
  </View>
544
575
  ) : null}
545
- {listFooter !== undefined ? (
546
- <View
547
- testID="native-list-footer-slot"
548
- style={{ paddingHorizontal: padding }}
549
- >
576
+ {hasFooterBand ? (
577
+ <View testID="native-list-footer-slot" style={footerBandStyle}>
578
+ {listExpandedContent !== undefined ? (
579
+ <View
580
+ testID="native-list-expanded-content-slot"
581
+ aria-hidden={!slotState.disclosureExpanded}
582
+ pointerEvents={slotState.disclosureExpanded ? 'auto' : 'none'}
583
+ style={
584
+ slotState.disclosureExpanded
585
+ ? undefined
586
+ : collapsedExpandedContentStyle
587
+ }
588
+ >
589
+ {listExpandedContent}
590
+ </View>
591
+ ) : null}
592
+ {listStructureToggle !== undefined ? (
593
+ <View
594
+ testID="native-list-structure-toggle-slot"
595
+ aria-hidden={!slotState.disclosurePresent}
596
+ pointerEvents={slotState.disclosurePresent ? 'auto' : 'none'}
597
+ style={
598
+ slotState.disclosurePresent
599
+ ? undefined
600
+ : collapsedExpandedContentStyle
601
+ }
602
+ >
603
+ {listStructureToggle}
604
+ </View>
605
+ ) : null}
606
+ {slotState.expandedTrailingInset > 0 &&
607
+ (listExpandedContent !== undefined ||
608
+ listStructureToggle !== undefined) ? (
609
+ <View
610
+ testID="native-list-trailing-inset-slot"
611
+ style={trailingInsetStyle}
612
+ />
613
+ ) : null}
550
614
  {listFooter}
551
615
  </View>
552
616
  ) : null}
package/src/index.ts CHANGED
@@ -19,6 +19,7 @@ export type {
19
19
  export type * from './models';
20
20
  export {
21
21
  applyRowPatches,
22
+ planNativeListPatches,
22
23
  serializePatches,
23
24
  serializeSnapshot,
24
25
  validatePatches,
package/src/validation.ts CHANGED
@@ -3186,6 +3186,116 @@ function normalizePatchStyles(
3186
3186
  return changed ? next : patches;
3187
3187
  }
3188
3188
 
3189
+ const EMPTY_ROW_PATCHES: readonly RowPatch[] = Object.freeze([]);
3190
+
3191
+ function sameJsonValue(left: unknown, right: unknown): boolean {
3192
+ if (left === right) return true;
3193
+ if (left === null || right === null) return false;
3194
+ if (typeof left !== 'object' || typeof right !== 'object') return false;
3195
+ if (Array.isArray(left) || Array.isArray(right)) {
3196
+ return (
3197
+ Array.isArray(left) &&
3198
+ Array.isArray(right) &&
3199
+ left.length === right.length &&
3200
+ left.every((value, index) => sameJsonValue(value, right[index]))
3201
+ );
3202
+ }
3203
+ const leftObject = left as Record<string, unknown>;
3204
+ const rightObject = right as Record<string, unknown>;
3205
+ const leftKeys = Object.keys(leftObject).filter(
3206
+ (key) => leftObject[key] !== undefined
3207
+ );
3208
+ const rightKeys = Object.keys(rightObject).filter(
3209
+ (key) => rightObject[key] !== undefined
3210
+ );
3211
+ return (
3212
+ leftKeys.length === rightKeys.length &&
3213
+ leftKeys.every((key) => sameJsonValue(leftObject[key], rightObject[key]))
3214
+ );
3215
+ }
3216
+
3217
+ function sameOptionalPresence(left: unknown, right: unknown): boolean {
3218
+ return (left === undefined) === (right === undefined);
3219
+ }
3220
+
3221
+ /** Plan value-only patches; callers own valid immutable snapshots and commit state. */
3222
+ export function planNativeListPatches(
3223
+ previous: NativeListSnapshot,
3224
+ next: NativeListSnapshot
3225
+ ): readonly RowPatch[] | undefined {
3226
+ if (previous === next) return EMPTY_ROW_PATCHES;
3227
+ const { rows: previousRows, ...previousMetadata } = previous;
3228
+ const { rows: nextRows, ...nextMetadata } = next;
3229
+ if (
3230
+ previousRows.length !== nextRows.length ||
3231
+ !sameJsonValue(previousMetadata, nextMetadata)
3232
+ )
3233
+ return undefined;
3234
+ if (previousRows === nextRows) return EMPTY_ROW_PATCHES;
3235
+
3236
+ const patches: RowPatch[] = [];
3237
+ for (let index = 0; index < nextRows.length; index += 1) {
3238
+ const oldRow = previousRows[index];
3239
+ const row = nextRows[index];
3240
+ if (oldRow.key !== row.key || oldRow.type !== row.type) return undefined;
3241
+ if (oldRow === row) continue;
3242
+
3243
+ if (oldRow.type === 'identity' && row.type === 'identity') {
3244
+ const {
3245
+ subtitle: oldSubtitle,
3246
+ subtitleSegments: oldSubtitleSegments,
3247
+ trailing: oldTrailing,
3248
+ ...oldMetadata
3249
+ } = oldRow;
3250
+ const { subtitle, subtitleSegments, trailing, ...metadata } = row;
3251
+ if (
3252
+ !sameOptionalPresence(oldSubtitle, subtitle) ||
3253
+ !sameOptionalPresence(oldSubtitleSegments, subtitleSegments) ||
3254
+ !sameOptionalPresence(oldTrailing, trailing) ||
3255
+ !sameJsonValue(oldMetadata, metadata)
3256
+ )
3257
+ return undefined;
3258
+ if (
3259
+ !sameJsonValue(oldSubtitle, subtitle) ||
3260
+ !sameJsonValue(oldSubtitleSegments, subtitleSegments) ||
3261
+ !sameJsonValue(oldTrailing, trailing)
3262
+ ) {
3263
+ patches.push({
3264
+ type: 'identity',
3265
+ key: row.key,
3266
+ changes: { subtitle, subtitleSegments, trailing },
3267
+ });
3268
+ }
3269
+ } else if (oldRow.type === 'dataRow' && row.type === 'dataRow') {
3270
+ const {
3271
+ columns: oldColumns,
3272
+ trailing: oldTrailing,
3273
+ ...oldMetadata
3274
+ } = oldRow;
3275
+ const { columns, trailing, ...metadata } = row;
3276
+ if (
3277
+ !sameOptionalPresence(oldTrailing, trailing) ||
3278
+ !sameJsonValue(oldMetadata, metadata) ||
3279
+ !sameJsonValue(oldColumns[0], columns[0])
3280
+ )
3281
+ return undefined;
3282
+ if (
3283
+ !sameJsonValue(oldColumns.slice(1), columns.slice(1)) ||
3284
+ !sameJsonValue(oldTrailing, trailing)
3285
+ ) {
3286
+ patches.push({
3287
+ type: 'dataRow',
3288
+ key: row.key,
3289
+ changes: { columns, trailing },
3290
+ });
3291
+ }
3292
+ } else if (!sameJsonValue(oldRow, row)) {
3293
+ return undefined;
3294
+ }
3295
+ }
3296
+ return patches.length === 0 ? EMPTY_ROW_PATCHES : patches;
3297
+ }
3298
+
3189
3299
  export function applyRowPatches(
3190
3300
  snapshot: NativeListSnapshot,
3191
3301
  patches: readonly RowPatch[]