-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.js
107 lines (91 loc) · 2.6 KB
/
index.js
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
import { WeElement, define } from 'omi'
import { Scene, stylesheet } from 'spritejs'
import h from 'snabbdom/h'
import attributes from 'snabbdom/modules/attributes'
import props from 'snabbdom/modules/props'
import * as api from './nodeapi'
const snabbdom = require('snabbdom')
const {create, update} = attributes
function updateEvents(oldVnode, vnode) {
const oldEvents = oldVnode.events,
attrs = vnode.data.attrs
if(oldVnode.elm && oldEvents) {
oldEvents.forEach(([type, f]) => {
oldVnode.elm.removeEventListener(type, f)
})
oldVnode.events = []
}
if(vnode.elm && attrs) {
Object.entries(attrs).forEach(([key, val]) => {
if(key.indexOf('on') === 0 && typeof val === 'function') {
const eventType = key.slice(2).toLowerCase()
vnode.elm.addEventListener(eventType, val)
vnode.events = vnode.events || []
vnode.events.push([eventType, val])
delete attrs[key]
}
})
}
}
function createAttrs(oldVnode, vnode) {
updateEvents(oldVnode, vnode)
return create(oldVnode, vnode)
}
function updateAttrs(oldVnode, vnode) {
updateEvents(oldVnode, vnode)
return update(oldVnode, vnode)
}
const patch = snabbdom.init([
{
create: createAttrs,
update: updateAttrs,
},
props,
], api)
function parseVNode(vdom) {
const {nodeName, key, attributes: attrs, children} = vdom
let sel = nodeName
if(attrs && attrs.id) sel = `${sel}#${attrs.id}`
const props = {attrs}
if(key) props.key = key
return h(sel, props, children.map(child => parseVNode(child)))
}
define('omi-sprite', class extends WeElement {
install() {
}
installed() {
if(this.shadowRoot && this.shadowRoot.styleSheets) {
stylesheet.fromDocumentCSS(this.shadowRoot.styleSheets)
}
let node = this
while(node) {
const styleSheets = node.styleSheets
if(styleSheets) {
stylesheet.fromDocumentCSS(styleSheets)
}
node = node.parentNode
}
this.scene = new Scene(this.container, this.props)
render(this.scene, this.props.children)
}
afterUpdate() {
render(this.scene, this.props.children)
}
render(props) {
return (
<div ref={e => { this.container = e }}
viewport={ props.viewport }
resolution={ props.resolution }>
</div>
)
}
})
function render(scene, children) {
children.forEach((layer) => {
if(!layer.attributes.id) layer.attributes.id = `layer_${Math.random().toString(36).slice(2)}`
const layerEl = scene.layer(layer.attributes.id)
const node = layerEl.vnode_ || layerEl
layerEl.vnode_ = parseVNode(layer)
patch(node, layerEl.vnode_)
})
}