-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathuseNote.ts
375 lines (319 loc) · 8.3 KB
/
useNote.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
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
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 useHeader from './useHeader';
import { getTitle } from '@/infrastructure/utils/note';
/**
* 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>;
/**
* Get the format of note parents
*/
formatNoteParents: () => 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>;
}
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 } = useHeader();
/**
* 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
*/
let noteParents: Note[] = [];
/**
* Load note by id
* @param id - Note identifier got from composable argument
*/
async function load(id: NoteId): Promise<void> {
/**
* @todo try-catch domain errors
*/
const response = await noteService.getNoteById(id);
note.value = response.note;
canEdit.value = response.accessRights.canEdit;
noteTools.value = response.tools;
parentNote.value = response.parentNote;
noteParents = response.parents;
}
/**
* 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;
}
/**
* Reform the received note parents from api into presentation format.
* @returns An array of Note objects representing the formatted note parents.
* @throws {Error} If the note id is not defined.
*/
function formatNoteParents(): Note[] {
if (currentId.value === null) {
throw new Error('note id is not defined');
}
let presentationFormat: Note[] = [];
if (noteParents.length === 0) {
presentationFormat.push({
id: currentId.value,
content: note.value?.content as NoteContent,
});
} else {
presentationFormat = noteParents;
}
return presentationFormat;
}
/**
* Get note by custom hostname
*/
const resolveHostname = async (): Promise<void> => {
note.value = (await noteService.getNoteByHostname(location.hostname)).note;
};
onMounted(() => {
/**
* If we have id, load note
*/
if (currentId.value !== null) {
void load(currentId.value);
}
});
/**
* Reset note to the initial state
*/
function resetNote(): void {
note.value = createDraft();
canEdit.value = true;
lastUpdateContent.value = null;
}
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) => {
formatNoteParents();
patchOpenedPageByUrl(
route.path,
{
title: currentNoteTitle,
url: route.path,
});
});
return {
note,
noteTools,
noteTitle,
canEdit,
resolveHostname,
resolveToolsByContent,
save,
unlinkParent,
formatNoteParents,
parentNote,
};
}