Skip to content

Instantly share code, notes, and snippets.

@linus
Created February 11, 2016 15:43
Show Gist options
  • Save linus/5c508b1c2a504c16141b to your computer and use it in GitHub Desktop.
Save linus/5c508b1c2a504c16141b to your computer and use it in GitHub Desktop.
class Video extends Inline {
get attrs() {
return {
url: new Attribute,
id: new Attribute({compute: function (attrs) {console.log(attrs);return videoRE.exec(attrs.url)[2]}}),
type: new Attribute({compute: function (attrs) {console.log(attrs);return videoRE.exec(attrs.url)[1]}}),
width: new Attribute({default: "640"}),
height: new Attribute({default: "480"})
}
}
get draggable() { return true }
static toURL({id, type}) {
switch(type) {
case "vimeo": return `https://player.vimeo.com/video/${id}`
case "youtube": return `https://www.youtube.com/embed/${id}`
}
}
static fromURL (url, attrs = {}) {
let match = videoRE.exec(url)
attrs.id = match[2]
attrs.type = match[1]
return attrs
}
}
Video.register("parseDOM", "iframe", {
rank: 25,
parse: function (dom, state) {
if(dom.className != "avideo") return false
state.insert(this, Video.fromURL(dom.src))
}
})
Video.prototype.serializeDOM = node => elt("iframe", {
class: "avideo",
src: Video.toURL(node.attrs),
width: node.attrs.width,
height: node.attrs.height
})
Video.register("command", "insert", {
params: [
{label: "URL", attr: "url", type: "text"},
{label: "Width", attr: "width", type: "text",
prefill (pm) {
return selectedNodeAttr(pm, this, "width")
}},
{label: "Height", attr: "height", type: "text",
prefill (pm) {
return selectedNodeAttr(pm, this, "height")
}},
],
label: "Insert video",
run(pm, url) {
return pm.tr.replaceSelection(this.create(Video.fromURL(url))).apply(pm.apply.scroll)
},
menu: {
group: "insert", rank: 1,
display: {type: "label", label: "Video"}
}
})
Video.register("autoInput", "autoVideo", new InputRule(/\[video +(.+)\]$/, "]", function (pm, [stmt, paramStr], pos) {
let start = pos.move(-stmt.length)
let params = paramStr.split(/\s+/)
let attrs = params.length === 1
? { url: params[0] }
: params
.map(s => {return s.split(/=(.*)/)})
.reduce((acc, [key, val]) => {acc[key] = val; return acc}, {})
pm.tr.replaceWith(start, pos, this.create(attrs)).apply()
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment