-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvideo.ts
128 lines (102 loc) · 2.98 KB
/
video.ts
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
import { Node, nodeInputRule } from '@tiptap/react'
import { Plugin, PluginKey } from 'prosemirror-state'
export interface VideoOptions {
HTMLAttributes: Record<string, any>,
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
video: {
/**
* Set a video node
*/
setVideo: (src: string) => ReturnType,
/**
* Toggle a video
*/
toggleVideo: (src: string) => ReturnType,
}
}
}
const VIDEO_INPUT_REGEX = /!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\)/
export const Video = Node.create({
name: 'video',
group: "block",
addAttributes() {
return {
src: {
default: null,
parseHTML: (el) => (el as HTMLSpanElement).getAttribute('src'),
renderHTML: (attrs) => ({ src: attrs.src }),
},
};
},
parseHTML() {
return [
{
tag: 'video',
getAttrs: el => ({ src: (el as HTMLVideoElement).getAttribute('src') }),
},
]
},
renderHTML({ HTMLAttributes }) {
return [
'video',
{ controls: 'true', style: 'width: 100%', ...HTMLAttributes },
['source', HTMLAttributes]
]
},
addCommands() {
return {
setVideo: (src: string) => ({ commands }) => commands.insertContent(`<video controls="true" style="width: 100%" src="${src}" />`),
toggleVideo: () => ({ commands }) => commands.toggleNode(this.name, 'paragraph'),
};
},
addInputRules() {
return [
nodeInputRule({
find: VIDEO_INPUT_REGEX,
type: this.type,
getAttributes: (match) => {
const [,, src] = match
return { src }
},
})
]
},
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey('videoDropPlugin'),
props: {
handleDOMEvents: {
drop(view, event) {
const { state: { schema, tr }, dispatch } = view
const hasFiles = event.dataTransfer &&
event.dataTransfer.files &&
event.dataTransfer.files.length
if (!hasFiles) return false
const videos = Array
.from(event.dataTransfer.files)
.filter(file => (/video/i).test(file.type))
if (videos.length === 0) return false
event.preventDefault()
const coordinates = view.posAtCoords({ left: event.clientX, top: event.clientY })
videos.forEach(video => {
const reader = new FileReader()
reader.onload = readerEvent => {
const node = schema.nodes.video.create({ src: readerEvent.target?.result })
if (coordinates && typeof coordinates.pos === 'number') {
const transaction = tr.insert(coordinates?.pos, node)
dispatch(transaction)
}
}
reader.readAsDataURL(video)
})
return true
}
}
}
})
]
}
})