-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuseNote.ts
More file actions
324 lines (278 loc) · 7.26 KB
/
useNote.ts
File metadata and controls
324 lines (278 loc) · 7.26 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
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';
/**
* 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>;
/**
* 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, 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();
/**
* 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);
/**
* 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;
} catch (error) {
deleteOpenedPageByUrl(route.path);
if (error instanceof DomainError) {
void router.push(`/error/${error.statusCode}`);
} else {
void router.push('/error/500');
}
}
}
/**
* 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);
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;
}
/**
* 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;
}
/**
* 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;
}
void load(newId);
});
watch(noteTitle, (currentNoteTitle) => {
patchOpenedPageByUrl(
route.path,
{
title: currentNoteTitle,
url: route.path,
});
});
return {
note,
noteTools,
noteTitle,
canEdit,
resolveHostname,
resolveToolsByContent,
save,
unlinkParent,
parentNote,
};
}