MCPcopy Create free account
hub / github.com/annotorious/annotorious / createStore

Function createStore

packages/annotorious-core/src/state/Store.ts:31–420  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

29const isAnnotation = <T extends Annotation>(arg: any): arg is T => arg.id !== undefined;
30
31export const createStore = <T extends Annotation>() => {
32
33 const annotationIndex = new Map<string, T>();
34
35 const bodyIndex = new Map<string, string>();
36
37 const observers: StoreObserver<T>[] = [];
38
39 const observe = (onChange: { (event: StoreChangeEvent<T>): void }, options: StoreObserveOptions = {}) => {
40 observers.push({ onChange, options });
41 }
42
43 const unobserve = (onChange: { (event: StoreChangeEvent<T>): void }) => {
44 const idx = observers.findIndex(observer => observer.onChange == onChange);
45 if (idx > -1)
46 observers.splice(idx, 1);
47 }
48
49 const emit = (origin: Origin, changes: ChangeSet<T>) => {
50 const event: StoreChangeEvent<T> = {
51 origin,
52 changes: {
53 created: changes.created || [],
54 updated: changes.updated || [],
55 deleted: changes.deleted || []
56 },
57 state: [...annotationIndex.values()]
58 };
59
60 observers.forEach(observer => {
61 if (shouldNotify(observer, event))
62 observer.onChange(event);
63 });
64 }
65
66 const addAnnotation = (annotation: Partial<T>, origin = Origin.LOCAL) => {
67 const existing = annotation.id && annotationIndex.get(annotation.id);
68
69 if (existing) {
70 throw Error(`Cannot add annotation ${annotation.id} - exists already`);
71 } else {
72 const sanitized = sanitize(annotation);
73
74 annotationIndex.set(sanitized.id, sanitized);
75 sanitized.bodies.forEach(b => bodyIndex.set(b.id, sanitized.id));
76 emit(origin, { created: [sanitized] });
77 }
78 }
79
80 const updateOneAnnotation = (arg1: string | Partial<T>, arg2?: Partial<T> | Origin) => {
81 const updated: T = typeof arg1 === 'string' ? sanitize(arg2 as Partial<T>) : sanitize(arg1);
82
83 const oldId: string | undefined = typeof arg1 === 'string' ? arg1 : arg1.id;
84 const oldValue = oldId && annotationIndex.get(oldId);
85
86 if (oldValue) {
87 const update: Update<T> = diffAnnotations(oldValue, updated);
88

Callers 4

Hover.test.tsFile · 0.90
Store.test.tsFile · 0.90
Selection.test.tsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected