-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
editorjs-injector.ts
330 lines (305 loc) · 9.9 KB
/
editorjs-injector.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import { ApplicationRef, Inject, Injectable, InjectionToken, NgZone } from '@angular/core';
import EditorJS, { EditorConfig } from '@editorjs/editorjs';
import { BehaviorSubject, combineLatest, Observable, Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { Block } from '../types/blocks';
import { BlocksMap, ChangeMap, EditorMap, EventMap, EventType, ReadyMap } from '../types/maps';
/**
* Default values for each internal map
*/
const MAP_DEFAULTS = [['blocksMap', []], ['changeMap', 0], ['readyMap', false]];
/**
* Injection token for the EditorJS class
*/
export const EDITORJS_MODULE_IMPORT = new InjectionToken<any>('EDITORJS_MODULE_IMPORT');
/**
* EditorJS factory service, call `createInstance` with an `EditorConfig` to
* return an instance after the DOM element is ready, this is stored in a subject to
* be retrieved when ready.
*/
@Injectable({
providedIn: 'root'
})
export class EditorJSInstanceService {
/**
* Internal destroy method for the service
*/
private onDestroy$ = new Subject<boolean>();
/**
* Internal map of all EditorJS instances
*/
private editorMap: EditorMap = {};
/**
* Internal map of all Block `BehaviorSubject` instances
*/
private blocksMap: BlocksMap = {};
/**
* Internal map of all EditorJS ready states
*/
private readyMap: ReadyMap = {};
/**
* Internal map of all EditorJS change states
*/
private changeMap: ChangeMap = {};
/**
* The Event map is used to trigger events
*/
private eventMap: EventMap = {};
/**
* Import the `EditorJS` class
* @param EditorJS The `EditorJS` class
* @param zone Angular zone to run
* @param ref The application reference to trigger a tick
*/
constructor(
@Inject(EDITORJS_MODULE_IMPORT) private EditorJS: any,
private readonly zone: NgZone,
private readonly ref: ApplicationRef
) {}
/**
* Creates a new `EditorJS` instance outside of the Angular zone and
* then adds it to the editor instances
* @param config The {EditorConfig} configuration to create
*/
public createInstance(config: EditorConfig, autosave = false): void {
const holder = config.holder as string;
const editorConfig = {
...config,
onChange: () => {
this.changeMap[holder].next(Date.now());
}
};
this.zone.runOutsideAngular(() => {
const editor = new (this.EditorJS as any)(editorConfig);
const holder = config.holder as string;
editor.isReady.then(() => {
this.zone.run(() => {
this.setupSubjects(holder, editor);
this.setupEvents(holder);
this.readyMap[holder].next(true);
this.ref.tick();
});
});
});
}
/**
* Calls the save method on an editor
* @param holder The holder ID of the `EditorJS` instance
*/
public save(holder: string) {
this.eventMap[holder].next({ type: 'save' });
}
/**
* Calls a clear method on an editor
* @param holder The holder ID of the `EditorJS` instance
*/
public clear(holder: string) {
this.eventMap[holder].next({ type: 'clear' });
}
/**
* Updates the editor with new blocks
* @param holder The holder ID of the `EditorJS` instance
* @param blocks The blocks to update the editor with
*/
public update(holder: string, blocks: Block[]) {
if (!this.eventMap[holder]) {
this.eventMap[holder] = new BehaviorSubject<EventType>({ type: '' });
}
this.eventMap[holder].next({ type: 'update', payload: { blocks } });
}
/**
* Returns an Observable value of an `EditorJS` instance
* @param holder The holder ID of the `EditorJS` instance
*/
public getInstance(holder: string): Observable<EditorJS> {
if (!this.editorMap[holder]) {
this.editorMap[holder] = new BehaviorSubject<EditorJS | undefined>(undefined);
}
return this.editorMap[holder].asObservable();
}
/**
* Returns an Observable value of an `EditorJS` instance
* @param holder The holder ID of the `EditorJS` instance
*/
public getReady(holder: string): Observable<boolean> {
if (!this.readyMap[holder]) {
this.readyMap[holder] = new BehaviorSubject<boolean>(false);
}
return this.readyMap[holder].asObservable();
}
/**
* Returns an Observable value of an `EditorJS` instance
* @param holder The holder ID of the `EditorJS` instance
*/
public getChanged(holder: string): Observable<number> {
if (!this.changeMap[holder]) {
this.changeMap[holder] = new BehaviorSubject<number>(0);
}
return this.changeMap[holder].asObservable();
}
/**
* Returns an Observable value of an `EditorJS` instance
* @param holder The holder ID of the `EditorJS` instance
*/
public getBlocks(holder: string): Observable<Block[]> {
if (!this.blocksMap[holder]) {
this.blocksMap[holder] = new BehaviorSubject<Block[]>([]);
}
return this.blocksMap[holder].asObservable();
}
/**
* Destroys an instance of an editor and cleans up all Observable values
* @param holder The holder ID of the `EditorJS` instance
*/
public destroyInstance(holder: string): void {
const instanceDestroyed = new Subject<boolean>();
this.editorMap[holder]
.pipe(
filter(editor => typeof editor !== 'undefined'),
takeUntil(instanceDestroyed)
)
.subscribe(editor => {
this.zone.runOutsideAngular(() => {
editor.destroy();
this.zone.run(() => {
this.cleanupSubjects(holder);
instanceDestroyed.next(true);
instanceDestroyed.complete();
this.ref.tick();
});
});
});
}
/**
* Sets up the Subjects provided by this service
* @param holder The holder to set up the subjects for
* @param editor The Editor instance created outside of Angular
*/
private setupSubjects(holder: string, editor: EditorJS): void {
if (this.editorMap[holder]) {
this.editorMap[holder].next(editor);
} else {
this.editorMap[holder] = new BehaviorSubject<EditorJS>(editor);
}
MAP_DEFAULTS.forEach(([mapKay, value]: [string, typeof value]) => {
if (!this[mapKay][holder]) {
this[mapKay][holder] = new BehaviorSubject<typeof value>(value);
}
this[mapKay][holder].next(value);
});
if (!this.eventMap[holder]) {
this.eventMap[holder] = new BehaviorSubject<EventType>({ type: '' });
}
}
/**
* Sets up a listener for the event map and provides the editor and blocks to handle
* updates
* @param holder The holder ID of the `EditorJS` instance
*/
private setupEvents(holder: string) {
combineLatest([this.eventMap[holder], this.editorMap[holder]])
.pipe(
filter(([event, editor]) => event.type && typeof editor !== 'undefined'),
takeUntil(this.onDestroy$)
)
.subscribe(([event, editor]) => {
if (event.type === 'save') {
this.saveHandler(holder, editor);
}
if (event.type === 'clear') {
this.clearHandler(holder, editor);
}
if (event.type === 'update') {
this.updateHandler(holder, editor, event.payload.blocks);
}
this.eventMap[holder].next({ type: '' });
});
this.ref.tick();
}
/**
* Handles cleaning up all the subjects once an `EditorJS` instance has been
* destroyed
* @param holder The holder ID for the `EditorJS` instance
*/
private cleanupSubjects(holder: string) {
MAP_DEFAULTS.forEach(([mapKay, value]: [string, any]) => {
if (this[mapKay][holder]) {
this[mapKay][holder].next(value);
this[mapKay][holder].complete();
this[mapKay][holder] = null;
delete this[mapKay][holder];
}
});
this.eventMap[holder].next({ type: '' });
this.eventMap[holder].complete();
this.eventMap[holder] = null;
delete this.eventMap[holder];
this.editorMap[holder] = null;
delete this.editorMap[holder];
}
/**
* Call this to destroy all subscriptions within the service
*/
public destroy() {
Object.keys(this.editorMap).forEach(key => {
this.destroyInstance(key);
});
this.onDestroy$.next(true);
this.onDestroy$.complete();
}
/**
* This internal handler calls the `EditorJS` instance save outside of the
* Angular zone, this means it will not trigger change detection
* @param holder The holder ID for the `EditorJS` instance
* @param editor The `EditorJS` instance
* @param blocks The {Block} items to render
*/
private saveHandler(holder: string, editor: EditorJS) {
this.zone.runOutsideAngular(() => {
editor.saver.save().then(data => {
this.zone.run(() => {
this.blocksMap[holder].next(data.blocks);
});
});
});
}
/**
* This internal handler calls the `EditorJS` instance clear outside of the
* Angular zone, this means it will not trigger change detection
* @param holder The holder ID for the `EditorJS` instance
* @param editor The `EditorJS` instance
* @param blocks The {Block} items to render
*/
private clearHandler(holder: string, editor: EditorJS) {
this.zone.runOutsideAngular(() => {
editor.blocks.clear();
this.zone.run(() => {
this.blocksMap[holder].next([]);
this.changeMap[holder].next(Date.now());
});
});
}
/**
* This internal handler calls the `EditorJS` instance render outside of the
* Angular zone, this means it will not trigger change detection
* @param holder The holder ID for the `EditorJS` instance
* @param editor The `EditorJS` instance
* @param blocks The {Block} items to render
*/
private updateHandler(holder: string, editor: EditorJS, blocks: Block[]) {
if (!blocks) {
return;
}
this.zone.runOutsideAngular(() => {
editor.blocks.render({
time: Date.now(),
version: EditorJS.version,
blocks
});
this.zone.run(() => {
this.blocksMap[holder].next(blocks);
this.changeMap[holder].next(Date.now());
});
});
}
}