-
Notifications
You must be signed in to change notification settings - Fork 114
/
Editor.vue
547 lines (509 loc) · 19.4 KB
/
Editor.vue
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
<template>
<!-- Loading screen -->
<template v-if="status == 'loading'">
<div class="loading"></div>
</template>
<!-- File missing error (collection) -->
<template v-else-if="status == 'no-file-collection'">
<div class="error h-screen">
<div class="text-center max-w-md">
<h1 class="font-semibold text-2xl mb-2">Nope, file's not here.</h1>
<p class="text-neutral-400 mb-6">It may have moved or been deleted. Make sure as well things are properly configured and that your connection is working.</p>
<div class="flex gap-x-2 justify-center">
<router-link class="btn-primary" :to="{ name: 'content' }">Take me out of here</router-link>
</div>
</div>
</div>
</template>
<!-- File missing error (single file) -->
<template v-else-if="status == 'no-file'">
<div class="error h-screen">
<div class="text-center max-w-md">
<h1 class="font-semibold text-2xl mb-2">The file is missing.</h1>
<p class="text-neutral-400 mb-6">There is no file yet at <code class="text-sm bg-neutral-100 dark:bg-neutral-850 rounded-lg p-1">{{ schema.path }}</code>. Do you want to create one?</p>
<div class="flex gap-x-2 justify-center">
<button class="btn-primary" @click="createSingleFile(schema.path)">Create the file</button>
</div>
</div>
</div>
</template>
<!-- Editor -->
<template v-else>
<!-- Header (navigation + history + actions) -->
<header class="z-50 sticky top-0 bg-white border-b border-neutral-200 dark:bg-neutral-950 dark:border-neutral-750 flex gap-x-1 lg:gap-x-2 items-center py-1 px-2 lg:py-2 lg:px-4">
<router-link v-if="schema && schema.type && (schema.type == 'collection')" :to="{ name: 'content', params: { name: name }, ...(folder != schema.path ? { query: { folder: folder } } : {}) }">
<button class="!hidden lg:!inline-flex btn-secondary ">
<Icon name="ArrowLeft" class="h-4 w-4 stroke-2 shrink-0"/>
<span>{{ schema.label }}</span>
<ul v-if="subfolders.length > 0" class="flex gap-x-2 items-center">
<template v-if="subfolders.length > 2">
<li class="flex gap-x-2 items-center">
<span class="text-neutral-400 dark:text-neutral-500">/</span>
<span class="truncate max-w-20">...</span>
</li>
<li class="flex gap-x-2 items-center">
<span class="text-neutral-400 dark:text-neutral-500">/</span>
<Icon name="Folder" class="h-4 w-4 stroke-2 shrink-0"/>
<span class="truncate max-w-20">{{ subfolders.slice(-1)[0] }}</span>
</li>
</template>
<template v-else>
<li v-for="(subfolder, index) in subfolders" :key="index" class="flex gap-x-2 items-center">
<span class="text-neutral-400 dark:text-neutral-500">/</span>
<Icon name="Folder" class="h-4 w-4 stroke-2 shrink-0"/>
<span class="truncate max-w-20">{{ subfolder }}</span>
</li>
</template>
</ul>
</button>
<button class="lg:hidden btn-icon-secondary">
<Icon name="ArrowLeft" class="h-4 w-4 stroke-2 shrink-0"/>
</button>
</router-link>
<div class="flex gap-x-2 ml-auto items-center">
<template v-if="sha">
<History
:owner="props.owner"
:repo="props.repo"
:branch="props.branch"
:path="currentPath"
:sha="sha"
/>
</template>
<button class="btn-primary" @click.prevent="save" :disabled="(sha && !isModelChanged) || (status === 'validating-config')">
Save
<div class="spinner-white-sm" v-if="status == 'saving'"></div>
</button>
<Dropdown v-if="sha" :dropdownClass="'!max-w-none w-48'">
<template #trigger>
<button class="btn-icon-secondary group-[.dropdown-active]:bg-neutral-100 dark:group-[.dropdown-active]:bg-neutral-850">
<Icon name="MoreVertical" class="h-4 w-4 stroke-2 shrink-0"/>
</button>
</template>
<template #content>
<ul>
<li>
<a :href="`https://github.com/${props.owner}/${props.repo}/blob/${props.branch}/${props.path}`" target="_blank" class="link">
<div>See file on GitHub</div>
<Icon name="ExternalLink" class="h-4 w-4 stroke-2 shrink-0 ml-auto text-neutral-400 dark:text-neutral-500"/>
</a>
</li>
<template v-if="schema && schema.type && (schema.type == 'collection')">
<li><hr class="border-t border-neutral-150 dark:border-neutral-750 my-2"/></li>
<li><button class="link w-full" @click.prevent="renameComponent.openModal()">Rename</button></li>
<li><router-link :to="{ name: 'new', params: { path: currentPath } }" class="link w-full">Make a copy</router-link></li>
<li><button class="link-danger w-full" @click.prevent="deleteComponent.openModal()">Delete</button></li>
</template>
</ul>
</template>
</Dropdown>
</div>
</header>
<!-- Fields -->
<main class="mx-auto p-4 lg:p-8" :class="{ 'max-w-4xl': mode !== 'datagrid'}">
<h1 v-if="displayTitle" class="font-semibold text-2xl lg:text-4xl mb-8">{{ displayTitle }}</h1>
<div v-if="displayDescription" v-html="displayDescription" class="mb-8 prose"></div>
<template v-if="model || model === ''">
<template v-if="['yaml-frontmatter', 'json-frontmatter', 'toml-frontmatter', 'yaml', 'json', 'toml'].includes(mode)">
<template v-if="schema && schema.fields">
<field v-for="field in schema.fields" :key="field.name" :field="field" :model="model" ref="fieldRefs"></field>
</template>
<template v-else>
<CodeMirror v-model="model" :language="extension" :validation="schemaValidation"/>
</template>
</template>
<template v-else-if="mode === 'code'">
<CodeMirror v-model="model" :language="extension" :validation="schemaValidation"/>
</template>
<template v-else-if="mode === 'datagrid'">
<div class="overflow-x-auto">
<Datagrid v-model="model"/>
</div>
</template>
<template v-else>
<textarea rows="20" v-model="model" class="textarea w-full"></textarea>
</template>
</template>
</main>
<!-- Rename modal -->
<Rename
ref="renameComponent"
:owner="props.owner"
:repo="props.repo"
:branch="props.branch"
:path="currentPath"
@file-renamed="handleRenamed"
/>
<!-- Delete modal -->
<Delete
ref="deleteComponent"
:owner="props.owner"
:repo="props.repo"
:branch="props.branch"
:path="currentPath"
:sha="sha"
@file-deleted="handleDeleted"
/>
<!-- Waiting overlay -->
<Teleport to="body">
<div class="waiting" v-show="status == 'saving'"></div>
</Teleport>
</template>
</template>
<script setup>
import { ref, onMounted, watch, computed, inject } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Base64 } from 'js-base64';
import { debounce } from 'lodash';
import YAML from 'yaml';
import notifications from '@/services/notifications';
import github from '@/services/github';
import config from '@/services/config';
import frontmatter from '@/services/frontmatter';
import useSchema from '@/composables/useSchema';
import CodeMirror from '@/components/file/CodeMirror.vue';
import Datagrid from '@/components/file/Datagrid.vue';
import Dropdown from '@/components/utils/Dropdown.vue';
import Icon from '@/components/utils/Icon.vue';
import Field from '@/components/file/Field.vue';
import Delete from '@/components/file/Delete.vue';
import History from '@/components/file/History.vue';
import Rename from '@/components/file/Rename.vue';
const route = useRoute();
const router = useRouter();
const { createModel, sanitizeObject, getSchemaByName, generateFilename, renderDescription } = useSchema();
const emit = defineEmits(['file-saved']);
const repoStore = inject('repoStore', { owner: null, repo: null, branch: null, config: null, details: null });
const props = defineProps({
owner: String,
repo: String,
branch: String,
name: String,
path: String,
config: Object,
title: String,
description: String,
format: String,
isNew: Boolean
});
const schema = ref(null);
const mode = ref(props.format);
const file = ref(null);
const folder = computed(() => {
if (props.isNew && route.query.folder) {
return route.query.folder;
} else if (props.path) {
const pathSegments = props.path.split('/');
pathSegments.pop();
return pathSegments.join('/');
} else {
return schema.value.path;
}
});
const subfolders = computed(() => {
const basePathSegments = schema.value.path.split('/').filter(Boolean);
const currentPathSegments = folder.value.split('/').filter(Boolean);
return currentPathSegments.slice(basePathSegments.length);
});
const extension = ref(null);
const sha = ref(null);
const model = ref(null);
const initialModel = ref(null);
const currentPath = ref(null);
const newPath = ref(null);
const fieldRefs = ref([]);
const renameComponent = ref(null);
const deleteComponent = ref(null);
const status = ref('loading');
const displayTitle = ref('');
const checkValidation = ref(undefined);
const schemaValidation = computed(() => {
if (route.name === 'settings') {
return checkValidation.value ? checkValidation.value : repoStore.config?.validation;
} else {
return undefined;
}
});
const isModelChanged = computed(() => {
return JSON.stringify(sanitizeObject(model.value)) !== JSON.stringify(sanitizeObject(initialModel.value));
});
const displayDescription = computed(() => {
let markdownDescription = '';
if (props.description) {
markdownDescription = props.description;
} else if (schema.value?.description) {
markdownDescription = schema.value?.description;
} else {
return '';
}
return renderDescription(markdownDescription);
});
const createSingleFile = async (path) => {
status.value = 'loading';
const data = await github.saveFile(props.owner, props.repo, props.branch, path, '');
if (data) {
notifications.notify(`The file (${path}) was successfully created.`, 'success');
await setEditor();
status.value = '';
} else {
notifications.notify(`The file (${path}) couldn't be created. Try reloading the page.`, 'error', { delay: 0 });
}
};
const handleRenamed = ({ renamedPath, renamedSha }) => {
// Updating path/history to continue editing
status.value = 'handling-renamed';
router.replace({
name: 'edit',
params: { owner: props.owner, repo: props.repo, branch: props.branch, path: renamedPath }
});
currentPath.value = renamedPath;
// Status get reset in the watcher at the end
};
const handleDeleted = () => {
router.push({ name: 'content', params: { name: props.name } });
};
const resetEditor = () => {
schema.value = null;
mode.value = props.format;
file.value = null;
extension.value = null;
sha.value = null;
model.value = null;
initialModel.value = null;
currentPath.value = (!props.isNew) ? props.path : null;
newPath.value = null;
status.value = 'loading';
displayTitle.value = '';
};
const setDisplayTitle = () => {
if (props.title) {
// If the title is passed as a prop, we use it
displayTitle.value = props.title;
} else if (sha.value) {
// Editing a file
displayTitle.value = model.value?.title ? `Editing "${ model.value.title }"` : 'Editing file';
} else if (props.path) {
// Making a copy of a file
displayTitle.value = `Copy of "${ model.value.title }"`;
} else {
// Creating a new file
displayTitle.value = 'Create a new entry';
}
};
const setEditor = async () => {
resetEditor();
let content = '';
// Retrieve the schema
schema.value = (props.name) ? getSchemaByName(props.config, props.name) : null;
// Retrieve the file
if (props.path) {
file.value = await github.getFile(props.owner, props.repo, props.branch, props.path);
if (!file.value) {
if (schema.value.type === 'file') {
status.value = 'no-file';
} else {
status.value = 'no-file-collection';
}
return;
} else {
sha.value = (props.isNew) ? null : file.value.sha;
content = Base64.decode(file.value.content);
}
}
// Set the extension
if (file.value) {
const parts = file.value.name.split('.');
if (parts.length > 1 && !(parts.length === 2 && parts[0] === '')) {
extension.value = parts.pop().toLowerCase();
}
}
// Define the editor's mode
if (props.format) {
mode.value = props.format;
} else if (schema.value && schema.value.format) {
mode.value = schema.value.format;
} else {
mode.value = 'raw'; // Default mode
const codeExtensions = ['yaml', 'yml', 'javascript', 'js', 'jsx', 'typescript', 'ts', 'tsx', 'json', 'html', 'htm', 'markdown', 'md', 'mdx'];
if (schema.value && schema.value.fields) {
if (extension.value && ['yaml', 'yml'].includes(extension.value)) {
mode.value = 'yaml';
} else if (extension.value === 'json') {
mode.value = 'json';
} else if (extension.value === 'toml') {
mode.value = 'toml';
} else if (schema.value.fields.some(field => field.name === 'body')) {
mode.value = 'yaml-frontmatter';
} else if (codeExtensions.includes(extension.value)) {
mode.value = 'code';
}
} else if (codeExtensions.includes(extension.value)) {
mode.value = 'code';
} else if (extension.value === 'csv' ) {
mode.value = 'datagrid';
}
}
let contentObject = {};
try {
// TODO: Move all YAML/JSON/TOML logic to one service
if (!content.trim()) {
contentObject = {};
} else {
switch (mode.value) {
case 'yaml-frontmatter':
case 'json-frontmatter':
case 'toml-frontmatter':
contentObject = frontmatter.parse(content, { format: mode.value, delimiters: schema.value.delimiters });
break;
case 'yaml':
contentObject = YAML.parse(content, { strict: false });
break;
case 'json':
contentObject = JSON.parse(content);
break;
case 'toml':
const tomlObject = TOML.parse(content, 1.0, '\n', false);
contentObject = JSON.parse(JSON.stringify(tomlObject));
break;
}
}
} catch (error) {
console.error('Error parsing frontmatter:', error);
const options = {
delay: 10000,
actions: [{
label: 'Review settings',
handler: () => router.push({ name: 'settings' }),
primary: true
}]
};
notifications.notify(`Failed to parse the file at "${props.path}", your settings may be wrong. Switching to raw editor.`, 'error', options);
// We can't parse the content, we switch to the raw editor.
mode.value = 'raw';
}
// For YAML and JSON files, if schema.list is true we wrap the model and fields into an extra "listWrapper" object
if (['yaml', 'json'].includes(mode.value) && schema.value && schema.value.fields && schema.value.list) {
schema.value.fields = [{ name: 'listWrapper', type: 'object', list: true, label: false, fields: schema.value.fields }];
contentObject = { listWrapper: contentObject };
}
if (['yaml-frontmatter', 'json-frontmatter', 'toml-frontmatter', 'yaml', 'json', 'toml'].includes(mode.value) && schema.value && schema.value.fields) {
model.value = createModel(schema.value.fields, contentObject);
} else {
model.value = content;
}
initialModel.value = JSON.parse(JSON.stringify(model.value));
setDisplayTitle();
status.value = '';
};
const validateFields = () => {
status.value = 'validating';
let errors = [];
fieldRefs.value.forEach(fieldRef => {
errors.push(...fieldRef.validate());
});
status.value = '';
return errors;
};
const save = async () => {
// We run validation first
const validationErrors = validateFields();
if (validationErrors.length > 0) {
notifications.notify('Uh-oh! Some of your fields have issues. Please check for errors.', 'error');
return;
}
// We're good to go
status.value = 'saving';
let content = JSON.parse(JSON.stringify(model.value));
// For YAML and JSON files with schema.list set to true, we've wrapped the model and fields into an extra "listWrapper" object
if (['yaml', 'json'].includes(mode.value) && schema.value && schema.value.fields && schema.value.list) {
content = model.value.listWrapper;
}
// Sanitize the object and stringify it
content = sanitizeObject(content);
if (Object.keys(content).length === 0) {
// If the object is empty, we just return an empty string
content = '';
} else {
switch (mode.value) {
case 'yaml-frontmatter':
case 'json-frontmatter':
case 'toml-frontmatter':
content = frontmatter.stringify(content, { format: mode.value, delimiters: schema.value.delimiters });
break;
case 'yaml':
content = YAML.stringify(content);
break;
case 'json':
content = JSON.stringify(content, null, 2);
break;
case 'toml':
content = TOML.stringify(content, null, 2);
break;
}
}
try {
// If it's a new file, we need to generate a filename
if (!sha.value) {
const pattern = (schema.value && schema.value.filename) ? schema.value.filename : '{year}-{month}-{day}-{primary}.md';
const filename = generateFilename(pattern, schema.value, model.value);
currentPath.value = `${folder.value}/${filename}`;
}
// Saving the file
const saveData = await github.saveFile(props.owner, props.repo, props.branch, currentPath.value, Base64.encode(content), sha.value, true);
if (!saveData) {
notifications.notify(`Failed to save the file "${currentPath.value}".`, 'error');
status.value = '';
return;
}
currentPath.value = saveData.content.path;
// If we've just created the file, we update the history to point at the edit route
if (!sha.value) {
router.replace({
name: 'edit',
params: { owner: props.owner, repo: props.repo, branch: props.branch, path: currentPath.value }
});
}
// Updating values to continue editing
sha.value = saveData.content.sha;
initialModel.value = JSON.parse(JSON.stringify(model.value));
setDisplayTitle();
notifications.notify(`Saved "${currentPath.value}"`, 'success');
emit('file-saved', currentPath.value);
if (route.name === 'settings') {
// We've updated the configuration, we need to reload it
await config.set(props.owner, props.repo, props.branch);
}
status.value = '';
} catch (error) {
notifications.notify(`Failed to save the file "${currentPath.value}"`, 'error');
}
};
onMounted(async () => {
await setEditor();
});
watch(() => route.path, async () => {
if (status.value === 'handling-renamed') {
status.value = '';
} else {
await setEditor();
}
});
const checkConfig = debounce(
async () => {
({ validation: checkValidation.value } = await config.parse(props.owner, props.repo, props.branch, model.value));
status.value = '';
},
500
);
watch(() => model.value, (newValue, oldValue) => {
if (route.name === 'settings') {
if (JSON.stringify(newValue) === JSON.stringify(initialModel.value)) {
checkValidation.value = undefined;
status.value = '';
} else {
status.value = 'validating-config';
checkConfig();
}
}
}, { deep: true });
</script>