-
Notifications
You must be signed in to change notification settings - Fork 133
/
Block.vue
493 lines (463 loc) · 15.8 KB
/
Block.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
<template>
<div class="group flex w-full rounded"
:class="{
// Add top margin for headings
'pt-12 first:pt-0': block.type === BlockType.H1,
'pt-4 first:pt-0': block.type === BlockType.H2,
}">
<div class="h-full px-2 pl-4 py-1.5 text-center cursor-pointer transition-all duration-150 text-neutral-300 flex"
:class="{
'py-3.5': block.type === BlockType.H1,
'py-3': block.type === BlockType.H2,
'py-2.5': block.type === BlockType.H3,
}">
<Tooltip value="<span class='text-neutral-400'><span class='text-white'>Click</span> to delete block</span>">
<v-icon name="hi-trash" @click="emit('deleteBlock')"
class="w-6 h-6 hover:bg-neutral-100 hover:text-neutral-400 p-0.5 rounded group-hover:opacity-100 opacity-0" />
</Tooltip>
<Tooltip value="<span class='text-neutral-400'><span class='text-white'>Click</span> to add block below</span>">
<v-icon name="hi-plus" @click="emit('newBlock')"
class="w-6 h-6 hover:bg-neutral-100 hover:text-neutral-400 p-0.5 rounded group-hover:opacity-100 opacity-0" />
</Tooltip>
<BlockMenu ref="menu"
@setBlockType="type => emit('setBlockType', type)"
@clearSearch="clearSearch"
/>
</div>
<div class="w-full relative" :class="{ 'px-4 sm:px-0': block.type !== BlockType.Divider }">
<!-- Actual content -->
<component :is="BlockComponents[props.block.type]" ref="content"
:block="block"
@keydown.capture="keyDownHandler"
@keyup="parseMarkdown" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, PropType } from 'vue'
import { Block, BlockType, BlockComponents } from '@/utils/types'
import BlockMenu from './BlockMenu.vue'
import Tooltip from './elements/Tooltip.vue'
const props = defineProps({
block: {
type: Object as PropType<Block>,
default: {
type: BlockType.Text,
details: {},
},
},
})
const emit = defineEmits([
'deleteBlock',
'newBlock',
'moveToPrevChar',
'moveToNextChar',
'moveToPrevLine',
'moveToNextLine',
'merge',
'split',
'setBlockType',
])
function getFirstChild () {
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote) {
if ((content.value as any).$el.firstChild.firstChild.childNodes.length > 1) {
return (content.value as any).$el.firstChild.firstChild.firstChild
} else {
return (content.value as any).$el.firstChild.firstChild.firstChild
}
} else {
if ((content.value as any).$el) return (content.value as any).$el.firstChild || content.value.$el
else return (content.value as any).firstChild || content.value
}
}
function getLastChild () {
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote) {
if ((content.value as any).$el.firstChild.firstChild.childNodes.length > 1) {
return (content.value as any).$el.firstChild.firstChild.lastChild
} else {
return (content.value as any).$el.firstChild.firstChild.firstChild
}
} else {
if ((content.value as any).$el) return (content.value as any).$el.firstChild || content.value.$el
else return (content.value as any).firstChild || content.value
}
}
function getInnerContent () {
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote) {
return (content.value as any).$el.firstChild.firstChild.firstChild
} else {
return (content.value as any).$el.firstChild
}
}
function getTextContent () {
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote || props.block.type === BlockType.H1) {
return content.value.$el.querySelector('.ProseMirror').editor.getText()
}
const innerContent = getInnerContent()
if (innerContent) return innerContent.parentElement ? innerContent.parentElement.textContent : innerContent.textContent
else return ''
}
function getHtmlContent () {
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote || props.block.type === BlockType.H1) {
return content.value.$el.querySelector('.ProseMirror').editor.getHTML()
}
const innerContent = getInnerContent()
if (innerContent) return innerContent.parentElement.innerHTML
else return ''
}
function keyDownHandler (event:KeyboardEvent) {
if (event.key === 'ArrowUp') {
if (menu.value?.open) {
event.preventDefault()
}
// If at first line, move to previous block
else if (atFirstLine()) {
event.preventDefault()
emit('moveToPrevLine')
}
} else if (event.key === 'ArrowDown') {
if (menu.value?.open) {
event.preventDefault()
}
// If at last line, move to next block
else if (atLastLine()) {
event.preventDefault()
emit('moveToNextLine')
}
} else if (event.key === 'ArrowLeft') {
// If at first character, move to previous block
if (atFirstChar()) {
event.preventDefault()
emit('moveToPrevChar')
}
} else if (event.key === 'ArrowRight') {
// If at last character, move to next block
if (atLastChar()) {
event.preventDefault()
emit('moveToNextChar')
}
} else if (event.key === 'Backspace' && highlightedLength() === 0) {
if (!(menu.value && menu.value.open) && atFirstChar()) {
event.preventDefault()
emit('merge')
}
} else if (event.key === 'Enter') {
event.preventDefault()
if (!(menu.value && menu.value.open)) {
emit('split')
}
}
}
function isContentBlock () {
return [BlockType.Text, BlockType.Quote, BlockType.H1, BlockType.H2, BlockType.H3].includes(props.block.type)
}
const content = ref<any>(null)
const menu = ref<typeof BlockMenu|null>(null)
function atFirstChar () {
const startCoord = getStartCoordinates()
const coord = getCaretCoordinates()
return coord?.x === startCoord.x && coord?.y === startCoord.y
}
function atLastChar () {
const endCoord = getEndCoordinates()
const coord = getCaretCoordinates()
return coord?.x === endCoord.x && coord?.y === endCoord.y
}
function atFirstLine () {
const startCoord = getStartCoordinates()
const coord = getCaretCoordinates()
return coord?.y === startCoord.y
}
function atLastLine () {
const endCoord = getEndCoordinates()
const coord = getCaretCoordinates()
return coord?.y === endCoord.y
}
function highlightedLength () {
return window.getSelection()?.toString().length
}
function moveToStart () {
if (isContentBlock()) {
const firstChild = getFirstChild()
if (firstChild) {
const selection = window.getSelection()
const range = document.createRange()
range.selectNodeContents(firstChild)
range.collapse(true)
selection?.removeAllRanges()
selection?.addRange(range)
}
} else {
emit('moveToNextChar')
}
}
function moveToEnd () {
if (isContentBlock()) {
const lastChild = getLastChild()
if (lastChild) {
const selection = window.getSelection()
const range = document.createRange()
range.selectNodeContents(lastChild)
range.collapse()
selection?.removeAllRanges()
selection?.addRange(range)
}
} else {
emit('moveToPrevChar')
}
}
async function moveToFirstLine () {
if (isContentBlock()) {
const textContent = getTextContent()
if (!textContent) {
moveToStart()
} else {
let prevCoord = getCaretCoordinates()
let prevDist = 99999
let caretPos = 1
while (true) {
setCaretPos(caretPos)
const newCoord = getCaretCoordinates()
const newDist = Math.abs((newCoord?.x as number) - (prevCoord?.x as number))
if (newDist > prevDist) {
if (caretPos > 0) setCaretPos(caretPos - 1)
break
} else if (caretPos === textContent.length || caretPos > 999) {
// Reached end of line
break
} else {
prevDist = newDist
caretPos += 1
}
}
}
} else {
emit('moveToNextLine')
}
}
async function moveToLastLine () {
if (isContentBlock()) {
const textContent = getTextContent()
if (!textContent) {
moveToStart()
} else {
let prevCoord = getCaretCoordinates()
let prevDist = 99999
let caretPos = textContent.length
while (true) {
setCaretPos(caretPos)
const newCoord = getCaretCoordinates()
const newDist = Math.abs((newCoord?.x as number) - (prevCoord?.x as number))
if (newDist > prevDist) {
if (caretPos < textContent.length) setCaretPos(caretPos + 1)
break
} else if (caretPos === 0) {
// Reached start of line
break
} else {
prevDist = newDist
caretPos -= 1
}
}
}
} else {
emit('moveToPrevLine')
}
}
function getCaretCoordinates () {
let x = 0, y = 0
const selection = window.getSelection()
if ((selection?.rangeCount as number) > 0) {
const range = selection?.getRangeAt(0)
if (range?.startContainer.firstChild) {
const newRange = document.createRange()
newRange.selectNodeContents(range.startContainer.firstChild)
newRange.collapse(true)
const rect = newRange.getBoundingClientRect()
return rect
}
const rect = range?.getBoundingClientRect()
return rect
}
return { x, y }
}
function getCaretPos () {
const selection = window.getSelection()
if (selection) {
let selectedNode = selection.anchorNode
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote) {
let offsetNode, offset = 0, tag = null
if (['STRONG', 'EM'].includes(selectedNode?.parentElement?.tagName as string)) {
selectedNode = selectedNode?.parentElement as Node
tag = (selectedNode as HTMLElement).tagName.toLowerCase()
}
// Edge case when character length is 1
if (selectedNode !== null && selectedNode.childNodes.length > 0) {
if (selectedNode.childNodes[0].textContent && selectedNode.childNodes[0].textContent.length <= 1)
selectedNode = selectedNode.childNodes[0];
}
for (const [i, node] of (content.value as any).$el.firstChild.firstChild.childNodes.entries()) {
if (node === selectedNode) {
offsetNode = node
if (node.tagName) offset += 2 + node.tagName.length
break
}
if (node.tagName) offset += node.outerHTML.length
else offset += node.textContent.length
offsetNode = node
}
return { pos: offset + selection.anchorOffset + (selectedNode?.parentElement?.tagName === 'P' ? 3 : 0), tag }
} else {
return { pos: selection.anchorOffset + (selectedNode?.parentElement?.tagName === 'H1' ? 4 : 0) }
}
} else {
return { pos: 0 }
}
}
function getCaretPosWithoutTags () {
const selection = window.getSelection()
if (selection) {
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote) {
let offsetNode, offset = 0, tag = null
let selectedNode = selection.anchorNode
if (['STRONG', 'EM'].includes(selectedNode?.parentElement?.tagName as string)) {
selectedNode = selectedNode?.parentElement as Node
tag = (selectedNode as HTMLElement).tagName.toLowerCase()
}
// Edge case when character length is 1
if (selectedNode !== null && selectedNode.childNodes.length > 0) {
if (selectedNode.childNodes[0].textContent && selectedNode.childNodes[0].textContent.length <= 1)
selectedNode = selectedNode.childNodes[0];
}
for (const [i, node] of (content.value as any).$el.firstChild.firstChild.childNodes.entries()) {
if (node === selectedNode) {
offsetNode = node
break
}
offset += node.textContent.length
offsetNode = node
}
return { pos: offset + selection.anchorOffset, tag }
} else {
return { pos: selection.anchorOffset }
}
} else {
return { pos: 0 }
}
}
function setCaretPos (caretPos:number) {
const innerContent = getInnerContent()
if (innerContent) {
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote || props.block.type === BlockType.H1) {
let offsetNode, offset = 0
const numNodes = (content.value as any).$el.firstChild.firstChild.childNodes.length
for (const [i, node] of (content.value as any).$el.firstChild.firstChild.childNodes.entries()) {
if (offset + node.textContent.length > caretPos || i === numNodes - 1) {
offsetNode = node
break
}
offset += node.textContent.length
offsetNode = node
}
const selection = window.getSelection()
const range = document.createRange()
range.setStart(offsetNode.firstChild || offsetNode, caretPos - offset)
range.setEnd(offsetNode.firstChild || offsetNode, caretPos - offset)
selection?.removeAllRanges()
selection?.addRange(range)
} else {
const selection = window.getSelection()
const range = document.createRange()
range.setStart(innerContent, caretPos)
range.setEnd(innerContent, caretPos)
selection?.removeAllRanges()
selection?.addRange(range)
}
}
}
function getStartCoordinates () {
let x = 0, y = 0
const firstChild = getFirstChild()
if (firstChild) {
const range = document.createRange()
range.selectNodeContents(firstChild.firstChild || firstChild)
range.collapse(true)
const rect = range.getBoundingClientRect()
x = rect.left
y = rect.top
}
return { x, y }
}
function getEndCoordinates () {
let x = 0, y = 0
const lastChild = getLastChild()
if (lastChild) {
const range = document.createRange()
range.selectNodeContents(lastChild.firstChild || lastChild)
range.collapse()
const rect = range.getBoundingClientRect()
x = rect.left
y = rect.top
}
return { x, y }
}
function parseMarkdown (event:KeyboardEvent) {
const textContent = getTextContent()
if(!textContent) return
const headingRegexpMap = {
[BlockType.H1]: /^#\s(.*)$/,
[BlockType.H2]: /^##\s(.*)$/,
[BlockType.H3]: /^###\s(.*)$/,
}
const handleHeadingContent = (blockType: keyof typeof headingRegexpMap) => {
emit('setBlockType', blockType)
const newContent = textContent.replace(headingRegexpMap[blockType], '$1')
;(content.value as any).innerText = newContent
props.block.details.value = newContent
}
if (textContent.match(headingRegexpMap[BlockType.H1]) && event.key === ' ') {
handleHeadingContent(BlockType.H1)
} else if (textContent.match(headingRegexpMap[BlockType.H2]) && event.key === ' ') {
handleHeadingContent(BlockType.H2)
} else if (textContent.match(headingRegexpMap[BlockType.H3]) && event.key === ' ') {
handleHeadingContent(BlockType.H3)
} else if (textContent.match(/^---$/)) {
emit('setBlockType', BlockType.Divider);
(content.value as any).innerText = ''
} else if (event.key === '/') {
if (menu.value && !menu.value.open) {
menu.value.open = true
menu.value.openedWithSlash = true
}
}
}
function clearSearch (searchTermLength: number, openedWithSlash: boolean = false) {
// If openedWithSlash, searchTermLength = 0 but we still need to clear
if (searchTermLength < 1 && !openedWithSlash)
return
const pos = getCaretPosWithoutTags().pos
const startIdx = pos - searchTermLength - 1
const endIdx = pos
setTimeout(() => {
const originalText = (content.value as any).$el.innerText
props.block.details.value = originalText.substring(0, startIdx) + originalText.substring(endIdx);
if (props.block.type === BlockType.Text || props.block.type === BlockType.Quote) {
props.block.details.value = `<p>${originalText.substring(0, startIdx) + originalText.substring(endIdx)}</p>`
} else {
(content.value as any).$el.innerText = originalText.substring(0, startIdx) + originalText.substring(endIdx)
}
setTimeout(() => setCaretPos(startIdx))
})
}
defineExpose({
content,
getTextContent,
getHtmlContent,
moveToStart,
moveToEnd,
moveToFirstLine,
moveToLastLine,
getCaretPos,
setCaretPos,
})
</script>