-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuseNote.ts
More file actions
434 lines (371 loc) · 9.86 KB
/
useNote.ts
File metadata and controls
434 lines (371 loc) · 9.86 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import { onMounted, ref, type Ref, type MaybeRefOrGetter, computed, toValue, watch } from 'vue';
import { noteService, editorToolsService } from '@/domain';
import type { Note, NoteContent, NoteId } from '@/domain/entities/Note';
import type { NoteTool } from '@/domain/entities/Note';
import { useRouter, useRoute } from 'vue-router';
import type { NoteDraft } from '@/domain/entities/NoteDraft';
import type EditorTool from '@/domain/entities/EditorTool';
import DomainError from '@/domain/entities/errors/Base';
import useNavbar from './useNavbar';
import { getTitle } from '@/infrastructure/utils/note';
import type { NoteHierarchy } from '@/domain/entities/NoteHierarchy';
/**
* Creates base structure for the empty note:
* First block is Header, second is an empty Paragraph
*/
function createDraft(): NoteDraft {
return {
content: {
blocks: [
{
type: 'header',
data: {
level: 1,
text: '',
},
},
{
type: 'paragraph',
data: {
text: '',
},
},
],
},
};
}
/**
* Note hook state
*/
interface UseNoteComposableState {
/**
* NoteDraft - on new note creation
* Note - when note is loaded
* null - when note is not loaded yet
*/
note: Ref<Note | NoteDraft | null>;
/**
* List of tools used in the note
*/
noteTools: Ref<EditorTool[] | undefined>;
/**
* Creates/updates the note
*/
save: (content: NoteContent, parentId: NoteId | undefined) => Promise<void>;
/**
* Returns list of tools used in note
*/
resolveToolsByContent: (content: NoteContent) => NoteTool[];
/**
* Load note by custom hostname
*/
resolveHostname: () => Promise<void>;
/**
* Unlink note from parent
*/
unlinkParent: () => Promise<void>;
/**
* Returns an array of note parents for the current note.
*/
noteParents: Ref<Note[]>;
/**
* Defines if user can edit note
*/
canEdit: Ref<boolean>;
/**
* Parent note, undefined if it's a root note
*/
parentNote: Ref<Note | undefined>;
/**
* Title for bookmarks in the browser
*/
noteTitle: Ref<string>;
/**
* Note hierarchy
*/
noteHierarchy: Ref<NoteHierarchy | null>;
/**
* Load note by id
* @param id - Note identifier
*/
load: (id: NoteId) => Promise<void>;
/**
* Load note hierarchy separately when needed
* @param id - Note identifier
*/
loadHierarchy: (id: NoteId) => Promise<void>;
}
interface UseNoteComposableOptions {
/**
* Note identifier
*/
id: MaybeRefOrGetter<NoteId | null>;
}
/**
* Application service for working with the specific Note
* @param options - note service options
*/
export default function (options: UseNoteComposableOptions): UseNoteComposableState {
const { patchOpenedPageByUrl, deleteOpenedPageByUrl } = useNavbar();
/**
* Current note identifier
*/
const currentId = computed(() => toValue(options.id));
/**
* Currently opened note
*
* When new note is created, fill with draft
*/
const note = ref<Note | NoteDraft | null>(currentId.value === null ? createDraft() : null);
/**
* Here we will store the content of the note on last save
*/
const lastUpdateContent = ref<NoteContent | null>(null);
/**
* List of tools used in the note
* Undefined when note is not loaded yet
*/
const noteTools = ref<EditorTool[] | undefined>(undefined);
/**
* Router instance used to replace the current route with note id
*/
const router = useRouter();
const route = useRoute();
/**
* Is there any note currently saving
* Used to prevent re-load note after draft is saved
*/
const isNoteSaving = ref<boolean>(false);
/**
* Note Title identifier
*/
const noteTitle = computed(() => {
const noteContent = lastUpdateContent.value ?? note.value?.content;
return getTitle(noteContent);
});
/**
* Editing rights for the currently opened note
*
* true by default
*/
const canEdit = ref<boolean>(true);
/**
* Parent note
*
* undefined by default
*/
const parentNote = ref<Note | undefined>(undefined);
/**
* Note parents of the actual note
*
* Actual note by default
*/
const noteParents = ref<Note[]>([]);
/**
* Note hierarchy
*
* null by default
*/
const noteHierarchy = ref<NoteHierarchy | null>(null);
/**
* get note hierarchy
* @param id - note id
*/
async function getNoteHierarchy(id: NoteId): Promise<void> {
let response = await noteService.getNoteHierarchy(id);
noteHierarchy.value = response;
}
/**
* Load note by id
* @param id - Note identifier got from composable argument
*/
async function load(id: NoteId): Promise<void> {
try {
const response = await noteService.getNoteById(id);
note.value = response.note;
canEdit.value = response.accessRights.canEdit;
noteTools.value = response.tools;
parentNote.value = response.parentNote;
noteParents.value = response.parents;
} catch (error) {
deleteOpenedPageByUrl(route.path);
if (error instanceof DomainError) {
void router.push(`/error/${error.statusCode}`);
} else {
void router.push('/error/500');
}
}
}
/**
* Load note hierarchy separately when needed
* @param id - Note identifier
*/
async function loadHierarchy(id: NoteId): Promise<void> {
await getNoteHierarchy(id);
}
/**
* Returns list of tools used in the note
* @param content - content of the note
*/
function resolveToolsByContent(content: NoteContent): NoteTool[] {
const uniqueNoteTools = new Map<string, NoteTool>();
content.blocks.forEach((block) => {
const toolClassAndInfo = editorToolsService.getToolByName(block.type);
if (toolClassAndInfo === undefined) {
return;
}
uniqueNoteTools.set(toolClassAndInfo.tool.id, {
id: toolClassAndInfo.tool.id,
name: toolClassAndInfo.tool.name,
});
});
return Array.from(uniqueNoteTools.values());
}
/**
* Saves the note
* @param content - Note content (Editor.js data)
* @param parentId - Id of the parent note. If null, then it's a root note
*/
async function save(content: NoteContent, parentId: NoteId | undefined): Promise<void> {
if (note.value === null) {
throw new Error('Note is not loaded yet');
}
/**
* Resolve tools that are used in note
*/
const specifiedNoteTools = resolveToolsByContent(content);
isNoteSaving.value = true;
if (currentId.value === null) {
/**
* @todo try-catch domain errors
*/
const noteCreated = await noteService.createNote(content, specifiedNoteTools, parentId);
/**
* Replace the current route with note id
*/
await router.replace({
name: 'note',
params: {
id: noteCreated.id,
},
});
patchOpenedPageByUrl(
route.path,
{
title: noteTitle.value,
url: route.path,
});
} else {
await noteService.updateNoteContentAndTools(currentId.value, content, specifiedNoteTools);
}
/**
* Store just saved content in memory
*/
lastUpdateContent.value = content;
isNoteSaving.value = false;
}
/**
* Unlink note from parent
*/
async function unlinkParent(): Promise<void> {
if (note.value === null) {
throw new Error('Note is not loaded yet');
}
if (currentId.value === null) {
throw new Error('Note id is not defined');
}
await noteService.unlinkParent(currentId.value);
parentNote.value = undefined;
}
onMounted(() => {
/**
* If we have id, load note and note hierarchy
*/
if (currentId.value !== null) {
void load(currentId.value);
}
});
/**
* Get note by custom hostname
*/
const resolveHostname = async (): Promise<void> => {
note.value = (await noteService.getNoteByHostname(location.hostname)).note;
};
/**
* Reset note to the initial state
*/
function resetNote(): void {
note.value = createDraft();
canEdit.value = true;
lastUpdateContent.value = null;
noteHierarchy.value = null;
}
/**
* Recursively update the note hierarchy title
* @param hierarchy - The note hierarchy to update
* @param title - The new title to update in the hierarchy
*/
function updateNoteHierarchyContent(hierarchy: NoteHierarchy | null, title: string): void {
// If hierarchy is null, there's nothing to update
if (!hierarchy) {
return;
}
// If content is null, we can't update the hierarchy content
if (!title) {
return;
}
// Update the title of the current note in the hierarchy if it matches the currentId
if (hierarchy.noteId === currentId.value) {
hierarchy.noteTitle = title;
}
// Recursively update child notes
if (hierarchy.childNotes) {
hierarchy.childNotes.forEach(child => updateNoteHierarchyContent(child, title));
}
}
watch(currentId, (newId, prevId) => {
/**
* One note is open, user clicks on "+" to create another new note
* Clear existing note
*/
if (newId === null) {
resetNote();
return;
}
const isDraftSaving = prevId === null && isNoteSaving.value;
/**
* Case for newly created note,
* we don't need to re-load it
*/
if (isDraftSaving) {
return;
}
void load(newId);
});
watch(noteTitle, (currentNoteTitle) => {
if (route.name == 'note') {
patchOpenedPageByUrl(
route.path,
{
title: currentNoteTitle,
url: route.path,
});
}
updateNoteHierarchyContent(noteHierarchy.value, currentNoteTitle);
});
return {
note,
noteTools,
noteTitle,
canEdit,
resolveHostname,
resolveToolsByContent,
save,
unlinkParent,
noteParents,
parentNote,
noteHierarchy,
load,
loadHierarchy,
};
}