-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathNcRichText.vue
605 lines (564 loc) · 14.4 KB
/
NcRichText.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
<!--
- SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<docs>
### General description
This component displays rich text with optional autolink or [Markdown support](https://www.markdownguide.org/basic-syntax/).
```vue
<template>
<div>
<textarea v-model="text" />
<NcCheckboxRadioSwitch :checked.sync="autolink" type="checkbox">Autolink</NcCheckboxRadioSwitch>
<NcCheckboxRadioSwitch :checked.sync="useMarkdown" type="checkbox">Use Markdown</NcCheckboxRadioSwitch>
<NcRichText
:class="{'plain-text': !useMarkdown }"
:text="text" :autolink="autolink" :arguments="args"
:use-markdown="useMarkdown" />
</div>
</template>
<script>
export default {
data() {
return {
text: `## Hello everyone 🎉
The file {file} was added by {username}. Visit https://nextcloud.com to check it!
Some examples for markdown syntax:
1. **bold text**
2. _italic text_
3. example of \`inline code\`
> blockquote example
`,
autolink: true,
useMarkdown: true,
args: {
file: 'MyDocument.odt',
username: {
component: 'NcUserBubble',
props: {
displayName: 'Jane Doe'
}
}
},
}
},
}
</script>
<style lang="scss">
textarea {
width: 100%;
height: 200px;
}
.plain-text {
white-space: pre-line;
}
</style>
```
### Flavored Markdown
This component can support [Github Flavored Markdown](https://github.github.com/gfm/).
It adds such elements, as tables, task lists, strikethrough, and supports code syntax highlighting and autolinks by default
It is also possible to make a rendered content interactive and listen for events
```vue
<template>
<div>
<textarea v-model="text" />
<NcRichText :text="text"
:use-extended-markdown="true"
:interactive="true"
@interact:todo="handleInteraction"/>
</div>
</template>
<script>
export default {
data() {
return {
text: `## Try flavored markdown right now!
~~strikethrough~~
- [ ] task to be done
- [x] task completed
Table header | Column A | Column B
-- | -- | --
Table row | value A | value B
---
\`\`\`js
const GenRandomId = (length) => {
\treturn Math.random()
\t\t.toString(36)
\t\t.replace(/[^a-z]+/g, '')
\t\t.slice(0, length || 5)
}
\`\`\`
`,
}
},
methods: {
handleInteraction(id) {
const parentId = id.split('-markdown-input-')[0]
const index = Array.from(document.querySelectorAll(`span[id^="${parentId}-markdown-input-"]`)).findIndex((el) => el.id.includes(id))
if (index === -1 ) {
return
}
let checkBoxIndex = 0
let lines = this.text.split('\n')
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes('[ ]') || lines[i].includes('[x]')) {
if (checkBoxIndex === index) {
const isChecked = lines[i].includes('[x]')
if (isChecked) {
lines[i] = lines[i].replace('[x]', '[ ]')
} else {
lines[i] = lines[i].replace('[ ]', '[x]')
}
break
}
checkBoxIndex++
}
}
this.text = lines.join('\n')
},
},
}
</script>
<style lang="scss">
textarea {
width: 100%;
height: 200px;
}
</style>
```
### Usage with NcRichContenteditable
See [NcRichContenteditable](#/Components/NcRichContenteditable) documentation for more information
```vue
<template>
<div>
<NcRichContenteditable :value.sync="message"
:auto-complete="autoComplete"
:maxlength="100"
:user-data="userData"
placeholder="Try mentioning user @Test01 or inserting emoji :smile"
@submit="onSubmit" />
<NcCheckboxRadioSwitch :checked.sync="autolink" type="checkbox">Autolink</NcCheckboxRadioSwitch>
<NcCheckboxRadioSwitch :checked.sync="useMarkdown" type="checkbox">Use Markdown</NcCheckboxRadioSwitch>
<NcCheckboxRadioSwitch :checked.sync="useExtendedMarkdown" type="checkbox">Use extended Markdown</NcCheckboxRadioSwitch>
<NcRichText :text="text"
:autolink="autolink"
:arguments="userMentions"
:use-markdown="useMarkdown"
:use-extended-markdown="useExtendedMarkdown" />
</div>
</template>
<script>
export default {
data() {
return {
message: '',
autolink: true,
useMarkdown: true,
useExtendedMarkdown: true,
userData: {
Test01: {
icon: 'icon-user',
id: 'Test01',
label: 'Test01',
source: 'users',
primary: true,
},
Test02: {
icon: 'icon-user',
id: 'Test02',
label: 'Test02',
source: 'users',
status: {
clearAt: null,
icon: '🎡',
message: 'Visiting London',
status: 'away',
},
subline: 'Visiting London',
},
'Test@User': {
icon: 'icon-user',
id: 'Test@User',
label: 'Test 03',
source: 'users',
status: {
clearAt: null,
icon: '🎡',
message: 'Having space in my name',
status: 'online',
},
subline: 'Visiting London',
},
'Test Offline': {
icon: 'icon-user',
id: 'Test Offline',
label: 'Test Offline',
source: 'users',
status: {
clearAt: null,
icon: null,
message: null,
status: 'offline',
},
subline: null,
},
'Test DND': {
icon: 'icon-user',
id: 'Test DND',
label: 'Test DND',
source: 'users',
status: {
clearAt: null,
icon: null,
message: 'Out sick',
status: 'dnd',
},
subline: 'Out sick',
},
},
userMentions: {
'user-1': {
component: 'NcUserBubble',
props: {
displayName: 'Test01',
user: 'Test01',
primary: true,
},
},
'user-2': {
component: 'NcUserBubble',
props: {
displayName: 'Test02',
user: 'Test02',
},
},
'user-3': {
component: 'NcUserBubble',
props: {
displayName: 'Test 03',
user: 'Test@User',
},
},
'user-4': {
component: 'NcUserBubble',
props: {
displayName: 'Test Offline',
user: 'Test Offline',
},
},
'user-5': {
component: 'NcUserBubble',
props: {
displayName: 'Test DND',
user: 'Test DND',
},
},
},
}
},
computed: {
text() {
return this.message
.replace('@Test01', '{user-1}')
.replace('@Test02', '{user-2}')
.replace('@Test@User', '{user-3}')
.replace('@"Test Offline"', '{user-4}')
.replace('@"Test DND"', '{user-5}')
},
},
methods: {
autoComplete(search, callback) {
callback(Object.values(this.userData))
},
onSubmit() {
alert(this.message)
}
}
}
</script>
```
</docs>
<script>
import { ref } from 'vue'
import NcReferenceList from './NcReferenceList.vue'
import NcCheckboxRadioSwitch from '../NcCheckboxRadioSwitch/NcCheckboxRadioSwitch.vue'
import { getRoute, remarkAutolink } from './autolink.js'
import { remarkPlaceholder, prepareTextNode } from './placeholder.js'
import GenRandomId from '../../utils/GenRandomId.js'
import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkGfm from 'remark-gfm'
import breaks from 'remark-breaks'
import remark2rehype from 'remark-rehype'
import rehype2react from 'rehype-react'
import rehypeExternalLinks from 'rehype-external-links'
import { RouterLink } from 'vue-router'
/**
* Heavy libraries should be loaded on demand to reduce component size
*/
let rehypeHighlight
const rehypeHighlightLoaded = ref(false)
/**
* Load 'rehype-highlight' library when code block is rendered with `useExtendedMarkdown`
*/
async function importRehypeLibrary() {
const module = await import('rehype-highlight')
rehypeHighlight = module.default
rehypeHighlightLoaded.value = true
}
export default {
name: 'NcRichText',
components: {
NcReferenceList,
},
props: {
text: {
type: String,
default: '',
},
arguments: {
type: Object,
default: () => {
return {}
},
},
referenceLimit: {
type: Number,
default: 0,
},
referenceInteractive: {
type: Boolean,
default: true,
},
referenceInteractiveOptIn: {
type: Boolean,
default: false,
},
/** Provide data upfront to avoid extra http request */
references: {
type: Object,
default: null,
},
markdownCssClasses: {
type: Object,
default: () => {
return {
a: 'rich-text--external-link',
ol: 'rich-text--ordered-list',
ul: 'rich-text--un-ordered-list',
li: 'rich-text--list-item',
strong: 'rich-text--strong',
em: 'rich-text--italic',
h1: 'rich-text--heading rich-text--heading-1',
h2: 'rich-text--heading rich-text--heading-2',
h3: 'rich-text--heading rich-text--heading-3',
h4: 'rich-text--heading rich-text--heading-4',
h5: 'rich-text--heading rich-text--heading-5',
h6: 'rich-text--heading rich-text--heading-6',
hr: 'rich-text--hr',
table: 'rich-text--table',
pre: 'rich-text--pre',
code: 'rich-text--code',
blockquote: 'rich-text--blockquote',
}
},
},
useMarkdown: {
type: Boolean,
default: false,
},
/** Provide GitHub Flavored Markdown syntax */
useExtendedMarkdown: {
type: Boolean,
default: false,
},
/** Provide event from rendered markdown inputs */
interactive: {
type: Boolean,
default: false,
},
autolink: {
type: Boolean,
default: true,
},
},
emits: ['interact:todo'],
data() {
return {
parentId: GenRandomId(5),
}
},
methods: {
renderPlaintext(h) {
const context = this
const placeholders = this.text.split(/(\{[a-z\-_.0-9]+\})/ig).map(function(entry, index, list) {
const matches = entry.match(/^\{([a-z\-_.0-9]+)\}$/i)
// just return plain string nodes as text
if (!matches) {
return prepareTextNode({ h, context }, entry)
}
// return component instance if argument is an object
const argumentId = matches[1]
const argument = context.arguments[argumentId]
if (typeof argument === 'object') {
const { component, props } = argument
return h(component, {
props,
class: 'rich-text--component',
})
}
if (argument) {
return h('span', { class: 'rich-text--fallback' }, argument)
}
return entry
})
return h('div', { class: 'rich-text--wrapper' }, [
h('div', {}, placeholders.flat()),
this.referenceLimit > 0
? h('div', { class: 'rich-text--reference-widget' }, [
h(NcReferenceList, {
props: {
text: this.text,
referenceData: this.references,
interactive: this.referenceInteractive,
interactiveOptIn: this.referenceInteractiveOptIn,
},
}),
])
: null,
])
},
renderMarkdown(h) {
const renderedMarkdown = unified()
.use(remarkParse)
.use(remarkAutolink, {
autolink: this.autolink,
useMarkdown: this.useMarkdown,
useExtendedMarkdown: this.useExtendedMarkdown,
})
.use(this.useExtendedMarkdown ? remarkGfm : undefined)
.use(breaks)
.use(remark2rehype, {
handlers: {
component(toHast, node) {
return toHast(node, node.component, { value: node.value })
},
},
})
.use((this.useExtendedMarkdown && rehypeHighlightLoaded.value) ? rehypeHighlight : undefined)
// .use(rehypeAddClasses, this.markdownCssClasses)
.use(remarkPlaceholder)
.use(rehypeExternalLinks, {
target: '_blank',
rel: ['noopener noreferrer'],
})
.use(rehype2react, {
createElement: (tag, attrs, children) => {
// unescape special symbol "<" for simple text nodes
children = children?.map(child => typeof child === 'string'
? child.replace(/</gmi, '<')
: child,
)
if (!tag.startsWith('#')) {
if (this.useExtendedMarkdown) {
if (tag === 'code' && !rehypeHighlightLoaded.value) {
importRehypeLibrary()
}
let nestedNode = null
if (tag === 'li' && Array.isArray(children)
&& children[0].tag === 'input'
&& children[0].data.attrs.type === 'checkbox') {
const [inputNode, ...labelParts] = children
const nestedNodeIndex = labelParts.findIndex((child) => ['ul', 'ol', 'li', 'blockquote', 'pre'].includes(child.tag))
if (nestedNodeIndex !== -1) {
nestedNode = labelParts[nestedNodeIndex]
labelParts.splice(nestedNodeIndex)
}
const id = this.parentId + '-markdown-input-' + GenRandomId(5)
const inputComponent = h(NcCheckboxRadioSwitch, {
attrs: {
...inputNode.data.attrs,
id,
disabled: !this.interactive,
},
on: {
'update:checked': () => {
this.$emit('interact:todo', id)
},
},
}, labelParts)
return h(tag, attrs, [inputComponent, nestedNode])
}
}
if (tag === 'a') {
const route = getRoute(this.$router, attrs.attrs.href)
if (route) {
delete attrs.attrs.href
delete attrs.attrs.target
return h(RouterLink, {
...attrs,
props: {
to: route,
},
}, children)
}
}
return h(tag, attrs, children)
}
const placeholder = this.arguments[tag.slice(1)]
if (!placeholder) {
return h('span', { ...{ attrs }, ...{ class: 'rich-text--fallback' } }, [`{${tag.slice(1)}}`])
}
if (!placeholder.component) {
return h('span', attrs, [placeholder])
}
return h(
placeholder.component,
{
attrs,
props: placeholder.props,
class: 'rich-text--component',
},
children,
)
},
prefix: false,
})
.processSync(this.text
// escape special symbol "<" to not treat text as HTML
.replace(/</gmi, '<')
// unescape special symbol ">" to parse blockquotes
.replace(/>/gmi, '>'),
)
.result
return h('div', { class: 'rich-text--wrapper rich-text--wrapper-markdown' }, [
renderedMarkdown,
this.referenceLimit > 0
? h('div', { class: 'rich-text--reference-widget' }, [
h(NcReferenceList, {
props: {
text: this.text,
referenceData: this.references,
interactive: this.referenceInteractive,
interactiveOptIn: this.referenceInteractiveOptIn,
},
}),
])
: null,
])
},
},
render(h) {
return this.useMarkdown || this.useExtendedMarkdown
? this.renderMarkdown(h)
: this.renderPlaintext(h)
},
}
</script>
<style lang="scss" scoped>
/* stylelint-disable-next-line scss/at-import-partial-extension */
@import './richtext.scss';
a:not(.rich-text--component) {
text-decoration: underline;
}
</style>