/
ObservableGroupMap.ts
219 lines (196 loc) · 7.09 KB
/
ObservableGroupMap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import {
observable,
IReactionDisposer,
reaction,
observe,
IObservableArray,
transaction,
ObservableMap,
Lambda,
} from "mobx"
// ObservableGroupMaps actually each use their own symbol, so that an item can be tracked by
// multiple OGMs. We declare this here so we can type the arrays properly.
declare const OGM_INFO_KEY: unique symbol
interface GroupItem {
[OGM_INFO_KEY]?: GroupItemInfo
}
interface GroupItemInfo {
groupByValue: any
reaction: IReactionDisposer
groupArrIndex: number
}
/**
* Reactively sorts a base observable array into multiple observable arrays based on the value of a
* `groupBy: (item: T) => G` function.
*
* This observes the individual computed groupBy values and only updates the source and dest arrays
* when there is an actual change, so this is far more efficient than, for example
* `base.filter(i => groupBy(i) === 'we')`.
*
* No guarantees are made about the order of items in the grouped arrays.
*
* The resulting map of arrays is read-only. clear(), set(), delete() are not supported and
* modifying the group arrays will lead to undefined behavior.
*
* @example
* const slices = observable([
* { day: "mo", hours: 12 },
* { day: "tu", hours: 2 },
* ])
* const slicesByDay = new ObservableGroupMap(slices, (slice) => slice.day)
* autorun(() => console.log(
* slicesByDay.get("mo")?.length ?? 0,
* slicesByDay.get("we"))) // outputs 1, undefined
* slices[0].day = "we" // outputs 0, [{ day: "we", hours: 12 }]
*/
export class ObservableGroupMap<G, T> extends ObservableMap<G, IObservableArray<T & GroupItem>> {
/**
* Base observable array which is being sorted into groups.
*/
private readonly _base: IObservableArray<T & GroupItem>
/**
* The ObservableGroupMap needs to track some state per-item. This is the name/symbol of the
* property used to attach the state.
*/
private readonly _ogmInfoKey: typeof OGM_INFO_KEY
/**
* The function used to group the items.
*/
private readonly _groupBy: (x: T) => G
/**
* This function is used to generate the mobx debug names of the observable group arrays.
*/
private readonly _keyToName: (group: G) => string
private readonly _disposeBaseObserver: Lambda
/**
* Create a new ObservableGroupMap. This immediately observes all members of the array. Call
* #dispose() to stop tracking.
*
* @param base The array to sort into groups.
* @param groupBy The function used for grouping.
* @param options Object with properties:
* `name`: Debug name of this ObservableGroupMap.
* `keyToName`: Function to create the debug names of the observable group arrays.
*/
constructor(
base: IObservableArray<T>,
groupBy: (x: T) => G,
{
name = "ogm" + ((Math.random() * 1000) | 0),
keyToName = (x) => "" + x,
}: { name?: string; keyToName?: (group: G) => string } = {}
) {
super()
this._keyToName = keyToName
this._groupBy = groupBy
this._ogmInfoKey = ("function" == typeof Symbol
? Symbol("ogmInfo" + name)
: "__ogmInfo" + name) as any
this._base = base
for (let i = 0; i < base.length; i++) {
this._addItem(base[i])
}
this._disposeBaseObserver = observe(this._base, (change) => {
if ("splice" === change.type) {
transaction(() => {
for (const removed of change.removed) {
this._removeItem(removed)
}
for (const added of change.added) {
this._addItem(added)
}
})
} else if ("update" === change.type) {
transaction(() => {
this._removeItem(change.oldValue)
this._addItem(change.newValue)
})
} else {
throw new Error("illegal state")
}
})
}
public clear(): void {
throw new Error("not supported")
}
public delete(_key: G): boolean {
throw new Error("not supported")
}
public set(_key: G, _value: IObservableArray<T>): this {
throw new Error("not supported")
}
public get(key: G): IObservableArray<T> | undefined {
// override get to return IObservableArray<T> instead of IObservableArray<T & GroupItem>
return super.get(key)
}
/**
* Disposes all observers created during construction and removes state added to base array
* items.
*/
public dispose() {
this._disposeBaseObserver()
for (let i = 0; i < this._base.length; i++) {
const item = this._base[i]
const grouperItemInfo: GroupItemInfo = item[this._ogmInfoKey]
grouperItemInfo.reaction()
delete item[this._ogmInfoKey]
}
}
private _getGroupArr(key: G) {
let result = super.get(key)
if (undefined === result) {
result = observable([], { name: `GroupArray[${this._keyToName(key)}]` })
super.set(key, result)
}
return result
}
private _removeFromGroupArr(key: G, itemIndex: number) {
const arr = super.get(key)!
if (1 === arr.length) {
super.delete(key)
} else if (itemIndex === arr.length - 1) {
// last position in array
arr.length--
} else {
arr[itemIndex] = arr[arr.length - 1]
arr[itemIndex][this._ogmInfoKey].groupArrIndex = itemIndex
arr.length--
}
}
private _addItem(item: T & GroupItem) {
const groupByValue = this._groupBy(item)
const groupArr = this._getGroupArr(groupByValue)
const value: GroupItemInfo = {
groupByValue: groupByValue,
groupArrIndex: groupArr.length,
reaction: reaction(
() => this._groupBy(item),
(newGroupByValue, _r) => {
console.log("new group by value ", newGroupByValue)
const grouperItemInfo = item[this._ogmInfoKey]!
this._removeFromGroupArr(
grouperItemInfo.groupByValue,
grouperItemInfo.groupArrIndex
)
const newGroupArr = this._getGroupArr(newGroupByValue)
const newGroupArrIndex = newGroupArr.length
newGroupArr.push(item)
grouperItemInfo.groupByValue = newGroupByValue
grouperItemInfo.groupArrIndex = newGroupArrIndex
}
),
}
Object.defineProperty(item, this._ogmInfoKey, {
configurable: true,
enumerable: false,
value,
})
groupArr.push(item)
}
private _removeItem(item: GroupItem) {
const grouperItemInfo = item[this._ogmInfoKey]
this._removeFromGroupArr(grouperItemInfo.groupByValue, grouperItemInfo.groupArrIndex)
grouperItemInfo.reaction()
delete item[this._ogmInfoKey]
}
}