Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadOrderPlanner.swift

196 lines8.5 KB

1import Foundation
2​
3/// Swift port of the order-key math shared by web and React Native
4/// (`packages/client-runtime/src/state/threadSort.ts`). Order keys are
5/// base-26 fractional indices: a move writes one key that sorts between the
6/// moved thread's new neighbors, so threads hosted on other servers are never
7/// touched and every client converges on the same order.
8enum ThreadOrderPlanner {
9 private static let digits = Array("abcdefghijklmnopqrstuvwxyz")
10​
11 /// Whether the thread's environment accepts `thread.pin.reorder` /
12 /// `thread.active.reorder` writes for this section.
13 static func isWritable(_ thread: FeatureThread, section: FeatureThreadOrderSection) -> Bool {
14 switch section {
15 case .pinned: thread.supportsPinReorder == true
16 case .active: thread.supportsActiveReorder == true
17 }
18 }
19​
20 /// Key that sorts strictly between two neighbors; nil bounds mean "top of
21 /// the arranged run" / "bottom of the keyed run". Returns nil instead of
22 /// trapping when existing keys are corrupt or out of order — callers fall
23 /// back to rewriting the section.
24 static func orderKeyBetween(before: String?, after: String?) -> String? {
25 let a = before ?? ""
26 let b = after ?? ""
27 if !a.isEmpty, !isValidKey(a) { return nil }
28 if !b.isEmpty, !isValidKey(b) { return nil }
29 if !b.isEmpty, a >= b { return nil }
30 return midpoint(a, b)
31 }
32​
33 /// Evenly spaced keys for materializing an order. Wider keys keep a
34 /// large section from exhausting the space between two-digit keys
35 /// (`generateSpreadPinOrderKeys` in client-runtime).
36 static func spreadKeys(count: Int) -> [String] {
37 guard count > 0 else { return [] }
38 var width = 2
39 var space = digits.count * digits.count
40 while space <= (count + 1) * 2 {
41 width += 1
42 space *= digits.count
43 }
44 let step = Double(space) / Double(count + 1)
45 var keys: [String] = []
46 for index in 0..<count {
47 var value = Int((step * Double(index + 1)).rounded())
48 // Skip values whose low digit is the minimum (a trailing "a" key).
49 if value % digits.count == 0 { value += 1 }
50 var key = ""
51 for _ in 0..<width {
52 key = String(digits[value % digits.count]) + key
53 value /= digits.count
54 }
55 keys.append(key)
56 }
57 return keys
58 }
59​
60 /// Assignments needed to realize a new order. When the moved thread sits
61 /// between two keyed (or absent) neighbors this is a single write; when a
62 /// neighbor is keyless the whole section gets fresh spread keys — a
63 /// one-time materialization, after which every move is single-write.
64 /// `keysByID` may include rows outside `orderedIDs` (archived, snoozed,
65 /// filtered): their keys are reserved so a fresh key never collides with
66 /// a hidden row's (`planPinnedReorder` in client-runtime).
67 static func planReorder(
68 orderedIDs: [String],
69 keysByID: [String: String?],
70 movedID: String
71 ) -> [FeatureThreadOrderAssignment] {
72 let visibleIDs = Set(orderedIDs)
73 var reservedKeys = Set<String>()
74 for (id, key) in keysByID where !visibleIDs.contains(id) {
75 if let key { reservedKeys.insert(key) }
76 }
77 guard let movedIndex = orderedIDs.firstIndex(of: movedID) else { return [] }
78 let beforeID = movedIndex > 0 ? orderedIDs[movedIndex - 1] : nil
79 let afterID = movedIndex < orderedIDs.count - 1 ? orderedIDs[movedIndex + 1] : nil
80 let beforeKey = beforeID.flatMap { keysByID[$0] ?? nil }
81 let afterKey = afterID.flatMap { keysByID[$0] ?? nil }
82 let beforeUsable = beforeID == nil || beforeKey != nil
83 let afterUsable = afterID == nil || afterKey != nil
84 if beforeUsable, afterUsable {
85 var key = orderKeyBetween(before: beforeKey, after: afterKey)
86 while let current = key, reservedKeys.contains(current) {
87 key = orderKeyBetween(before: current, after: afterKey)
88 }
89 if let key {
90 return [FeatureThreadOrderAssignment(threadID: movedID, orderKey: key)]
91 }
92 }
93 // Keyless neighbor (or corrupt keys): rewrite the section in the new order.
94 let keys = spreadKeys(count: orderedIDs.count + reservedKeys.count)
95 .filter { !reservedKeys.contains($0) }
96 return orderedIDs.enumerated().compactMap { index, id in
97 guard index < keys.count, keys[index] != keysByID[id] ?? nil else { return nil }
98 return FeatureThreadOrderAssignment(threadID: id, orderKey: keys[index])
99 }
100 }
101​
102 /// Planner for a drag drop: `ordered` is the section's displayed order
103 /// after the drop (same input web passes to `planPinnedReorder`).
104 /// `all` keeps hidden rows' keys reserved. Every visible row anchors its
105 /// position but a plan exists only when the moved row — and every row a
106 /// spread rewrite would touch — can be written: reorder-capable and in
107 /// `connectedEnvironmentIDs`. Rows on disconnected servers keep their
108 /// stale keys as anchors and are never written, so a spread rewrite
109 /// cannot half-land on a dead client.
110 static func planDrop(
111 ordered: [FeatureThread],
112 all: [FeatureThread],
113 section: FeatureThreadOrderSection,
114 connectedEnvironmentIDs: Set<String>,
115 movedID: String
116 ) -> [FeatureThreadOrderAssignment]? {
117 let writableIDs = writableIDs(
118 in: ordered,
119 section: section,
120 connectedEnvironmentIDs: connectedEnvironmentIDs
121 )
122 guard writableIDs.contains(movedID) else { return nil }
123 let assignments = planReorder(
124 orderedIDs: ordered.map(\.id),
125 keysByID: keysByID(all, section: section),
126 movedID: movedID
127 )
128 guard !assignments.isEmpty,
129 assignments.allSatisfy({ writableIDs.contains($0.threadID) })
130 else { return nil }
131 return assignments
132 }
133​
134 private static func keysByID(
135 _ all: [FeatureThread],
136 section: FeatureThreadOrderSection
137 ) -> [String: String?] {
138 var keysByID: [String: String?] = [:]
139 for thread in all {
140 keysByID[thread.id] = section == .pinned ? thread.pinOrderKey : thread.activeOrderKey
141 }
142 return keysByID
143 }
144​
145 private static func writableIDs(
146 in ordered: [FeatureThread],
147 section: FeatureThreadOrderSection,
148 connectedEnvironmentIDs: Set<String>
149 ) -> Set<String> {
150 Set(
151 ordered
152 .filter {
153 isWritable($0, section: section)
154 && connectedEnvironmentIDs.contains($0.environmentID ?? "")
155 }
156 .map(\.id)
157 )
158 }
159​
160 private static func isValidKey(_ key: String) -> Bool {
161 guard !key.isEmpty, key.allSatisfy({ digits.contains($0) }) else { return false }
162 // A trailing minimum digit would leave no room to sort a key
163 // immediately before this one; generators never produce it, so treat
164 // it as corrupt.
165 return key.last != digits[0]
166 }
167​
168 /// Midpoint of two digit strings interpreted as fractions in (0, 1).
169 /// "" stands for the open bound on either side. Requires a < b.
170 private static func midpoint(_ a: String, _ b: String) -> String {
171 if !b.isEmpty {
172 // Recurse past the longest common prefix ("a" pads the shorter side).
173 var n = 0
174 let aChars = Array(a)
175 let bChars = Array(b)
176 while n < bChars.count,
177 (n < aChars.count ? aChars[n] : digits[0]) == bChars[n] { n += 1 }
178 if n > 0 {
179 return String(bChars[0..<n])
180 + midpoint(
181 n < aChars.count ? String(aChars[n...]) : "",
182 String(bChars[n...])
183 )
184 }
185 }
186 let digitA = a.isEmpty ? 0 : digits.firstIndex(of: a.first!)!
187 let digitB = b.isEmpty ? digits.count : digits.firstIndex(of: b.first!)!
188 if digitB - digitA > 1 {
189 return String(digits[(digitA + digitB + 1) / 2])
190 }
191 // Consecutive leading digits: either b has spare digits to shorten
192 // into, or we extend a (never producing a trailing minimum digit).
193 if b.count > 1 { return String(b.first!) }
194 return String(digits[digitA]) + midpoint(String(a.dropFirst()), "")
195 }