generated from shgysk8zer0/npm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmd-editor.js
More file actions
401 lines (337 loc) · 10.1 KB
/
md-editor.js
File metadata and controls
401 lines (337 loc) · 10.1 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
import { parse, createStyleSheet } from '@aegisjsproject/markdown';
import { registerComponent } from '@aegisjsproject/core/componentRegistry.js';
import { html } from '@aegisjsproject/core/parsers/html.js';
import { css } from '@aegisjsproject/core/parsers/css.js';
import { componentBase, componentDarkTheme, componentLightTheme } from '@aegisjsproject/styles/theme.js';
import { btn, btnSecondary, btnDanger } from '@aegisjsproject/styles/button.js';
const styles = css`:host(:not([hidden]):not([popover])) {
display: inline-block;
}
:host {
resize: both;
overflow: scroll;
font-size: 1rem;
}
#container, pre {
max-width: 100%;
overflow: auto;
}
#toolbar {
position: sticky;
top: 0;
width: 100%;
margin: 0;
background-color: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(4px);
}
#toolbar > li {
list-style: none;
display: inline-block;
}
#editor, #viewer {
min-height: 2em;
padding: 0.8em;
}
#editor:empty::before {
display: inline;
content: "Enter markdown content here";
}
.icon {
width: 1em;
height: 1em;
vertical-align: baseline;
}
@media (max-width: 800px) {
.mobile-hidden {
display: none;
}
}`;
const template = html`<div id="container" part="container">
<menu id="toolbar" role="toolbar" part="menubar" aria-label="Markdown Editor Views">
<li>
<button type="button" role="menuitem" id="editor-btn" class="btn btn-secondary" part="btn view-editor" data-mode="editor" title="Switch to Editor View" aria-label="Switch to Editor View" disabled="">
<slot name="editor-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16" part="btn-icon" class="icon" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M8.5 1H1c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4.5L8.5 1zM11 14H1V2h7l3 3v9zM5 6.98L3.5 8.5 5 10l-.5 1L2 8.5 4.5 6l.5.98zM7.5 6L10 8.5 7.5 11l-.5-.98L8.5 8.5 7 7l.5-1z"/>
</svg>
</slot>
<span part="btn-label" class="mobile-hidden">
<slot name="editor-label">Editor</slot>
</span>
</button>
</li>
<li>
<button type="button" role="menuitem" id="viewer-btn" class="btn btn-secondary" part="btn view-viewer" data-mode="viewer" title="Switch to Viewer Mode" aria-label="Switch to Viewer Mode">
<slot name="viewer-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" part="btn-icon" class="icon" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/>
</svg>
<span part="btn-label" class="mobile-hidden">
<slot name="viewer-label">Viewer</slot>
</span>
</button>
</li>
</menu>
<pre id="editor" part="editor" contenteditable="true" role="textarea"></pre>
<div id="viewer" part="viewer" hidden=""></div>
</div>`;
class HTMLMarkdownEditorElement extends HTMLElement {
#shadow = this.attachShadow({ mode: 'closed', delegatesFocus: true });
#internals = this.attachInternals();
#disabled = false;
#hasUpdated = false;
constructor() {
super();
this.#shadow.adoptedStyleSheets = [componentBase, componentLightTheme, componentDarkTheme, btn, btnSecondary, btnDanger, styles];
this.#shadow.append(
createStyleSheet('github', { media: '(prefers-color-scheme: light)' }),
createStyleSheet('github-dark', { media: '(prefers-color-scheme: dark)' }),
template.cloneNode(true)
);
this.#shadow.getElementById('toolbar').addEventListener('click', ({ target }) => {
if (target.matches('button, button *')) {
const btn = target.closest('button');
this.mode = btn.dataset.mode;
}
});
this.#editor.addEventListener('input', event => {
const target = event.target;
queueMicrotask(() => this.#setValue(target.innerText.trim()));
this.#hasUpdated = true;
}, { passive: true });
this.addEventListener('blur', () => {
if (this.#hasUpdated) {
this.dispatchEvent(new Event('change'));
this.#hasUpdated = false;
}
}, { passive: true });
this.#internals.role = 'textbox';
this.#internals.ariaMultiLine = 'true';
this.addEventListener('focus', () => {
if (this.mode !== 'editor') {
this.mode = 'editor';
}
this.#editor.focus();
}, { passive: true });
}
async attributeChangedCallback(attr, oldVal, newVal) {
if (oldVal !== newVal) {
const editor = this.#editor;
const viewer = this.#viewer;
switch(attr) {
case 'mode':
if (newVal === 'viewer') {
await this.#render();
editor.hidden = true;
viewer.hidden = false;
this.#internals.role = 'document';
this.#internals.ariaMultiLine = 'false';
this.#shadow.getElementById('viewer-btn').disabled = true;
this.#shadow.getElementById('editor-btn').disabled = false;
viewer.ariaLive = 'polite';
} else {
editor.hidden = false;
viewer.hidden = true;
this.#internals.role = 'textbox';
this.#internals.ariaMultiLine = 'true';
this.#shadow.getElementById('viewer-btn').disabled = false;
this.#shadow.getElementById('editor-btn').disabled = true;
viewer.ariaLive = null;
editor.focus();
}
break;
case 'required':
if (typeof newVal === 'string' && this.value.length === 0) {
this.#internals.setValidity({ valueMissing: true }, 'This is a required field.', this.#editor);
}
break;
case 'readonly':
this.#editor.contentEditable = (this.#disabled || typeof newVal === 'string') ? 'false' : 'true';
break;
}
}
}
connectedCallback() {
if (this.#editor.textContent.length === 0) {
this.#getInitialValue();
}
}
formDisabledCallback(disabled) {
this.#disabled = disabled;
this.#editor.contentEditable = (disabled || this.readOnly) ? 'false' : 'true';
}
formResetCallback() {
if (! this.#getInitialValue()) {
this.value = '';
}
}
formStateRestoreCallback(value) {
this.value = value;
}
get disabled() {
return this.hasAttribute('disabled');
}
set disabled(val) {
this.toggleAttribute('disabled', val);
}
get form() {
return this.#internals.form;
}
get labels() {
return this.#internals.labels;
}
get maxLength() {
if (this.hasAttribute('maxlength')) {
return Math.max(parseInt(this.getAttribute('maxlength'), -1)) || -1;
} else {
return -1;
}
}
set maxLength(val) {
if (typeof val === 'string') {
this.maxLength = parseInt(val);
} else if (Number.isSafeInteger(val) && val > -1) {
this.setAttribute('maxlength', val);
} else {
this.removeAttribute('maxlength');
}
}
get minLength() {
if (this.hasAttribute('minlength')) {
return Math.max(parseInt(this.getAttribute('minlength'), 0)) || -1;
} else {
return -1;
}
}
set minLength(val) {
if (typeof val === 'string') {
this.minLength = parseInt(val);
} else if (Number.isSafeInteger(val) && val > -1) {
this.setAttribute('minlength', val);
} else {
this.removeAttribute('minlength');
}
}
get mode() {
return this.getAttribute('mode') ?? 'editor';
}
set mode(val) {
if (typeof val !== 'string') {
this.removeAttribute('mode');
} else if (! ['editor', 'viewer'].includes(val)) {
throw new TypeError(`Invalid view option: "${val}".`);
} else {
this.setAttribute('mode', val);
}
}
get name() {
return this.getAttribute('name');
}
set name(val) {
if (typeof val === 'string') {
this.setAttribute('name', val);
} else {
this.removeAttribute('name');
}
}
get readOnly() {
return this.hasAttribute('readonly');
}
set readOnly(val) {
this.toggleAttribute('readonly', val);
}
get required() {
return this.hasAttribute('required');
}
set required(val) {
this.toggleAttribute('required', val);
}
get validationMessage() {
return this.#internals.validationMessage;
}
get validity() {
return this.#internals.validity;
}
get value() {
return this.#editor.innerText;
}
set value(val) {
if (typeof val !== 'string') {
throw new TypeError('Cannot set markdown content to non-string.');
} else {
this.#editor.innerText = val;
this.#setValue(val);
if (this.mode === 'viewer') {
this.#render();
}
}
}
get willValidate() {
return this.#internals.willValidate;
}
get html() {
return parse(this.value);
}
get #editor() {
return this.#shadow.getElementById('editor');
}
get #viewer() {
return this.#shadow.getElementById('viewer');
}
checkValidity() {
return this.#internals.checkValidity();
}
reportValidity() {
return this.#internals.reportValidity();
}
toBlob({ lastModified } = {}) {
return new Blob([this.value], { type: 'text/markdown', lastModified });
}
toFile(name, { lastModified } = {}) {
return new File([this.value], name, { type: 'text/markdown', lastModified });
}
async importBlob(blob) {
if (! (blob instanceof Blob)) {
throw new TypeError('Cannot import from non-blob object.');
} else {
const md = await blob.text();
this.value = md;
return md;
}
}
async #render() {
await scheduler.yield();
this.#viewer.replaceChildren(this.html);
}
#setValue(val) {
this.#internals.setFormValue(val);
const { required, minLength, maxLength } = this;
const anchor = this.#editor;
if (required && val.trim().length === 0) {
this.#internals.setValidity({ valueMissing: true }, 'This is a required field.', anchor);
} else if (val.length < minLength) {
this.#internals.setValidity({ tooShort: true }, `This requires a length of at least ${minLength} characters`, anchor);
} else if (maxLength > -1 && val.length > maxLength) {
this.#internals.setValidity({ tooLong: true }, `This requires a length of at most ${maxLength} characters`, anchor);
} else {
this.#internals.setValidity({});
}
}
#getInitialValue() {
if (this.textContent.length !== 0) {
const content = this.textContent.startsWith('\n') ? String.dedent(this.textContent).trim() : this.textContent.trim();
this.#editor.textContent = content;
this.#setValue(content);
return true;
} else {
return false;
}
}
static get formAssociated() {
return true;
}
static get observedAttributes() {
return ['mode', 'readonly', 'required'];
}
}
registerComponent('md-editor', HTMLMarkdownEditorElement);