-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathindex.js
225 lines (209 loc) · 6.51 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
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
import { h, cloneElement, render, hydrate } from 'preact';
/**
* @typedef {import('preact').FunctionComponent<any> | import('preact').ComponentClass<any> | import('preact').FunctionalComponent<any> } ComponentDefinition
* @typedef {{ shadow: false } | { shadow: true, mode: 'open' | 'closed'}} Options
* @typedef {HTMLElement & { _root: ShadowRoot | HTMLElement, _vdomComponent: ComponentDefinition, _vdom: ReturnType<typeof import("preact").h> | null }} PreactCustomElement
*/
/**
* Register a preact component as web-component.
* @param {ComponentDefinition} Component The preact component to register
* @param {string} [tagName] The HTML element tag-name (must contain a hyphen and be lowercase)
* @param {string[]} [propNames] HTML element attributes to observe
* @param {Options} [options] Additional element options
* @example
* ```ts
* // use custom web-component class
* class PreactWebComponent extends Component {
* static tagName = 'my-web-component';
* render() {
* return <p>Hello world!</p>
* }
* }
*
* register(PreactComponent);
*
* // use a preact component
* function PreactComponent({ prop }) {
* return <p>Hello {prop}!</p>
* }
*
* register(PreactComponent, 'my-component');
* register(PreactComponent, 'my-component', ['prop']);
* register(PreactComponent, 'my-component', ['prop'], {
* shadow: true,
* mode: 'closed'
* });
* ```
*/
export default function register(Component, tagName, propNames, options) {
function PreactElement() {
const inst = /** @type {PreactCustomElement} */ (
Reflect.construct(HTMLElement, [], PreactElement)
);
inst._vdomComponent = Component;
inst._root =
options && options.shadow
? inst.attachShadow({ mode: options.mode || 'open' })
: inst;
return inst;
}
PreactElement.prototype = Object.create(HTMLElement.prototype);
PreactElement.prototype.constructor = PreactElement;
PreactElement.prototype.connectedCallback = connectedCallback;
PreactElement.prototype.attributeChangedCallback = attributeChangedCallback;
PreactElement.prototype.disconnectedCallback = disconnectedCallback;
/**
* @type {string[]}
*/
propNames =
propNames ||
Component.observedAttributes ||
Object.keys(Component.propTypes || {});
PreactElement.observedAttributes = propNames;
// Keep DOM properties and Preact props in sync
propNames.forEach((name) => {
Object.defineProperty(PreactElement.prototype, name, {
get() {
return this._vdom.props[name];
},
set(v) {
if (this._vdom) {
this.attributeChangedCallback(name, null, v);
} else {
if (!this._props) this._props = {};
this._props[name] = v;
this.connectedCallback();
}
// Reflect property changes to attributes if the value is a primitive
const type = typeof v;
if (
v == null ||
type === 'string' ||
type === 'boolean' ||
type === 'number'
) {
this.setAttribute(name, v);
}
},
});
});
return customElements.define(
tagName || Component.tagName || Component.displayName || Component.name,
PreactElement
);
}
function ContextProvider(props) {
this.getChildContext = () => props.context;
// eslint-disable-next-line no-unused-vars
const { context, children, ...rest } = props;
return cloneElement(children, rest);
}
/**
* @this {PreactCustomElement}
*/
function connectedCallback() {
// Obtain a reference to the previous context by pinging the nearest
// higher up node that was rendered with Preact. If one Preact component
// higher up receives our ping, it will set the `detail` property of
// our custom event. This works because events are dispatched
// synchronously.
const event = new CustomEvent('_preact', {
detail: {},
bubbles: true,
cancelable: true,
});
this.dispatchEvent(event);
const context = event.detail.context;
this._vdom = h(
ContextProvider,
{ ...this._props, context },
toVdom(this, this._vdomComponent)
);
(this.hasAttribute('hydrate') ? hydrate : render)(this._vdom, this._root);
}
/**
* Camel-cases a string
* @param {string} str The string to transform to camelCase
* @returns camel case version of the string
*/
function toCamelCase(str) {
return str.replace(/-(\w)/g, (_, c) => (c ? c.toUpperCase() : ''));
}
/**
* Changed whenver an attribute of the HTML element changed
* @this {PreactCustomElement}
* @param {string} name The attribute name
* @param {unknown} oldValue The old value or undefined
* @param {unknown} newValue The new value
*/
function attributeChangedCallback(name, oldValue, newValue) {
if (!this._vdom) return;
// Attributes use `null` as an empty value whereas `undefined` is more
// common in pure JS components, especially with default parameters.
// When calling `node.removeAttribute()` we'll receive `null` as the new
// value. See issue #50.
newValue = newValue == null ? undefined : newValue;
const props = {};
props[name] = newValue;
props[toCamelCase(name)] = newValue;
this._vdom = cloneElement(this._vdom, props);
render(this._vdom, this._root);
}
/**
* @this {PreactCustomElement}
*/
function disconnectedCallback() {
render((this._vdom = null), this._root);
}
/**
* Pass an event listener to each `<slot>` that "forwards" the current
* context value to the rendered child. The child will trigger a custom
* event, where will add the context value to. Because events work
* synchronously, the child can immediately pull of the value right
* after having fired the event.
*/
function Slot(props, context) {
const ref = (r) => {
if (!r) {
this.ref.removeEventListener('_preact', this._listener);
} else {
this.ref = r;
if (!this._listener) {
this._listener = (event) => {
event.stopPropagation();
event.detail.context = context;
};
r.addEventListener('_preact', this._listener);
}
}
};
return h('slot', { ...props, ref });
}
function toVdom(element, nodeName) {
if (element.nodeType === 3) return element.data;
if (element.nodeType !== 1) return null;
let children = [],
props = {},
i = 0,
a = element.attributes,
cn = element.childNodes;
for (i = a.length; i--; ) {
if (a[i].name !== 'slot') {
props[a[i].name] = a[i].value;
props[toCamelCase(a[i].name)] = a[i].value;
}
}
for (i = cn.length; i--; ) {
const vnode = toVdom(cn[i], null);
// Move slots correctly
const name = cn[i].slot;
if (name) {
props[name] = h(Slot, { name }, vnode);
} else {
children[i] = vnode;
}
}
// Only wrap the topmost node with a slot
const wrappedChildren = nodeName ? h(Slot, null, children) : children;
return h(nodeName || element.nodeName.toLowerCase(), props, wrappedChildren);
}