|
1 | 1 | const hyperHTML = require('hyperhtml') |
| 2 | +const onload = require('on-load') |
2 | 3 | const slice = Array.prototype.slice |
| 4 | + |
3 | 5 | const WIRE_OR_BOUND_NODE = /(update|hyperHTML)$/ |
| 6 | +const ONLOAD_ATTR = /^data-onloadid/ |
4 | 7 |
|
5 | 8 | module.exports = function hypercomponent (component) { |
6 | 9 | const render = hyperHTML.wire() |
| 10 | + const renderer = typeof component === 'function' |
| 11 | + ? component |
| 12 | + : component.render |
7 | 13 |
|
8 | 14 | return function wireComponent () { |
| 15 | + const onloadHandler = component.onload |
| 16 | + const onunloadHandler = component.onunload |
9 | 17 | const args = slice.call(arguments) |
10 | 18 |
|
11 | | - if (typeof args[0] === 'function' && WIRE_OR_BOUND_NODE.test(args[0].name)) { |
12 | | - return component.apply(component, args) |
| 19 | + let isMounted = false |
| 20 | + let el = null |
| 21 | + |
| 22 | + if ( |
| 23 | + typeof args[0] === 'function' && |
| 24 | + WIRE_OR_BOUND_NODE.test(args[0].name) |
| 25 | + ) { |
| 26 | + el = renderer.apply(renderer, args) |
| 27 | + } else { |
| 28 | + args.unshift(render) // asign default renderer |
| 29 | + el = renderer.apply(renderer, args) |
| 30 | + } |
| 31 | + |
| 32 | + if (!onloadHandler && !onunloadHandler) return el |
| 33 | + |
| 34 | + if (Array.isArray(el)) { |
| 35 | + return el // A root elelemnt is required if you want to use mount/unmmount |
| 36 | + } |
| 37 | + |
| 38 | + let len = (el.attributes && el.attributes.length) || 0 |
| 39 | + while (len--) { |
| 40 | + if (ONLOAD_ATTR.test(el.attributes[len].name)) { |
| 41 | + isMounted = true |
| 42 | + break |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + if (!isMounted) { |
| 47 | + return onload(el, onloadHandler, onunloadHandler) |
13 | 48 | } |
14 | 49 |
|
15 | | - args.unshift(render) |
16 | | - return component.apply(component, args) |
| 50 | + return el |
17 | 51 | } |
18 | 52 | } |
0 commit comments