forked from johnfactotum/foliate-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathannotations.js
62 lines (62 loc) · 2.23 KB
/
annotations.js
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
export class Annotations {
#annotationsByIndex = new Map()
#byValue = new Map()
#anchorsByValue = new Map()
#indicesByValue = new Map()
constructor({ resolve, compare, onAdd, onDelete, onUpdate }) {
this.resolve = resolve
this.compare = compare
this.onAdd = onAdd
this.onDelete = onDelete
this.onUpdate = onUpdate
}
async add(annotation, sorted) {
const { value } = annotation
if (this.#byValue.has(value)) return
const { index, anchor } = await this.resolve(value)
this.#byValue.set(value, annotation)
this.#indicesByValue.set(value, index)
this.#anchorsByValue.set(value, anchor)
if (this.#annotationsByIndex.has(index)) {
const arr = this.#annotationsByIndex.get(index)
if (sorted) {
arr.push(annotation)
this.onAdd?.(annotation, index, arr.length - 1)
} else {
let position = 0
for (let i = 0; i < arr.length; i++) {
const itemValue = arr[i].value
if (this.compare(value, itemValue) <= 0) break
position = i + 1
}
arr.splice(position, 0, annotation)
this.onAdd?.(annotation, index, position)
}
} else {
this.#annotationsByIndex.set(index, [annotation])
this.onAdd?.(annotation, index, 0)
}
}
update(annotation) {
const index = this.#indicesByValue.get(annotation.value)
const old = this.#byValue.get(annotation.value)
Object.assign(old, annotation)
this.onUpdate?.(annotation, index)
}
delete(value) {
const index = this.#indicesByValue.get(value)
const arr = this.#annotationsByIndex.get(index)
const position = arr.findIndex(a => a.value === value)
arr.splice(position, 1)
this.#byValue.delete(value)
this.#indicesByValue.delete(value)
this.#anchorsByValue.delete(value)
this.onDelete?.(value, index, position)
}
getByIndex(index) {
return this.#annotationsByIndex.get(index) ?? []
}
getAnchor(value) {
return this.#anchorsByValue.get(value)
}
}