Showing preview only (270K chars total). Download the full file or copy to clipboard to get everything.
Repository: WebReflection/hyperHTML-Element
Branch: master
Commit: 418299139c31
Files: 28
Total size: 259.4 KB
Directory structure:
gitextract_91jr2tdp/
├── .github/
│ └── workflows/
│ └── node.js.yml
├── .gitignore
├── .npmignore
├── .npmrc
├── LICENSE.txt
├── README.md
├── cjs/
│ ├── index.d.ts
│ ├── index.js
│ └── package.json
├── es5.config.js
├── es5.js
├── esm/
│ ├── index.d.ts
│ └── index.js
├── esm.config.js
├── index.d.ts
├── index.js
├── min.js
├── package.json
├── test/
│ ├── boolean.html
│ ├── builtin.html
│ ├── button.html
│ ├── ce.js
│ ├── checked.html
│ ├── index.html
│ ├── test.es5.js
│ └── test.js
├── test.js
└── typescript.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/node.js.yml
================================================
# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm run build --if-present
- run: npm test
- run: npm run coverage --if-present
- name: Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .gitignore
================================================
.DS_Store
.nyc_output/
node_modules/
coverage/
================================================
FILE: .npmignore
================================================
.nyc_output/
coverage/
node_modules/
test/*
.babelrc
.gitignore
.travis.yml
es5.config.js
esm.config.js
package-lock.json
test.js
typescript.md
================================================
FILE: .npmrc
================================================
package-lock=true
package-lock=true
================================================
FILE: LICENSE.txt
================================================
ISC License
Copyright (c) 2017-2018, Andrea Giammarchi, @WebReflection
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
================================================
FILE: README.md
================================================
# hyperHTML-Element
[](https://opensource.org/licenses/ISC) [](https://travis-ci.org/WebReflection/hyperHTML-Element) [](https://greenkeeper.io/) 
An extensible class to define hyperHTML based Custom Elements.
`npm install hyperhtml-element`
#### hyperHTML included
This class attaches all `hyperHTML` methods to itself,
with the only exception of the `define` method,
used in here to define Custom Elements instead.
To have same [define functionality](https://viperhtml.js.org/hyperhtml/documentation/#api-3),
please use `HyperHTMLElement.intent(...)` which provides exact same API.
### Documentation
You can find more info about this helper in [hyperHTML documentation](https://viperhtml.js.org/hyperhtml/documentation/#components-2) page.
### The Class
```js
const HyperHTMLElement = require('hyperhtml-element');
class MyElement extends HyperHTMLElement {
// observed attributes are automatically defined as accessors
static get observedAttributes() { return ['key']; }
// boolean attributes are automatically defined as accessors
// and will set or remove the passed value
static get booleanAttributes() { return ['active']; }
// invoked once the component has been fully upgraded
// suitable to perform any sort of setup
// granted to be invoked right before either
// connectedCallback or attributeChangedCallback
created() {
// triggers automatically attributeChangedCallback
this.key = 'value';
}
attributeChangedCallback(name, prev, curr) {
// when invoked, attributes will be already reflected
// through their accessor
this.key === curr; // true, and curr === "value"
this.getAttribute('key') === this.key; // always true
this.render();
}
render() {
// lazily defined, this.html property points to an hyperHTML bound context
// which could be the element shadowRoot or the element itself.
// All events can be handled directly by the context, thanks to handleEvent
// https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
return this.html`
Hello <strong onclick=${this}>HyperHTMLElement</strong>
( ${this.state.clicks} )`;
}
// using the inherited handleEvent,
// events can be easily defined as methods with `on` prefix.
onclick(e) {
// `this` refers to the current custom element
console.log(this, 'click', e.target);
// state handling, updates the view
this.setState({clicks: this.state.clicks + 1});
}
// alternatively, you can specify a `data-call`
// attribute with the name of the method to invoke
// this.html`<i data-call=onAnyEvent onclick=${this}>try</i>`;
onAnyEvent(e) {
// `this` still refers to the current custom element
console.log(this, e.type, e.currentTarget, e.target);
}
// you can also use Preact-like events handling
// this is less efficient, but migration friendly.
// The method is bound once per instance so that
// this.handleClick === this.handleClick is always true
// this.html`<i onclick=${this.handleClick}>try</i>`;
handleClick(e) {
// `this` still refers to the current custom element
console.log(this, e.type, e.currentTarget, e.target);
}
// define a default state to use whenever this.state is accessed
// it can create states from observed properties too
get defaultState() {
return {clicks: 0, key: this.key};
}
// this method is Preact friendly, once invoked
// as this.setState({new: 'value'});
// it will shallow copy properties over
// and it will invoke this.render() right after
setState(objOrFn)
// all other native Custom Elements method works as usual
// connectedCallback() { ... }
// adoptedCallback() { ... }
}
// classes must be defined through their public static method
// this is the moment the class will be fully setup once
// and registered to the customElements Registry.
MyElement.define('my-element');
```
#### New in v1.8
You can now define custom elements builtins too:
```js
class MyLink extends HyperHTMLElement {
created() { this.render(); }
render() {
return this.html`hello there!`;
}
}
MyLink.define('my-link', {extends: 'a'});
```
### Compatibility
`HyperHTMLElement` is compatible with every mobile browser and IE11 or greater.
There is a [native live test](https://webreflection.github.io/hyperHTML-Element/test/) page also [transpiled for ES5](https://webreflection.github.io/hyperHTML-Element/test/?es5) browsers.
================================================
FILE: cjs/index.d.ts
================================================
import HyperHTMLElement from "..";
export * from '..';
export default HyperHTMLElement;
================================================
FILE: cjs/index.js
================================================
'use strict';
/*! (C) 2017-2018 Andrea Giammarchi - ISC Style License */
const {Component, bind, define, hyper, wire} = require('hyperhtml');
// utils to deal with custom elements builtin extends
const ATTRIBUTE_CHANGED_CALLBACK = 'attributeChangedCallback';
const O = Object;
const classes = [];
const defineProperty = O.defineProperty;
const getOwnPropertyDescriptor = O.getOwnPropertyDescriptor;
const getOwnPropertyNames = O.getOwnPropertyNames;
/* istanbul ignore next */
const getOwnPropertySymbols = O.getOwnPropertySymbols || (() => []);
/* istanbul ignore next */
const getPrototypeOf = O.getPrototypeOf || (o => o.__proto__);
/* istanbul ignore next */
const ownKeys = typeof Reflect === 'object' && Reflect.ownKeys ||
(o => getOwnPropertyNames(o).concat(getOwnPropertySymbols(o)));
/* istanbul ignore next */
const setPrototypeOf = O.setPrototypeOf ||
((o, p) => (o.__proto__ = p, o));
/* istanbul ignore stop */
const camel = name => name.replace(/-([a-z])/g, ($0, $1) => $1.toUpperCase());
const {attachShadow} = HTMLElement.prototype;
const sr = new WeakMap;
class HyperHTMLElement extends HTMLElement {
// define a custom-element in the CustomElementsRegistry
// class MyEl extends HyperHTMLElement {}
// MyEl.define('my-el');
static define(name, options) {
const Class = this;
const proto = Class.prototype;
const onChanged = proto[ATTRIBUTE_CHANGED_CALLBACK];
const hasChange = !!onChanged;
// Class.booleanAttributes
// -----------------------------------------------
// attributes defined as boolean will have
// an either available or not available attribute
// regardless of the value.
// All falsy values, or "false", mean attribute removed
// while truthy values will be set as is.
// Boolean attributes are also automatically observed.
const booleanAttributes = Class.booleanAttributes || [];
booleanAttributes.forEach(attribute => {
const name = camel(attribute);
if (!(name in proto)) defineProperty(
proto,
name,
{
configurable: true,
get() {
return this.hasAttribute(attribute);
},
set(value) {
if (!value || value === 'false')
this.removeAttribute(attribute);
else
this.setAttribute(attribute, '');
}
}
);
});
// Class.observedAttributes
// -------------------------------------------------------
// HyperHTMLElement will directly reflect get/setAttribute
// operation once these attributes are used, example:
// el.observed = 123;
// will automatically do
// el.setAttribute('observed', 123);
// triggering also the attributeChangedCallback
const observedAttributes = (Class.observedAttributes || []).filter(
attribute => booleanAttributes.indexOf(attribute) < 0
);
observedAttributes.forEach(attribute => {
// it is possible to redefine the behavior at any time
// simply overwriting get prop() and set prop(value)
const name = camel(attribute);
if (!(name in proto)) defineProperty(
proto,
name,
{
configurable: true,
get() {
return this.getAttribute(attribute);
},
set(value) {
if (value == null)
this.removeAttribute(attribute);
else
this.setAttribute(attribute, value);
}
}
);
});
// if these are defined, overwrite the observedAttributes getter
// to include also booleanAttributes
const attributes = booleanAttributes.concat(observedAttributes);
if (attributes.length)
defineProperty(Class, 'observedAttributes', {
get() { return attributes; }
});
// created() {}
// ---------------------------------
// an initializer method that grants
// the node is fully known to the browser.
// It is ensured to run either after DOMContentLoaded,
// or once there is a next sibling (stream-friendly) so that
// you have full access to element attributes and/or childNodes.
const created = proto.created || function () {
this.render();
};
// used to ensure create() is called once and once only
defineProperty(
proto,
'_init$',
{
configurable: true,
writable: true,
value: true
}
);
defineProperty(
proto,
ATTRIBUTE_CHANGED_CALLBACK,
{
configurable: true,
value: function aCC(name, prev, curr) {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$)
return this._init$$.push(aCC.bind(this, name, prev, curr));
}
// ensure setting same value twice
// won't trigger twice attributeChangedCallback
if (hasChange && prev !== curr) {
onChanged.apply(this, arguments);
}
}
}
);
const onConnected = proto.connectedCallback;
const hasConnect = !!onConnected;
defineProperty(
proto,
'connectedCallback',
{
configurable: true,
value: function cC() {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$)
return this._init$$.push(cC.bind(this));
}
if (hasConnect) {
onConnected.apply(this, arguments);
}
}
}
);
// define lazily all handlers
// class { handleClick() { ... }
// render() { `<a onclick=${this.handleClick}>` } }
getOwnPropertyNames(proto).forEach(key => {
if (/^handle[A-Z]/.test(key)) {
const _key$ = '_' + key + '$';
const method = proto[key];
defineProperty(proto, key, {
configurable: true,
get() {
return this[_key$] ||
(this[_key$] = method.bind(this));
}
});
}
});
// whenever you want to directly use the component itself
// as EventListener, you can pass it directly.
// https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
// class Reactive extends HyperHTMLElement {
// oninput(e) { console.log(this, 'changed', e.target.value); }
// render() { this.html`<input oninput="${this}">`; }
// }
if (!('handleEvent' in proto)) {
defineProperty(
proto,
'handleEvent',
{
configurable: true,
value(event) {
this[
(event.currentTarget.dataset || {}).call ||
('on' + event.type)
](event);
}
}
);
}
if (options && options.extends) {
const Native = document.createElement(options.extends).constructor;
const Intermediate = class extends Native {};
const ckeys = ['length', 'name', 'arguments', 'caller', 'prototype'];
const pkeys = [];
let Super = null;
let BaseClass = Class;
while (Super = getPrototypeOf(BaseClass)) {
[
{target: Intermediate, base: Super, keys: ckeys},
{target: Intermediate.prototype, base: Super.prototype, keys: pkeys}
]
.forEach(({target, base, keys}) => {
ownKeys(base)
.filter(key => keys.indexOf(key) < 0)
.forEach((key) => {
keys.push(key);
defineProperty(
target,
key,
getOwnPropertyDescriptor(base, key)
);
});
});
BaseClass = Super;
if (Super === HyperHTMLElement)
break;
}
setPrototypeOf(Class, Intermediate);
setPrototypeOf(proto, Intermediate.prototype);
customElements.define(name, Class, options);
} else {
customElements.define(name, Class);
}
classes.push(Class);
return Class;
}
// weakly relate the shadowRoot for refs usage
attachShadow() {
const shadowRoot = attachShadow.apply(this, arguments);
sr.set(this, shadowRoot);
return shadowRoot;
}
// returns elements by ref
get refs() {
const value = {};
if ('_html$' in this) {
const all = (sr.get(this) || this).querySelectorAll('[ref]');
for (let {length} = all, i = 0; i < length; i++) {
const node = all[i];
value[node.getAttribute('ref')] = node;
}
Object.defineProperty(this, 'refs', {value});
return value;
}
return value;
}
// lazily bind once hyperHTML logic
// to either the shadowRoot, if present and open,
// the _shadowRoot property, if set due closed shadow root,
// or the custom-element itself if no Shadow DOM is used.
get html() {
return this._html$ || (this.html = bind(
// in a way or another, bind to the right node
// backward compatible, first two could probably go already
this.shadowRoot || this._shadowRoot || sr.get(this) || this
));
}
// it can be set too if necessary, it won't invoke render()
set html(value) {
defineProperty(this, '_html$', {configurable: true, value: value});
}
// overwrite this method with your own render
render() {}
// ---------------------//
// Basic State Handling //
// ---------------------//
// define the default state object
// you could use observed properties too
get defaultState() { return {}; }
// the state with a default
get state() {
return this._state$ || (this.state = this.defaultState);
}
// it can be set too if necessary, it won't invoke render()
set state(value) {
defineProperty(this, '_state$', {configurable: true, value: value});
}
// currently a state is a shallow copy, like in Preact or other libraries.
// after the state is updated, the render() method will be invoked.
// ⚠️ do not ever call this.setState() inside this.render()
setState(state, render) {
const target = this.state;
const source = typeof state === 'function' ? state.call(this, target) : state;
for (const key in source) target[key] = source[key];
if (render !== false) this.render();
return this;
}
};
// exposing hyperHTML utilities
HyperHTMLElement.Component = Component;
HyperHTMLElement.bind = bind;
HyperHTMLElement.intent = define;
HyperHTMLElement.wire = wire;
HyperHTMLElement.hyper = hyper;
try {
if (Symbol.hasInstance) classes.push(
defineProperty(HyperHTMLElement, Symbol.hasInstance, {
enumerable: false,
configurable: true,
value(instance) {
return classes.some(isPrototypeOf, getPrototypeOf(instance));
}
}));
} catch(meh) {}
Object.defineProperty(exports, '__esModule', {value: true}).default = HyperHTMLElement;
// ------------------------------//
// DOMContentLoaded VS created() //
// ------------------------------//
const dom = {
type: 'DOMContentLoaded',
handleEvent() {
if (dom.ready()) {
document.removeEventListener(dom.type, dom, false);
dom.list.splice(0).forEach(invoke);
}
else
setTimeout(dom.handleEvent);
},
ready() {
return document.readyState === 'complete';
},
list: []
};
if (!dom.ready()) {
document.addEventListener(dom.type, dom, false);
}
function checkReady(created, attributes, booleanAttributes) {
if (dom.ready() || isReady.call(this, created, attributes, booleanAttributes)) {
if (this._init$) {
const list = this._init$$ || [];
delete this._init$$;
const self = defineProperty(this, '_init$', {value: false});
booleanAttributes.forEach(name => {
if (self.getAttribute(name) === 'false')
self.removeAttribute(name);
});
attributes.forEach(name => {
if (self.hasOwnProperty(name)) {
const curr = self[name];
delete self[name];
list.unshift(() => { self[name] = curr; });
}
});
created.call(self);
list.forEach(invoke);
}
} else {
if (!this.hasOwnProperty('_init$$'))
defineProperty(this, '_init$$', {configurable: true, value: []});
dom.list.push(checkReady.bind(this, created, attributes, booleanAttributes));
}
}
function invoke(fn) {
fn();
}
function isPrototypeOf(Class) {
return this === Class.prototype;
}
function isReady(created, attributes, booleanAttributes) {
let el = this;
do { if (el.nextSibling) return true; }
while (el = el.parentNode);
setTimeout(checkReady.bind(this, created, attributes, booleanAttributes));
return false;
}
================================================
FILE: cjs/package.json
================================================
{"type":"commonjs"}
================================================
FILE: es5.config.js
================================================
import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
export default {
input: 'esm/index.js',
plugins: [
resolve({module: true}),
babel({presets: ["@babel/preset-env"]})
],
context: 'null',
moduleContext: 'null',
output: {
exports: 'named',
file: 'es5.js',
format: 'iife',
name: 'HyperHTMLElement'
}
};
================================================
FILE: es5.js
================================================
var HyperHTMLElement = (function (exports) {
'use strict';
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
/*! (c) Andrea Giammarchi - ISC */
var self$3 = {};
try {
self$3.WeakMap = WeakMap;
} catch (WeakMap) {
// this could be better but 90% of the time
// it's everything developers need as fallback
self$3.WeakMap = function (id, Object) {
var dP = Object.defineProperty;
var hOP = Object.hasOwnProperty;
var proto = WeakMap.prototype;
proto["delete"] = function (key) {
return this.has(key) && delete key[this._];
};
proto.get = function (key) {
return this.has(key) ? key[this._] : void 0;
};
proto.has = function (key) {
return hOP.call(key, this._);
};
proto.set = function (key, value) {
dP(key, this._, {
configurable: true,
value: value
});
return this;
};
return WeakMap;
function WeakMap(iterable) {
dP(this, '_', {
value: '_@ungap/weakmap' + id++
});
if (iterable) iterable.forEach(add, this);
}
function add(pair) {
this.set(pair[0], pair[1]);
}
}(Math.random(), Object);
}
var WeakMap$1 = self$3.WeakMap;
/*! (c) Andrea Giammarchi - ISC */
var self$2 = {};
try {
self$2.WeakSet = WeakSet;
} catch (WeakSet) {
(function (id, dP) {
var proto = WeakSet.prototype;
proto.add = function (object) {
if (!this.has(object)) dP(object, this._, {
value: true,
configurable: true
});
return this;
};
proto.has = function (object) {
return this.hasOwnProperty.call(object, this._);
};
proto["delete"] = function (object) {
return this.has(object) && delete object[this._];
};
self$2.WeakSet = WeakSet;
function WeakSet() {
dP(this, '_', {
value: '_@ungap/weakmap' + id++
});
}
})(Math.random(), Object.defineProperty);
}
var WeakSet$1 = self$2.WeakSet;
var _ref = [],
indexOf$1 = _ref.indexOf;
var append = function append(get, parent, children, start, end, before) {
var isSelect = ('selectedIndex' in parent);
var noSelection = isSelect;
while (start < end) {
var child = get(children[start], 1);
parent.insertBefore(child, before);
if (isSelect && noSelection && child.selected) {
noSelection = !noSelection;
var selectedIndex = parent.selectedIndex;
parent.selectedIndex = selectedIndex < 0 ? start : indexOf$1.call(parent.querySelectorAll('option'), child);
}
start++;
}
};
var eqeq = function eqeq(a, b) {
return a == b;
};
var identity = function identity(O) {
return O;
};
var indexOf = function indexOf(moreNodes, moreStart, moreEnd, lessNodes, lessStart, lessEnd, compare) {
var length = lessEnd - lessStart;
/* istanbul ignore if */
if (length < 1) return -1;
while (moreEnd - moreStart >= length) {
var m = moreStart;
var l = lessStart;
while (m < moreEnd && l < lessEnd && compare(moreNodes[m], lessNodes[l])) {
m++;
l++;
}
if (l === lessEnd) return moreStart;
moreStart = m + 1;
}
return -1;
};
var isReversed = function isReversed(futureNodes, futureEnd, currentNodes, currentStart, currentEnd, compare) {
while (currentStart < currentEnd && compare(currentNodes[currentStart], futureNodes[futureEnd - 1])) {
currentStart++;
futureEnd--;
}
return futureEnd === 0;
};
var next = function next(get, list, i, length, before) {
return i < length ? get(list[i], 0) : 0 < i ? get(list[i - 1], -0).nextSibling : before;
};
var remove = function remove(get, children, start, end) {
while (start < end) {
drop(get(children[start++], -1));
}
}; // - - - - - - - - - - - - - - - - - - -
// diff related constants and utilities
// - - - - - - - - - - - - - - - - - - -
var DELETION = -1;
var INSERTION = 1;
var SKIP = 0;
var SKIP_OND = 50;
var HS = function HS(futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges) {
var k = 0;
/* istanbul ignore next */
var minLen = futureChanges < currentChanges ? futureChanges : currentChanges;
var link = Array(minLen++);
var tresh = Array(minLen);
tresh[0] = -1;
for (var i = 1; i < minLen; i++) {
tresh[i] = currentEnd;
}
var nodes = currentNodes.slice(currentStart, currentEnd);
for (var _i = futureStart; _i < futureEnd; _i++) {
var index = nodes.indexOf(futureNodes[_i]);
if (-1 < index) {
var idxInOld = index + currentStart;
k = findK(tresh, minLen, idxInOld);
/* istanbul ignore else */
if (-1 < k) {
tresh[k] = idxInOld;
link[k] = {
newi: _i,
oldi: idxInOld,
prev: link[k - 1]
};
}
}
}
k = --minLen;
--currentEnd;
while (tresh[k] > currentEnd) {
--k;
}
minLen = currentChanges + futureChanges - k;
var diff = Array(minLen);
var ptr = link[k];
--futureEnd;
while (ptr) {
var _ptr = ptr,
newi = _ptr.newi,
oldi = _ptr.oldi;
while (futureEnd > newi) {
diff[--minLen] = INSERTION;
--futureEnd;
}
while (currentEnd > oldi) {
diff[--minLen] = DELETION;
--currentEnd;
}
diff[--minLen] = SKIP;
--futureEnd;
--currentEnd;
ptr = ptr.prev;
}
while (futureEnd >= futureStart) {
diff[--minLen] = INSERTION;
--futureEnd;
}
while (currentEnd >= currentStart) {
diff[--minLen] = DELETION;
--currentEnd;
}
return diff;
}; // this is pretty much the same petit-dom code without the delete map part
// https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L556-L561
var OND = function OND(futureNodes, futureStart, rows, currentNodes, currentStart, cols, compare) {
var length = rows + cols;
var v = [];
var d, k, r, c, pv, cv, pd;
outer: for (d = 0; d <= length; d++) {
/* istanbul ignore if */
if (d > SKIP_OND) return null;
pd = d - 1;
/* istanbul ignore next */
pv = d ? v[d - 1] : [0, 0];
cv = v[d] = [];
for (k = -d; k <= d; k += 2) {
if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) {
c = pv[pd + k + 1];
} else {
c = pv[pd + k - 1] + 1;
}
r = c - k;
while (c < cols && r < rows && compare(currentNodes[currentStart + c], futureNodes[futureStart + r])) {
c++;
r++;
}
if (c === cols && r === rows) {
break outer;
}
cv[d + k] = c;
}
}
var diff = Array(d / 2 + length / 2);
var diffIdx = diff.length - 1;
for (d = v.length - 1; d >= 0; d--) {
while (c > 0 && r > 0 && compare(currentNodes[currentStart + c - 1], futureNodes[futureStart + r - 1])) {
// diagonal edge = equality
diff[diffIdx--] = SKIP;
c--;
r--;
}
if (!d) break;
pd = d - 1;
/* istanbul ignore next */
pv = d ? v[d - 1] : [0, 0];
k = c - r;
if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) {
// vertical edge = insertion
r--;
diff[diffIdx--] = INSERTION;
} else {
// horizontal edge = deletion
c--;
diff[diffIdx--] = DELETION;
}
}
return diff;
};
var applyDiff = function applyDiff(diff, get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before) {
var live = [];
var length = diff.length;
var currentIndex = currentStart;
var i = 0;
while (i < length) {
switch (diff[i++]) {
case SKIP:
futureStart++;
currentIndex++;
break;
case INSERTION:
// TODO: bulk appends for sequential nodes
live.push(futureNodes[futureStart]);
append(get, parentNode, futureNodes, futureStart++, futureStart, currentIndex < currentLength ? get(currentNodes[currentIndex], 0) : before);
break;
case DELETION:
currentIndex++;
break;
}
}
i = 0;
while (i < length) {
switch (diff[i++]) {
case SKIP:
currentStart++;
break;
case DELETION:
// TODO: bulk removes for sequential nodes
if (-1 < live.indexOf(currentNodes[currentStart])) currentStart++;else remove(get, currentNodes, currentStart++, currentStart);
break;
}
}
};
var findK = function findK(ktr, length, j) {
var lo = 1;
var hi = length;
while (lo < hi) {
var mid = (lo + hi) / 2 >>> 0;
if (j < ktr[mid]) hi = mid;else lo = mid + 1;
}
return lo;
};
var smartDiff = function smartDiff(get, parentNode, futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges, currentLength, compare, before) {
applyDiff(OND(futureNodes, futureStart, futureChanges, currentNodes, currentStart, currentChanges, compare) || HS(futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges), get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before);
};
var drop = function drop(node) {
return (node.remove || dropChild).call(node);
};
function dropChild() {
var parentNode = this.parentNode;
/* istanbul ignore else */
if (parentNode) parentNode.removeChild(this);
}
/*! (c) 2018 Andrea Giammarchi (ISC) */
var domdiff = function domdiff(parentNode, // where changes happen
currentNodes, // Array of current items/nodes
futureNodes, // Array of future items/nodes
options // optional object with one of the following properties
// before: domNode
// compare(generic, generic) => true if same generic
// node(generic) => Node
) {
if (!options) options = {};
var compare = options.compare || eqeq;
var get = options.node || identity;
var before = options.before == null ? null : get(options.before, 0);
var currentLength = currentNodes.length;
var currentEnd = currentLength;
var currentStart = 0;
var futureEnd = futureNodes.length;
var futureStart = 0; // common prefix
while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentStart], futureNodes[futureStart])) {
currentStart++;
futureStart++;
} // common suffix
while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentEnd - 1], futureNodes[futureEnd - 1])) {
currentEnd--;
futureEnd--;
}
var currentSame = currentStart === currentEnd;
var futureSame = futureStart === futureEnd; // same list
if (currentSame && futureSame) return futureNodes; // only stuff to add
if (currentSame && futureStart < futureEnd) {
append(get, parentNode, futureNodes, futureStart, futureEnd, next(get, currentNodes, currentStart, currentLength, before));
return futureNodes;
} // only stuff to remove
if (futureSame && currentStart < currentEnd) {
remove(get, currentNodes, currentStart, currentEnd);
return futureNodes;
}
var currentChanges = currentEnd - currentStart;
var futureChanges = futureEnd - futureStart;
var i = -1; // 2 simple indels: the shortest sequence is a subsequence of the longest
if (currentChanges < futureChanges) {
i = indexOf(futureNodes, futureStart, futureEnd, currentNodes, currentStart, currentEnd, compare); // inner diff
if (-1 < i) {
append(get, parentNode, futureNodes, futureStart, i, get(currentNodes[currentStart], 0));
append(get, parentNode, futureNodes, i + currentChanges, futureEnd, next(get, currentNodes, currentEnd, currentLength, before));
return futureNodes;
}
}
/* istanbul ignore else */
else if (futureChanges < currentChanges) {
i = indexOf(currentNodes, currentStart, currentEnd, futureNodes, futureStart, futureEnd, compare); // outer diff
if (-1 < i) {
remove(get, currentNodes, currentStart, i);
remove(get, currentNodes, i + futureChanges, currentEnd);
return futureNodes;
}
} // common case with one replacement for many nodes
// or many nodes replaced for a single one
/* istanbul ignore else */
if (currentChanges < 2 || futureChanges < 2) {
append(get, parentNode, futureNodes, futureStart, futureEnd, get(currentNodes[currentStart], 0));
remove(get, currentNodes, currentStart, currentEnd);
return futureNodes;
} // the half match diff part has been skipped in petit-dom
// https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L391-L397
// accordingly, I think it's safe to skip in here too
// if one day it'll come out like the speediest thing ever to do
// then I might add it in here too
// Extra: before going too fancy, what about reversed lists ?
// This should bail out pretty quickly if that's not the case.
if (currentChanges === futureChanges && isReversed(futureNodes, futureEnd, currentNodes, currentStart, currentEnd, compare)) {
append(get, parentNode, futureNodes, futureStart, futureEnd, next(get, currentNodes, currentEnd, currentLength, before));
return futureNodes;
} // last resort through a smart diff
smartDiff(get, parentNode, futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges, currentLength, compare, before);
return futureNodes;
};
/*! (c) Andrea Giammarchi - ISC */
var self$1 = {};
self$1.CustomEvent = typeof CustomEvent === 'function' ? CustomEvent : function (__p__) {
CustomEvent[__p__] = new CustomEvent('').constructor[__p__];
return CustomEvent;
function CustomEvent(type, init) {
if (!init) init = {};
var e = document.createEvent('CustomEvent');
e.initCustomEvent(type, !!init.bubbles, !!init.cancelable, init.detail);
return e;
}
}('prototype');
var CustomEvent$1 = self$1.CustomEvent;
/*! (c) Andrea Giammarchi - ISC */
var self = {};
try {
self.Map = Map;
} catch (Map) {
self.Map = function Map() {
var i = 0;
var k = [];
var v = [];
return {
"delete": function _delete(key) {
var had = contains(key);
if (had) {
k.splice(i, 1);
v.splice(i, 1);
}
return had;
},
forEach: function forEach(callback, context) {
k.forEach(function (key, i) {
callback.call(context, v[i], key, this);
}, this);
},
get: function get(key) {
return contains(key) ? v[i] : void 0;
},
has: function has(key) {
return contains(key);
},
set: function set(key, value) {
v[contains(key) ? i : k.push(key) - 1] = value;
return this;
}
};
function contains(v) {
i = k.indexOf(v);
return -1 < i;
}
};
}
var Map$1 = self.Map;
// able to create Custom Elements like components
// including the ability to listen to connect/disconnect
// events via onconnect/ondisconnect attributes
// Components can be created imperatively or declaratively.
// The main difference is that declared components
// will not automatically render on setState(...)
// to simplify state handling on render.
function Component() {
return this; // this is needed in Edge !!!
} // Component is lazily setup because it needs
// wire mechanism as lazy content
function setup(content) {
// there are various weakly referenced variables in here
// and mostly are to use Component.for(...) static method.
var children = new WeakMap$1();
var create = Object.create;
var createEntry = function createEntry(wm, id, component) {
wm.set(id, component);
return component;
};
var get = function get(Class, info, context, id) {
var relation = info.get(Class) || relate(Class, info);
switch (_typeof(id)) {
case 'object':
case 'function':
var wm = relation.w || (relation.w = new WeakMap$1());
return wm.get(id) || createEntry(wm, id, new Class(context));
default:
var sm = relation.p || (relation.p = create(null));
return sm[id] || (sm[id] = new Class(context));
}
};
var relate = function relate(Class, info) {
var relation = {
w: null,
p: null
};
info.set(Class, relation);
return relation;
};
var set = function set(context) {
var info = new Map$1();
children.set(context, info);
return info;
}; // The Component Class
Object.defineProperties(Component, {
// Component.for(context[, id]) is a convenient way
// to automatically relate data/context to children components
// If not created yet, the new Component(context) is weakly stored
// and after that same instance would always be returned.
"for": {
configurable: true,
value: function value(context, id) {
return get(this, children.get(context) || set(context), context, id == null ? 'default' : id);
}
}
});
Object.defineProperties(Component.prototype, {
// all events are handled with the component as context
handleEvent: {
value: function value(e) {
var ct = e.currentTarget;
this['getAttribute' in ct && ct.getAttribute('data-call') || 'on' + e.type](e);
}
},
// components will lazily define html or svg properties
// as soon as these are invoked within the .render() method
// Such render() method is not provided by the base class
// but it must be available through the Component extend.
// Declared components could implement a
// render(props) method too and use props as needed.
html: lazyGetter('html', content),
svg: lazyGetter('svg', content),
// the state is a very basic/simple mechanism inspired by Preact
state: lazyGetter('state', function () {
return this.defaultState;
}),
// it is possible to define a default state that'd be always an object otherwise
defaultState: {
get: function get() {
return {};
}
},
// dispatch a bubbling, cancelable, custom event
// through the first known/available node
dispatch: {
value: function value(type, detail) {
var _wire$ = this._wire$;
if (_wire$) {
var event = new CustomEvent$1(type, {
bubbles: true,
cancelable: true,
detail: detail
});
event.component = this;
return (_wire$.dispatchEvent ? _wire$ : _wire$.firstChild).dispatchEvent(event);
}
return false;
}
},
// setting some property state through a new object
// or a callback, triggers also automatically a render
// unless explicitly specified to not do so (render === false)
setState: {
value: function value(state, render) {
var target = this.state;
var source = typeof state === 'function' ? state.call(this, target) : state;
for (var key in source) {
target[key] = source[key];
}
if (render !== false) this.render();
return this;
}
}
});
} // instead of a secret key I could've used a WeakMap
// However, attaching a property directly will result
// into better performance with thousands of components
// hanging around, and less memory pressure caused by the WeakMap
var lazyGetter = function lazyGetter(type, fn) {
var secret = '_' + type + '$';
return {
get: function get() {
return this[secret] || setValue(this, secret, fn.call(this, type));
},
set: function set(value) {
setValue(this, secret, value);
}
};
}; // shortcut to set value on get or set(value)
var setValue = function setValue(self, secret, value) {
return Object.defineProperty(self, secret, {
configurable: true,
value: typeof value === 'function' ? function () {
return self._wire$ = value.apply(this, arguments);
} : value
})[secret];
};
Object.defineProperties(Component.prototype, {
// used to distinguish better than instanceof
ELEMENT_NODE: {
value: 1
},
nodeType: {
value: -1
}
});
var attributes = {};
var intents = {};
var keys = [];
var hasOwnProperty = intents.hasOwnProperty;
var length = 0;
var Intent = {
// used to invoke right away hyper:attributes
attributes: attributes,
// hyperHTML.define('intent', (object, update) => {...})
// can be used to define a third parts update mechanism
// when every other known mechanism failed.
// hyper.define('user', info => info.name);
// hyper(node)`<p>${{user}}</p>`;
define: function define(intent, callback) {
if (intent.indexOf('-') < 0) {
if (!(intent in intents)) {
length = keys.push(intent);
}
intents[intent] = callback;
} else {
attributes[intent] = callback;
}
},
// this method is used internally as last resort
// to retrieve a value out of an object
invoke: function invoke(object, callback) {
for (var i = 0; i < length; i++) {
var key = keys[i];
if (hasOwnProperty.call(object, key)) {
return intents[key](object[key], callback);
}
}
}
};
var isArray = Array.isArray || function (toString) {
/* istanbul ignore next */
var $ = toString.call([]);
/* istanbul ignore next */
return function isArray(object) {
return toString.call(object) === $;
};
}({}.toString);
/*! (c) Andrea Giammarchi - ISC */
var createContent = function (document) {
var FRAGMENT = 'fragment';
var TEMPLATE = 'template';
var HAS_CONTENT = ('content' in create(TEMPLATE));
var createHTML = HAS_CONTENT ? function (html) {
var template = create(TEMPLATE);
template.innerHTML = html;
return template.content;
} : function (html) {
var content = create(FRAGMENT);
var template = create(TEMPLATE);
var childNodes = null;
if (/^[^\S]*?<(col(?:group)?|t(?:head|body|foot|r|d|h))/i.test(html)) {
var selector = RegExp.$1;
template.innerHTML = '<table>' + html + '</table>';
childNodes = template.querySelectorAll(selector);
} else {
template.innerHTML = html;
childNodes = template.childNodes;
}
append(content, childNodes);
return content;
};
return function createContent(markup, type) {
return (type === 'svg' ? createSVG : createHTML)(markup);
};
function append(root, childNodes) {
var length = childNodes.length;
while (length--) {
root.appendChild(childNodes[0]);
}
}
function create(element) {
return element === FRAGMENT ? document.createDocumentFragment() : document.createElementNS('http://www.w3.org/1999/xhtml', element);
} // it could use createElementNS when hasNode is there
// but this fallback is equally fast and easier to maintain
// it is also battle tested already in all IE
function createSVG(svg) {
var content = create(FRAGMENT);
var template = create('div');
template.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg">' + svg + '</svg>';
append(content, template.firstChild.childNodes);
return content;
}
}(document);
/*! (c) Andrea Giammarchi */
function disconnected(poly) {
var Event = poly.Event;
var WeakSet = poly.WeakSet;
var notObserving = true;
var observer = null;
return function observe(node) {
if (notObserving) {
notObserving = !notObserving;
observer = new WeakSet();
startObserving(node.ownerDocument);
}
observer.add(node);
return node;
};
function startObserving(document) {
var connected = new WeakSet();
var disconnected = new WeakSet();
try {
new MutationObserver(changes).observe(document, {
subtree: true,
childList: true
});
} catch (o_O) {
var timer = 0;
var records = [];
var reschedule = function reschedule(record) {
records.push(record);
clearTimeout(timer);
timer = setTimeout(function () {
changes(records.splice(timer = 0, records.length));
}, 0);
};
document.addEventListener('DOMNodeRemoved', function (event) {
reschedule({
addedNodes: [],
removedNodes: [event.target]
});
}, true);
document.addEventListener('DOMNodeInserted', function (event) {
reschedule({
addedNodes: [event.target],
removedNodes: []
});
}, true);
}
function changes(records) {
for (var record, length = records.length, i = 0; i < length; i++) {
record = records[i];
dispatchAll(record.removedNodes, 'disconnected', disconnected, connected);
dispatchAll(record.addedNodes, 'connected', connected, disconnected);
}
}
function dispatchAll(nodes, type, wsin, wsout) {
for (var node, event = new Event(type), length = nodes.length, i = 0; i < length; (node = nodes[i++]).nodeType === 1 && dispatchTarget(node, event, type, wsin, wsout)) {
}
}
function dispatchTarget(node, event, type, wsin, wsout) {
if (observer.has(node) && !wsin.has(node)) {
wsout["delete"](node);
wsin.add(node);
node.dispatchEvent(event);
/*
// The event is not bubbling (perf reason: should it?),
// hence there's no way to know if
// stop/Immediate/Propagation() was called.
// Should DOM Level 0 work at all?
// I say it's a YAGNI case for the time being,
// and easy to implement in user-land.
if (!event.cancelBubble) {
var fn = node['on' + type];
if (fn)
fn.call(node, event);
}
*/
}
for (var // apparently is node.children || IE11 ... ^_^;;
// https://github.com/WebReflection/disconnected/issues/1
children = node.children || [], length = children.length, i = 0; i < length; dispatchTarget(children[i++], event, type, wsin, wsout)) {
}
}
}
}
/*! (c) Andrea Giammarchi - ISC */
var importNode = function (document, appendChild, cloneNode, createTextNode, importNode) {
var _native = (importNode in document); // IE 11 has problems with cloning templates:
// it "forgets" empty childNodes. This feature-detects that.
var fragment = document.createDocumentFragment();
fragment[appendChild](document[createTextNode]('g'));
fragment[appendChild](document[createTextNode](''));
/* istanbul ignore next */
var content = _native ? document[importNode](fragment, true) : fragment[cloneNode](true);
return content.childNodes.length < 2 ? function importNode(node, deep) {
var clone = node[cloneNode]();
for (var
/* istanbul ignore next */
childNodes = node.childNodes || [], length = childNodes.length, i = 0; deep && i < length; i++) {
clone[appendChild](importNode(childNodes[i], deep));
}
return clone;
} : _native ? document[importNode] : function (node, deep) {
return node[cloneNode](!!deep);
};
}(document, 'appendChild', 'cloneNode', 'createTextNode', 'importNode');
var trim = ''.trim ||
/* istanbul ignore next */
function () {
return String(this).replace(/^\s+|\s+/g, '');
};
/*! (c) Andrea Giammarchi - ISC */
// Custom
var UID = '-' + Math.random().toFixed(6) + '%'; // Edge issue!
var UID_IE = false;
try {
if (!function (template, content, tabindex) {
return content in template && (template.innerHTML = '<p ' + tabindex + '="' + UID + '"></p>', template[content].childNodes[0].getAttribute(tabindex) == UID);
}(document.createElement('template'), 'content', 'tabindex')) {
UID = '_dt: ' + UID.slice(1, -1) + ';';
UID_IE = true;
}
} catch (meh) {}
var UIDC = '<!--' + UID + '-->'; // DOM
var COMMENT_NODE = 8;
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var SHOULD_USE_TEXT_CONTENT = /^(?:plaintext|script|style|textarea|title|xmp)$/i;
var VOID_ELEMENTS = /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
/*! (c) Andrea Giammarchi - ISC */
function sanitize (template) {
return template.join(UIDC).replace(selfClosing, fullClosing).replace(attrSeeker, attrReplacer);
}
var spaces = ' \\f\\n\\r\\t';
var almostEverything = '[^' + spaces + '\\/>"\'=]+';
var attrName = '[' + spaces + ']+' + almostEverything;
var tagName = '<([A-Za-z]+[A-Za-z0-9:._-]*)((?:';
var attrPartials = '(?:\\s*=\\s*(?:\'[^\']*?\'|"[^"]*?"|<[^>]*?>|' + almostEverything.replace('\\/', '') + '))?)';
var attrSeeker = new RegExp(tagName + attrName + attrPartials + '+)([' + spaces + ']*/?>)', 'g');
var selfClosing = new RegExp(tagName + attrName + attrPartials + '*)([' + spaces + ']*/>)', 'g');
var findAttributes = new RegExp('(' + attrName + '\\s*=\\s*)([\'"]?)' + UIDC + '\\2', 'gi');
function attrReplacer($0, $1, $2, $3) {
return '<' + $1 + $2.replace(findAttributes, replaceAttributes) + $3;
}
function replaceAttributes($0, $1, $2) {
return $1 + ($2 || '"') + UID + ($2 || '"');
}
function fullClosing($0, $1, $2) {
return VOID_ELEMENTS.test($1) ? $0 : '<' + $1 + $2 + '></' + $1 + '>';
}
var umap = (function (_) {
return {
// About: get: _.get.bind(_)
// It looks like WebKit/Safari didn't optimize bind at all,
// so that using bind slows it down by 60%.
// Firefox and Chrome are just fine in both cases,
// so let's use the approach that works fast everywhere 👍
get: function get(key) {
return _.get(key);
},
set: function set(key, value) {
return _.set(key, value), value;
}
};
});
/* istanbul ignore next */
var normalizeAttributes = UID_IE ? function (attributes, parts) {
var html = parts.join(' ');
return parts.slice.call(attributes, 0).sort(function (left, right) {
return html.indexOf(left.name) <= html.indexOf(right.name) ? -1 : 1;
});
} : function (attributes, parts) {
return parts.slice.call(attributes, 0);
};
function find(node, path) {
var length = path.length;
var i = 0;
while (i < length) {
node = node.childNodes[path[i++]];
}
return node;
}
function parse(node, holes, parts, path) {
var childNodes = node.childNodes;
var length = childNodes.length;
var i = 0;
while (i < length) {
var child = childNodes[i];
switch (child.nodeType) {
case ELEMENT_NODE:
var childPath = path.concat(i);
parseAttributes(child, holes, parts, childPath);
parse(child, holes, parts, childPath);
break;
case COMMENT_NODE:
var textContent = child.textContent;
if (textContent === UID) {
parts.shift();
holes.push( // basicHTML or other non standard engines
// might end up having comments in nodes
// where they shouldn't, hence this check.
SHOULD_USE_TEXT_CONTENT.test(node.nodeName) ? Text(node, path) : Any(child, path.concat(i)));
} else {
switch (textContent.slice(0, 2)) {
case '/*':
if (textContent.slice(-2) !== '*/') break;
case "\uD83D\uDC7B":
// ghost
node.removeChild(child);
i--;
length--;
}
}
break;
case TEXT_NODE:
// the following ignore is actually covered by browsers
// only basicHTML ends up on previous COMMENT_NODE case
// instead of TEXT_NODE because it knows nothing about
// special style or textarea behavior
/* istanbul ignore if */
if (SHOULD_USE_TEXT_CONTENT.test(node.nodeName) && trim.call(child.textContent) === UIDC) {
parts.shift();
holes.push(Text(node, path));
}
break;
}
i++;
}
}
function parseAttributes(node, holes, parts, path) {
var attributes = node.attributes;
var cache = [];
var remove = [];
var array = normalizeAttributes(attributes, parts);
var length = array.length;
var i = 0;
while (i < length) {
var attribute = array[i++];
var direct = attribute.value === UID;
var sparse;
if (direct || 1 < (sparse = attribute.value.split(UIDC)).length) {
var name = attribute.name; // the following ignore is covered by IE
// and the IE9 double viewBox test
/* istanbul ignore else */
if (cache.indexOf(name) < 0) {
cache.push(name);
var realName = parts.shift().replace(direct ? /^(?:|[\S\s]*?\s)(\S+?)\s*=\s*('|")?$/ : new RegExp('^(?:|[\\S\\s]*?\\s)(' + name + ')\\s*=\\s*(\'|")[\\S\\s]*', 'i'), '$1');
var value = attributes[realName] || // the following ignore is covered by browsers
// while basicHTML is already case-sensitive
/* istanbul ignore next */
attributes[realName.toLowerCase()];
if (direct) holes.push(Attr(value, path, realName, null));else {
var skip = sparse.length - 2;
while (skip--) {
parts.shift();
}
holes.push(Attr(value, path, realName, sparse));
}
}
remove.push(attribute);
}
}
length = remove.length;
i = 0;
/* istanbul ignore next */
var cleanValue = 0 < length && UID_IE && !('ownerSVGElement' in node);
while (i < length) {
// Edge HTML bug #16878726
var attr = remove[i++]; // IE/Edge bug lighterhtml#63 - clean the value or it'll persist
/* istanbul ignore next */
if (cleanValue) attr.value = ''; // IE/Edge bug lighterhtml#64 - don't use removeAttributeNode
node.removeAttribute(attr.name);
} // This is a very specific Firefox/Safari issue
// but since it should be a not so common pattern,
// it's probably worth patching regardless.
// Basically, scripts created through strings are death.
// You need to create fresh new scripts instead.
// TODO: is there any other node that needs such nonsense?
var nodeName = node.nodeName;
if (/^script$/i.test(nodeName)) {
// this used to be like that
// var script = createElement(node, nodeName);
// then Edge arrived and decided that scripts created
// through template documents aren't worth executing
// so it became this ... hopefully it won't hurt in the wild
var script = document.createElement(nodeName);
length = attributes.length;
i = 0;
while (i < length) {
script.setAttributeNode(attributes[i++].cloneNode(true));
}
script.textContent = node.textContent;
node.parentNode.replaceChild(script, node);
}
}
function Any(node, path) {
return {
type: 'any',
node: node,
path: path
};
}
function Attr(node, path, name, sparse) {
return {
type: 'attr',
node: node,
path: path,
name: name,
sparse: sparse
};
}
function Text(node, path) {
return {
type: 'text',
node: node,
path: path
};
}
// globals
var parsed = umap(new WeakMap$1());
function createInfo(options, template) {
var markup = (options.convert || sanitize)(template);
var transform = options.transform;
if (transform) markup = transform(markup);
var content = createContent(markup, options.type);
cleanContent(content);
var holes = [];
parse(content, holes, template.slice(0), []);
return {
content: content,
updates: function updates(content) {
var updates = [];
var len = holes.length;
var i = 0;
var off = 0;
while (i < len) {
var info = holes[i++];
var node = find(content, info.path);
switch (info.type) {
case 'any':
updates.push({
fn: options.any(node, []),
sparse: false
});
break;
case 'attr':
var sparse = info.sparse;
var fn = options.attribute(node, info.name, info.node);
if (sparse === null) updates.push({
fn: fn,
sparse: false
});else {
off += sparse.length - 2;
updates.push({
fn: fn,
sparse: true,
values: sparse
});
}
break;
case 'text':
updates.push({
fn: options.text(node),
sparse: false
});
node.textContent = '';
break;
}
}
len += off;
return function () {
var length = arguments.length;
if (len !== length - 1) {
throw new Error(length - 1 + ' values instead of ' + len + '\n' + template.join('${value}'));
}
var i = 1;
var off = 1;
while (i < length) {
var update = updates[i - off];
if (update.sparse) {
var values = update.values;
var value = values[0];
var j = 1;
var l = values.length;
off += l - 2;
while (j < l) {
value += arguments[i++] + values[j++];
}
update.fn(value);
} else update.fn(arguments[i++]);
}
return content;
};
}
};
}
function createDetails(options, template) {
var info = parsed.get(template) || parsed.set(template, createInfo(options, template));
return info.updates(importNode.call(document, info.content, true));
}
var empty = [];
function domtagger(options) {
var previous = empty;
var updates = cleanContent;
return function (template) {
if (previous !== template) updates = createDetails(options, previous = template);
return updates.apply(null, arguments);
};
}
function cleanContent(fragment) {
var childNodes = fragment.childNodes;
var i = childNodes.length;
while (i--) {
var child = childNodes[i];
if (child.nodeType !== 1 && trim.call(child.textContent).length === 0) {
fragment.removeChild(child);
}
}
}
/*! (c) Andrea Giammarchi - ISC */
var hyperStyle = function () {
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
var hyphen = /([^A-Z])([A-Z]+)/g;
return function hyperStyle(node, original) {
return 'ownerSVGElement' in node ? svg(node, original) : update(node.style, false);
};
function ized($0, $1, $2) {
return $1 + '-' + $2.toLowerCase();
}
function svg(node, original) {
var style;
if (original) style = original.cloneNode(true);else {
node.setAttribute('style', '--hyper:style;');
style = node.getAttributeNode('style');
}
style.value = '';
node.setAttributeNode(style);
return update(style, true);
}
function toStyle(object) {
var key,
css = [];
for (key in object) {
css.push(key.replace(hyphen, ized), ':', object[key], ';');
}
return css.join('');
}
function update(style, isSVG) {
var oldType, oldValue;
return function (newValue) {
var info, key, styleValue, value;
switch (_typeof(newValue)) {
case 'object':
if (newValue) {
if (oldType === 'object') {
if (!isSVG) {
if (oldValue !== newValue) {
for (key in oldValue) {
if (!(key in newValue)) {
style[key] = '';
}
}
}
}
} else {
if (isSVG) style.value = '';else style.cssText = '';
}
info = isSVG ? {} : style;
for (key in newValue) {
value = newValue[key];
styleValue = typeof value === 'number' && !IS_NON_DIMENSIONAL.test(key) ? value + 'px' : value;
if (!isSVG && /^--/.test(key)) info.setProperty(key, styleValue);else info[key] = styleValue;
}
oldType = 'object';
if (isSVG) style.value = toStyle(oldValue = info);else oldValue = newValue;
break;
}
default:
if (oldValue != newValue) {
oldType = 'string';
oldValue = newValue;
if (isSVG) style.value = newValue || '';else style.cssText = newValue || '';
}
break;
}
};
}
}();
/*! (c) Andrea Giammarchi - ISC */
var Wire = function (slice, proto) {
proto = Wire.prototype;
proto.ELEMENT_NODE = 1;
proto.nodeType = 111;
proto.remove = function (keepFirst) {
var childNodes = this.childNodes;
var first = this.firstChild;
var last = this.lastChild;
this._ = null;
if (keepFirst && childNodes.length === 2) {
last.parentNode.removeChild(last);
} else {
var range = this.ownerDocument.createRange();
range.setStartBefore(keepFirst ? childNodes[1] : first);
range.setEndAfter(last);
range.deleteContents();
}
return first;
};
proto.valueOf = function (forceAppend) {
var fragment = this._;
var noFragment = fragment == null;
if (noFragment) fragment = this._ = this.ownerDocument.createDocumentFragment();
if (noFragment || forceAppend) {
for (var n = this.childNodes, i = 0, l = n.length; i < l; i++) {
fragment.appendChild(n[i]);
}
}
return fragment;
};
return Wire;
function Wire(childNodes) {
var nodes = this.childNodes = slice.call(childNodes, 0);
this.firstChild = nodes[0];
this.lastChild = nodes[nodes.length - 1];
this.ownerDocument = nodes[0].ownerDocument;
this._ = null;
}
}([].slice);
// Node.CONSTANTS
var DOCUMENT_FRAGMENT_NODE = 11; // SVG related constants
var OWNER_SVG_ELEMENT = 'ownerSVGElement'; // Custom Elements / MutationObserver constants
var CONNECTED = 'connected';
var DISCONNECTED = 'dis' + CONNECTED;
var componentType = Component.prototype.nodeType;
var wireType = Wire.prototype.nodeType;
var observe = disconnected({
Event: CustomEvent$1,
WeakSet: WeakSet$1
});
var asHTML = function asHTML(html) {
return {
html: html
};
}; // returns nodes from wires and components
var asNode = function asNode(item, i) {
switch (item.nodeType) {
case wireType:
// in the Wire case, the content can be
// removed, post-pended, inserted, or pre-pended and
// all these cases are handled by domdiff already
/* istanbul ignore next */
return 1 / i < 0 ? i ? item.remove(true) : item.lastChild : i ? item.valueOf(true) : item.firstChild;
case componentType:
return asNode(item.render(), i);
default:
return item;
}
}; // returns true if domdiff can handle the value
var canDiff = function canDiff(value) {
return 'ELEMENT_NODE' in value;
}; // borrowed from uhandlers
// https://github.com/WebReflection/uhandlers
var booleanSetter = function booleanSetter(node, key, oldValue) {
return function (newValue) {
if (oldValue !== !!newValue) {
if (oldValue = !!newValue) node.setAttribute(key, '');else node.removeAttribute(key);
}
};
};
var hyperSetter = function hyperSetter(node, name, svg) {
return svg ? function (value) {
try {
node[name] = value;
} catch (nope) {
node.setAttribute(name, value);
}
} : function (value) {
node[name] = value;
};
}; // when a Promise is used as interpolation value
// its result must be parsed once resolved.
// This callback is in charge of understanding what to do
// with a returned value once the promise is resolved.
var invokeAtDistance = function invokeAtDistance(value, callback) {
callback(value.placeholder);
if ('text' in value) {
Promise.resolve(value.text).then(String).then(callback);
} else if ('any' in value) {
Promise.resolve(value.any).then(callback);
} else if ('html' in value) {
Promise.resolve(value.html).then(asHTML).then(callback);
} else {
Promise.resolve(Intent.invoke(value, callback)).then(callback);
}
}; // quick and dirty way to check for Promise/ish values
var isPromise_ish = function isPromise_ish(value) {
return value != null && 'then' in value;
}; // list of attributes that should not be directly assigned
var readOnly = /^(?:form|list)$/i; // reused every slice time
var slice = [].slice; // simplifies text node creation
var text = function text(node, _text) {
return node.ownerDocument.createTextNode(_text);
};
function Tagger(type) {
this.type = type;
return domtagger(this);
}
Tagger.prototype = {
// there are four kind of attributes, and related behavior:
// * events, with a name starting with `on`, to add/remove event listeners
// * special, with a name present in their inherited prototype, accessed directly
// * regular, accessed through get/setAttribute standard DOM methods
// * style, the only regular attribute that also accepts an object as value
// so that you can style=${{width: 120}}. In this case, the behavior has been
// fully inspired by Preact library and its simplicity.
attribute: function attribute(node, name, original) {
var isSVG = (OWNER_SVG_ELEMENT in node);
var oldValue; // if the attribute is the style one
// handle it differently from others
if (name === 'style') return hyperStyle(node, original, isSVG); // direct accessors for <input .value=${...}> and friends
else if (name.slice(0, 1) === '.') return hyperSetter(node, name.slice(1), isSVG); // boolean accessors for <input .value=${...}> and friends
else if (name.slice(0, 1) === '?') return booleanSetter(node, name.slice(1)); // the name is an event one,
// add/remove event listeners accordingly
else if (/^on/.test(name)) {
var type = name.slice(2);
if (type === CONNECTED || type === DISCONNECTED) {
observe(node);
} else if (name.toLowerCase() in node) {
type = type.toLowerCase();
}
return function (newValue) {
if (oldValue !== newValue) {
if (oldValue) node.removeEventListener(type, oldValue, false);
oldValue = newValue;
if (newValue) node.addEventListener(type, newValue, false);
}
};
} // the attribute is special ('value' in input)
// and it's not SVG *or* the name is exactly data,
// in this case assign the value directly
else if (name === 'data' || !isSVG && name in node && !readOnly.test(name)) {
return function (newValue) {
if (oldValue !== newValue) {
oldValue = newValue;
if (node[name] !== newValue && newValue == null) {
// cleanup on null to avoid silly IE/Edge bug
node[name] = '';
node.removeAttribute(name);
} else node[name] = newValue;
}
};
} else if (name in Intent.attributes) {
return function (any) {
var newValue = Intent.attributes[name](node, any);
if (oldValue !== newValue) {
oldValue = newValue;
if (newValue == null) node.removeAttribute(name);else node.setAttribute(name, newValue);
}
};
} // in every other case, use the attribute node as it is
// update only the value, set it as node only when/if needed
else {
var owner = false;
var attribute = original.cloneNode(true);
return function (newValue) {
if (oldValue !== newValue) {
oldValue = newValue;
if (attribute.value !== newValue) {
if (newValue == null) {
if (owner) {
owner = false;
node.removeAttributeNode(attribute);
}
attribute.value = newValue;
} else {
attribute.value = newValue;
if (!owner) {
owner = true;
node.setAttributeNode(attribute);
}
}
}
}
};
}
},
// in a hyper(node)`<div>${content}</div>` case
// everything could happen:
// * it's a JS primitive, stored as text
// * it's null or undefined, the node should be cleaned
// * it's a component, update the content by rendering it
// * it's a promise, update the content once resolved
// * it's an explicit intent, perform the desired operation
// * it's an Array, resolve all values if Promises and/or
// update the node with the resulting list of content
any: function any(node, childNodes) {
var diffOptions = {
node: asNode,
before: node
};
var nodeType = OWNER_SVG_ELEMENT in node ?
/* istanbul ignore next */
'svg' : 'html';
var fastPath = false;
var oldValue;
var anyContent = function anyContent(value) {
switch (_typeof(value)) {
case 'string':
case 'number':
case 'boolean':
if (fastPath) {
if (oldValue !== value) {
oldValue = value;
childNodes[0].textContent = value;
}
} else {
fastPath = true;
oldValue = value;
childNodes = domdiff(node.parentNode, childNodes, [text(node, value)], diffOptions);
}
break;
case 'function':
anyContent(value(node));
break;
case 'object':
case 'undefined':
if (value == null) {
fastPath = false;
childNodes = domdiff(node.parentNode, childNodes, [], diffOptions);
break;
}
default:
fastPath = false;
oldValue = value;
if (isArray(value)) {
if (value.length === 0) {
if (childNodes.length) {
childNodes = domdiff(node.parentNode, childNodes, [], diffOptions);
}
} else {
switch (_typeof(value[0])) {
case 'string':
case 'number':
case 'boolean':
anyContent({
html: value
});
break;
case 'object':
if (isArray(value[0])) {
value = value.concat.apply([], value);
}
if (isPromise_ish(value[0])) {
Promise.all(value).then(anyContent);
break;
}
default:
childNodes = domdiff(node.parentNode, childNodes, value, diffOptions);
break;
}
}
} else if (canDiff(value)) {
childNodes = domdiff(node.parentNode, childNodes, value.nodeType === DOCUMENT_FRAGMENT_NODE ? slice.call(value.childNodes) : [value], diffOptions);
} else if (isPromise_ish(value)) {
value.then(anyContent);
} else if ('placeholder' in value) {
invokeAtDistance(value, anyContent);
} else if ('text' in value) {
anyContent(String(value.text));
} else if ('any' in value) {
anyContent(value.any);
} else if ('html' in value) {
childNodes = domdiff(node.parentNode, childNodes, slice.call(createContent([].concat(value.html).join(''), nodeType).childNodes), diffOptions);
} else if ('length' in value) {
anyContent(slice.call(value));
} else {
anyContent(Intent.invoke(value, anyContent));
}
break;
}
};
return anyContent;
},
// style or textareas don't accept HTML as content
// it's pointless to transform or analyze anything
// different from text there but it's worth checking
// for possible defined intents.
text: function text(node) {
var oldValue;
var textContent = function textContent(value) {
if (oldValue !== value) {
oldValue = value;
var type = _typeof(value);
if (type === 'object' && value) {
if (isPromise_ish(value)) {
value.then(textContent);
} else if ('placeholder' in value) {
invokeAtDistance(value, textContent);
} else if ('text' in value) {
textContent(String(value.text));
} else if ('any' in value) {
textContent(value.any);
} else if ('html' in value) {
textContent([].concat(value.html).join(''));
} else if ('length' in value) {
textContent(slice.call(value).join(''));
} else {
textContent(Intent.invoke(value, textContent));
}
} else if (type === 'function') {
textContent(value(node));
} else {
node.textContent = value == null ? '' : value;
}
}
};
return textContent;
}
};
var isNoOp = (typeof document === "undefined" ? "undefined" : _typeof(document)) !== 'object';
var _templateLiteral = function templateLiteral(tl) {
var RAW = 'raw';
var isBroken = function isBroken(UA) {
return /(Firefox|Safari)\/(\d+)/.test(UA) && !/(Chrom[eium]+|Android)\/(\d+)/.test(UA);
};
var broken = isBroken((document.defaultView.navigator || {}).userAgent);
var FTS = !(RAW in tl) || tl.propertyIsEnumerable(RAW) || !Object.isFrozen(tl[RAW]);
if (broken || FTS) {
var forever = {};
var foreverCache = function foreverCache(tl) {
for (var key = '.', i = 0; i < tl.length; i++) {
key += tl[i].length + '.' + tl[i];
}
return forever[key] || (forever[key] = tl);
}; // Fallback TypeScript shenanigans
if (FTS) _templateLiteral = foreverCache; // try fast path for other browsers:
// store the template as WeakMap key
// and forever cache it only when it's not there.
// this way performance is still optimal,
// penalized only when there are GC issues
else {
var wm = new WeakMap$1();
var set = function set(tl, unique) {
wm.set(tl, unique);
return unique;
};
_templateLiteral = function templateLiteral(tl) {
return wm.get(tl) || set(tl, foreverCache(tl));
};
}
} else {
isNoOp = true;
}
return TL(tl);
};
function TL(tl) {
return isNoOp ? tl : _templateLiteral(tl);
}
function tta (template) {
var length = arguments.length;
var args = [TL(template)];
var i = 1;
while (i < length) {
args.push(arguments[i++]);
}
return args;
}
/**
* best benchmark goes here
* https://jsperf.com/tta-bench
* I should probably have an @ungap/template-literal-es too
export default (...args) => {
args[0] = unique(args[0]);
return args;
};
*/
var wires = new WeakMap$1(); // A wire is a callback used as tag function
// to lazily relate a generic object to a template literal.
// hyper.wire(user)`<div id=user>${user.name}</div>`; => the div#user
// This provides the ability to have a unique DOM structure
// related to a unique JS object through a reusable template literal.
// A wire can specify a type, as svg or html, and also an id
// via html:id or :id convention. Such :id allows same JS objects
// to be associated to different DOM structures accordingly with
// the used template literal without losing previously rendered parts.
var wire = function wire(obj, type) {
return obj == null ? content(type || 'html') : weakly(obj, type || 'html');
}; // A wire content is a virtual reference to one or more nodes.
// It's represented by either a DOM node, or an Array.
// In both cases, the wire content role is to simply update
// all nodes through the list of related callbacks.
// In few words, a wire content is like an invisible parent node
// in charge of updating its content like a bound element would do.
var content = function content(type) {
var wire, tagger, template;
return function () {
var args = tta.apply(null, arguments);
if (template !== args[0]) {
template = args[0];
tagger = new Tagger(type);
wire = wireContent(tagger.apply(tagger, args));
} else {
tagger.apply(tagger, args);
}
return wire;
};
}; // wires are weakly created through objects.
// Each object can have multiple wires associated
// and this is thanks to the type + :id feature.
var weakly = function weakly(obj, type) {
var i = type.indexOf(':');
var wire = wires.get(obj);
var id = type;
if (-1 < i) {
id = type.slice(i + 1);
type = type.slice(0, i) || 'html';
}
if (!wire) wires.set(obj, wire = {});
return wire[id] || (wire[id] = content(type));
}; // A document fragment loses its nodes
// as soon as it is appended into another node.
// This has the undesired effect of losing wired content
// on a second render call, because (by then) the fragment would be empty:
// no longer providing access to those sub-nodes that ultimately need to
// stay associated with the original interpolation.
// To prevent hyperHTML from forgetting about a fragment's sub-nodes,
// fragments are instead returned as an Array of nodes or, if there's only one entry,
// as a single referenced node which, unlike fragments, will indeed persist
// wire content throughout multiple renderings.
// The initial fragment, at this point, would be used as unique reference to this
// array of nodes or to this single referenced node.
var wireContent = function wireContent(node) {
var childNodes = node.childNodes;
var length = childNodes.length;
return length === 1 ? childNodes[0] : length ? new Wire(childNodes) : node;
};
// are already known to hyperHTML
var bewitched = new WeakMap$1(); // better known as hyper.bind(node), the render is
// the main tag function in charge of fully upgrading
// or simply updating, contexts used as hyperHTML targets.
// The `this` context is either a regular DOM node or a fragment.
function render() {
var wicked = bewitched.get(this);
var args = tta.apply(null, arguments);
if (wicked && wicked.template === args[0]) {
wicked.tagger.apply(null, args);
} else {
upgrade.apply(this, args);
}
return this;
} // an upgrade is in charge of collecting template info,
// parse it once, if unknown, to map all interpolations
// as single DOM callbacks, relate such template
// to the current context, and render it after cleaning the context up
function upgrade(template) {
var type = OWNER_SVG_ELEMENT in this ? 'svg' : 'html';
var tagger = new Tagger(type);
bewitched.set(this, {
tagger: tagger,
template: template
});
this.textContent = '';
this.appendChild(tagger.apply(null, arguments));
}
/*! (c) Andrea Giammarchi (ISC) */
// you can do the following
// const {bind, wire} = hyperHTML;
// and use them right away: bind(node)`hello!`;
var bind = function bind(context) {
return render.bind(context);
};
var define = Intent.define;
var tagger = Tagger.prototype;
hyper.Component = Component;
hyper.bind = bind;
hyper.define = define;
hyper.diff = domdiff;
hyper.hyper = hyper;
hyper.observe = observe;
hyper.tagger = tagger;
hyper.wire = wire; // exported as shared utils
// for projects based on hyperHTML
// that don't necessarily need upfront polyfills
// i.e. those still targeting IE
hyper._ = {
WeakMap: WeakMap$1,
WeakSet: WeakSet$1
}; // the wire content is the lazy defined
// html or svg property of each hyper.Component
setup(content); // everything is exported directly or through the
// that "magically" understands what's the best
// thing to do with passed arguments
function hyper(HTML) {
return arguments.length < 2 ? HTML == null ? content('html') : typeof HTML === 'string' ? hyper.wire(null, HTML) : 'raw' in HTML ? content('html')(HTML) : 'nodeType' in HTML ? hyper.bind(HTML) : weakly(HTML, 'html') : ('raw' in HTML ? content('html') : hyper.wire).apply(null, arguments);
}
var ATTRIBUTE_CHANGED_CALLBACK = 'attributeChangedCallback';
var O = Object;
var classes = [];
var defineProperty = O.defineProperty;
var getOwnPropertyDescriptor = O.getOwnPropertyDescriptor;
var getOwnPropertyNames = O.getOwnPropertyNames;
/* istanbul ignore next */
var getOwnPropertySymbols = O.getOwnPropertySymbols || function () {
return [];
};
/* istanbul ignore next */
var getPrototypeOf = O.getPrototypeOf || function (o) {
return o.__proto__;
};
/* istanbul ignore next */
var ownKeys = (typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === 'object' && Reflect.ownKeys || function (o) {
return getOwnPropertyNames(o).concat(getOwnPropertySymbols(o));
};
/* istanbul ignore next */
var setPrototypeOf = O.setPrototypeOf || function (o, p) {
return o.__proto__ = p, o;
};
/* istanbul ignore stop */
var camel = function camel(name) {
return name.replace(/-([a-z])/g, function ($0, $1) {
return $1.toUpperCase();
});
};
var _attachShadow = HTMLElement.prototype.attachShadow;
var sr = new WeakMap();
var HyperHTMLElement = /*#__PURE__*/function (_HTMLElement) {
_inherits(HyperHTMLElement, _HTMLElement);
var _super = _createSuper(HyperHTMLElement);
function HyperHTMLElement() {
_classCallCheck(this, HyperHTMLElement);
return _super.apply(this, arguments);
}
_createClass(HyperHTMLElement, [{
key: "attachShadow",
value: // weakly relate the shadowRoot for refs usage
function attachShadow() {
var shadowRoot = _attachShadow.apply(this, arguments);
sr.set(this, shadowRoot);
return shadowRoot;
} // returns elements by ref
}, {
key: "refs",
get: function get() {
var value = {};
if ('_html$' in this) {
var all = (sr.get(this) || this).querySelectorAll('[ref]');
for (var length = all.length, i = 0; i < length; i++) {
var node = all[i];
value[node.getAttribute('ref')] = node;
}
Object.defineProperty(this, 'refs', {
value: value
});
return value;
}
return value;
} // lazily bind once hyperHTML logic
// to either the shadowRoot, if present and open,
// the _shadowRoot property, if set due closed shadow root,
// or the custom-element itself if no Shadow DOM is used.
}, {
key: "html",
get: function get() {
return this._html$ || (this.html = bind( // in a way or another, bind to the right node
// backward compatible, first two could probably go already
this.shadowRoot || this._shadowRoot || sr.get(this) || this));
} // it can be set too if necessary, it won't invoke render()
,
set: function set(value) {
defineProperty(this, '_html$', {
configurable: true,
value: value
});
} // overwrite this method with your own render
}, {
key: "render",
value: function render() {} // ---------------------//
// Basic State Handling //
// ---------------------//
// define the default state object
// you could use observed properties too
}, {
key: "defaultState",
get: function get() {
return {};
} // the state with a default
}, {
key: "state",
get: function get() {
return this._state$ || (this.state = this.defaultState);
} // it can be set too if necessary, it won't invoke render()
,
set: function set(value) {
defineProperty(this, '_state$', {
configurable: true,
value: value
});
} // currently a state is a shallow copy, like in Preact or other libraries.
// after the state is updated, the render() method will be invoked.
// ⚠️ do not ever call this.setState() inside this.render()
}, {
key: "setState",
value: function setState(state, render) {
var target = this.state;
var source = typeof state === 'function' ? state.call(this, target) : state;
for (var key in source) {
target[key] = source[key];
}
if (render !== false) this.render();
return this;
}
}], [{
key: "define",
value: // define a custom-element in the CustomElementsRegistry
// class MyEl extends HyperHTMLElement {}
// MyEl.define('my-el');
function define(name, options) {
var Class = this;
var proto = Class.prototype;
var onChanged = proto[ATTRIBUTE_CHANGED_CALLBACK];
var hasChange = !!onChanged; // Class.booleanAttributes
// -----------------------------------------------
// attributes defined as boolean will have
// an either available or not available attribute
// regardless of the value.
// All falsy values, or "false", mean attribute removed
// while truthy values will be set as is.
// Boolean attributes are also automatically observed.
var booleanAttributes = Class.booleanAttributes || [];
booleanAttributes.forEach(function (attribute) {
var name = camel(attribute);
if (!(name in proto)) defineProperty(proto, name, {
configurable: true,
get: function get() {
return this.hasAttribute(attribute);
},
set: function set(value) {
if (!value || value === 'false') this.removeAttribute(attribute);else this.setAttribute(attribute, '');
}
});
}); // Class.observedAttributes
// -------------------------------------------------------
// HyperHTMLElement will directly reflect get/setAttribute
// operation once these attributes are used, example:
// el.observed = 123;
// will automatically do
// el.setAttribute('observed', 123);
// triggering also the attributeChangedCallback
var observedAttributes = (Class.observedAttributes || []).filter(function (attribute) {
return booleanAttributes.indexOf(attribute) < 0;
});
observedAttributes.forEach(function (attribute) {
// it is possible to redefine the behavior at any time
// simply overwriting get prop() and set prop(value)
var name = camel(attribute);
if (!(name in proto)) defineProperty(proto, name, {
configurable: true,
get: function get() {
return this.getAttribute(attribute);
},
set: function set(value) {
if (value == null) this.removeAttribute(attribute);else this.setAttribute(attribute, value);
}
});
}); // if these are defined, overwrite the observedAttributes getter
// to include also booleanAttributes
var attributes = booleanAttributes.concat(observedAttributes);
if (attributes.length) defineProperty(Class, 'observedAttributes', {
get: function get() {
return attributes;
}
}); // created() {}
// ---------------------------------
// an initializer method that grants
// the node is fully known to the browser.
// It is ensured to run either after DOMContentLoaded,
// or once there is a next sibling (stream-friendly) so that
// you have full access to element attributes and/or childNodes.
var created = proto.created || function () {
this.render();
}; // used to ensure create() is called once and once only
defineProperty(proto, '_init$', {
configurable: true,
writable: true,
value: true
});
defineProperty(proto, ATTRIBUTE_CHANGED_CALLBACK, {
configurable: true,
value: function aCC(name, prev, curr) {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$) return this._init$$.push(aCC.bind(this, name, prev, curr));
} // ensure setting same value twice
// won't trigger twice attributeChangedCallback
if (hasChange && prev !== curr) {
onChanged.apply(this, arguments);
}
}
});
var onConnected = proto.connectedCallback;
var hasConnect = !!onConnected;
defineProperty(proto, 'connectedCallback', {
configurable: true,
value: function cC() {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$) return this._init$$.push(cC.bind(this));
}
if (hasConnect) {
onConnected.apply(this, arguments);
}
}
}); // define lazily all handlers
// class { handleClick() { ... }
// render() { `<a onclick=${this.handleClick}>` } }
getOwnPropertyNames(proto).forEach(function (key) {
if (/^handle[A-Z]/.test(key)) {
var _key$ = '_' + key + '$';
var method = proto[key];
defineProperty(proto, key, {
configurable: true,
get: function get() {
return this[_key$] || (this[_key$] = method.bind(this));
}
});
}
}); // whenever you want to directly use the component itself
// as EventListener, you can pass it directly.
// https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
// class Reactive extends HyperHTMLElement {
// oninput(e) { console.log(this, 'changed', e.target.value); }
// render() { this.html`<input oninput="${this}">`; }
// }
if (!('handleEvent' in proto)) {
defineProperty(proto, 'handleEvent', {
configurable: true,
value: function value(event) {
this[(event.currentTarget.dataset || {}).call || 'on' + event.type](event);
}
});
}
if (options && options["extends"]) {
var Native = document.createElement(options["extends"]).constructor;
var Intermediate = /*#__PURE__*/function (_Native) {
_inherits(Intermediate, _Native);
var _super2 = _createSuper(Intermediate);
function Intermediate() {
_classCallCheck(this, Intermediate);
return _super2.apply(this, arguments);
}
return Intermediate;
}(Native);
var ckeys = ['length', 'name', 'arguments', 'caller', 'prototype'];
var pkeys = [];
var Super = null;
var BaseClass = Class;
while (Super = getPrototypeOf(BaseClass)) {
[{
target: Intermediate,
base: Super,
keys: ckeys
}, {
target: Intermediate.prototype,
base: Super.prototype,
keys: pkeys
}].forEach(function (_ref) {
var target = _ref.target,
base = _ref.base,
keys = _ref.keys;
ownKeys(base).filter(function (key) {
return keys.indexOf(key) < 0;
}).forEach(function (key) {
keys.push(key);
defineProperty(target, key, getOwnPropertyDescriptor(base, key));
});
});
BaseClass = Super;
if (Super === HyperHTMLElement) break;
}
setPrototypeOf(Class, Intermediate);
setPrototypeOf(proto, Intermediate.prototype);
customElements.define(name, Class, options);
} else {
customElements.define(name, Class);
}
classes.push(Class);
return Class;
}
}]);
return HyperHTMLElement;
}( /*#__PURE__*/_wrapNativeSuper(HTMLElement));
HyperHTMLElement.Component = Component;
HyperHTMLElement.bind = bind;
HyperHTMLElement.intent = define;
HyperHTMLElement.wire = wire;
HyperHTMLElement.hyper = hyper;
try {
if (Symbol.hasInstance) classes.push(defineProperty(HyperHTMLElement, Symbol.hasInstance, {
enumerable: false,
configurable: true,
value: function value(instance) {
return classes.some(isPrototypeOf, getPrototypeOf(instance));
}
}));
} catch (meh) {}
// DOMContentLoaded VS created() //
// ------------------------------//
var dom = {
type: 'DOMContentLoaded',
handleEvent: function handleEvent() {
if (dom.ready()) {
document.removeEventListener(dom.type, dom, false);
dom.list.splice(0).forEach(invoke);
} else setTimeout(dom.handleEvent);
},
ready: function ready() {
return document.readyState === 'complete';
},
list: []
};
if (!dom.ready()) {
document.addEventListener(dom.type, dom, false);
}
function checkReady(created, attributes, booleanAttributes) {
if (dom.ready() || isReady.call(this, created, attributes, booleanAttributes)) {
if (this._init$) {
var list = this._init$$ || [];
delete this._init$$;
var self = defineProperty(this, '_init$', {
value: false
});
booleanAttributes.forEach(function (name) {
if (self.getAttribute(name) === 'false') self.removeAttribute(name);
});
attributes.forEach(function (name) {
if (self.hasOwnProperty(name)) {
var curr = self[name];
delete self[name];
list.unshift(function () {
self[name] = curr;
});
}
});
created.call(self);
list.forEach(invoke);
}
} else {
if (!this.hasOwnProperty('_init$$')) defineProperty(this, '_init$$', {
configurable: true,
value: []
});
dom.list.push(checkReady.bind(this, created, attributes, booleanAttributes));
}
}
function invoke(fn) {
fn();
}
function isPrototypeOf(Class) {
return this === Class.prototype;
}
function isReady(created, attributes, booleanAttributes) {
var el = this;
do {
if (el.nextSibling) return true;
} while (el = el.parentNode);
setTimeout(checkReady.bind(this, created, attributes, booleanAttributes));
return false;
}
exports['default'] = HyperHTMLElement;
Object.defineProperty(exports, '__esModule', { value: true });
return exports["default"];
}({}));
================================================
FILE: esm/index.d.ts
================================================
import HyperHTMLElement from "..";
export * from '..';
export default HyperHTMLElement;
================================================
FILE: esm/index.js
================================================
/*! (C) 2017-2018 Andrea Giammarchi - ISC Style License */
import {Component, bind, define, hyper, wire} from 'hyperhtml';
// utils to deal with custom elements builtin extends
const ATTRIBUTE_CHANGED_CALLBACK = 'attributeChangedCallback';
const O = Object;
const classes = [];
const defineProperty = O.defineProperty;
const getOwnPropertyDescriptor = O.getOwnPropertyDescriptor;
const getOwnPropertyNames = O.getOwnPropertyNames;
/* istanbul ignore next */
const getOwnPropertySymbols = O.getOwnPropertySymbols || (() => []);
/* istanbul ignore next */
const getPrototypeOf = O.getPrototypeOf || (o => o.__proto__);
/* istanbul ignore next */
const ownKeys = typeof Reflect === 'object' && Reflect.ownKeys ||
(o => getOwnPropertyNames(o).concat(getOwnPropertySymbols(o)));
/* istanbul ignore next */
const setPrototypeOf = O.setPrototypeOf ||
((o, p) => (o.__proto__ = p, o));
/* istanbul ignore stop */
const camel = name => name.replace(/-([a-z])/g, ($0, $1) => $1.toUpperCase());
const {attachShadow} = HTMLElement.prototype;
const sr = new WeakMap;
class HyperHTMLElement extends HTMLElement {
// define a custom-element in the CustomElementsRegistry
// class MyEl extends HyperHTMLElement {}
// MyEl.define('my-el');
static define(name, options) {
const Class = this;
const proto = Class.prototype;
const onChanged = proto[ATTRIBUTE_CHANGED_CALLBACK];
const hasChange = !!onChanged;
// Class.booleanAttributes
// -----------------------------------------------
// attributes defined as boolean will have
// an either available or not available attribute
// regardless of the value.
// All falsy values, or "false", mean attribute removed
// while truthy values will be set as is.
// Boolean attributes are also automatically observed.
const booleanAttributes = Class.booleanAttributes || [];
booleanAttributes.forEach(attribute => {
const name = camel(attribute);
if (!(name in proto)) defineProperty(
proto,
name,
{
configurable: true,
get() {
return this.hasAttribute(attribute);
},
set(value) {
if (!value || value === 'false')
this.removeAttribute(attribute);
else
this.setAttribute(attribute, '');
}
}
);
});
// Class.observedAttributes
// -------------------------------------------------------
// HyperHTMLElement will directly reflect get/setAttribute
// operation once these attributes are used, example:
// el.observed = 123;
// will automatically do
// el.setAttribute('observed', 123);
// triggering also the attributeChangedCallback
const observedAttributes = (Class.observedAttributes || []).filter(
attribute => booleanAttributes.indexOf(attribute) < 0
);
observedAttributes.forEach(attribute => {
// it is possible to redefine the behavior at any time
// simply overwriting get prop() and set prop(value)
const name = camel(attribute);
if (!(name in proto)) defineProperty(
proto,
name,
{
configurable: true,
get() {
return this.getAttribute(attribute);
},
set(value) {
if (value == null)
this.removeAttribute(attribute);
else
this.setAttribute(attribute, value);
}
}
);
});
// if these are defined, overwrite the observedAttributes getter
// to include also booleanAttributes
const attributes = booleanAttributes.concat(observedAttributes);
if (attributes.length)
defineProperty(Class, 'observedAttributes', {
get() { return attributes; }
});
// created() {}
// ---------------------------------
// an initializer method that grants
// the node is fully known to the browser.
// It is ensured to run either after DOMContentLoaded,
// or once there is a next sibling (stream-friendly) so that
// you have full access to element attributes and/or childNodes.
const created = proto.created || function () {
this.render();
};
// used to ensure create() is called once and once only
defineProperty(
proto,
'_init$',
{
configurable: true,
writable: true,
value: true
}
);
defineProperty(
proto,
ATTRIBUTE_CHANGED_CALLBACK,
{
configurable: true,
value: function aCC(name, prev, curr) {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$)
return this._init$$.push(aCC.bind(this, name, prev, curr));
}
// ensure setting same value twice
// won't trigger twice attributeChangedCallback
if (hasChange && prev !== curr) {
onChanged.apply(this, arguments);
}
}
}
);
const onConnected = proto.connectedCallback;
const hasConnect = !!onConnected;
defineProperty(
proto,
'connectedCallback',
{
configurable: true,
value: function cC() {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$)
return this._init$$.push(cC.bind(this));
}
if (hasConnect) {
onConnected.apply(this, arguments);
}
}
}
);
// define lazily all handlers
// class { handleClick() { ... }
// render() { `<a onclick=${this.handleClick}>` } }
getOwnPropertyNames(proto).forEach(key => {
if (/^handle[A-Z]/.test(key)) {
const _key$ = '_' + key + '$';
const method = proto[key];
defineProperty(proto, key, {
configurable: true,
get() {
return this[_key$] ||
(this[_key$] = method.bind(this));
}
});
}
});
// whenever you want to directly use the component itself
// as EventListener, you can pass it directly.
// https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
// class Reactive extends HyperHTMLElement {
// oninput(e) { console.log(this, 'changed', e.target.value); }
// render() { this.html`<input oninput="${this}">`; }
// }
if (!('handleEvent' in proto)) {
defineProperty(
proto,
'handleEvent',
{
configurable: true,
value(event) {
this[
(event.currentTarget.dataset || {}).call ||
('on' + event.type)
](event);
}
}
);
}
if (options && options.extends) {
const Native = document.createElement(options.extends).constructor;
const Intermediate = class extends Native {};
const ckeys = ['length', 'name', 'arguments', 'caller', 'prototype'];
const pkeys = [];
let Super = null;
let BaseClass = Class;
while (Super = getPrototypeOf(BaseClass)) {
[
{target: Intermediate, base: Super, keys: ckeys},
{target: Intermediate.prototype, base: Super.prototype, keys: pkeys}
]
.forEach(({target, base, keys}) => {
ownKeys(base)
.filter(key => keys.indexOf(key) < 0)
.forEach((key) => {
keys.push(key);
defineProperty(
target,
key,
getOwnPropertyDescriptor(base, key)
);
});
});
BaseClass = Super;
if (Super === HyperHTMLElement)
break;
}
setPrototypeOf(Class, Intermediate);
setPrototypeOf(proto, Intermediate.prototype);
customElements.define(name, Class, options);
} else {
customElements.define(name, Class);
}
classes.push(Class);
return Class;
}
// weakly relate the shadowRoot for refs usage
attachShadow() {
const shadowRoot = attachShadow.apply(this, arguments);
sr.set(this, shadowRoot);
return shadowRoot;
}
// returns elements by ref
get refs() {
const value = {};
if ('_html$' in this) {
const all = (sr.get(this) || this).querySelectorAll('[ref]');
for (let {length} = all, i = 0; i < length; i++) {
const node = all[i];
value[node.getAttribute('ref')] = node;
}
Object.defineProperty(this, 'refs', {value});
return value;
}
return value;
}
// lazily bind once hyperHTML logic
// to either the shadowRoot, if present and open,
// the _shadowRoot property, if set due closed shadow root,
// or the custom-element itself if no Shadow DOM is used.
get html() {
return this._html$ || (this.html = bind(
// in a way or another, bind to the right node
// backward compatible, first two could probably go already
this.shadowRoot || this._shadowRoot || sr.get(this) || this
));
}
// it can be set too if necessary, it won't invoke render()
set html(value) {
defineProperty(this, '_html$', {configurable: true, value: value});
}
// overwrite this method with your own render
render() {}
// ---------------------//
// Basic State Handling //
// ---------------------//
// define the default state object
// you could use observed properties too
get defaultState() { return {}; }
// the state with a default
get state() {
return this._state$ || (this.state = this.defaultState);
}
// it can be set too if necessary, it won't invoke render()
set state(value) {
defineProperty(this, '_state$', {configurable: true, value: value});
}
// currently a state is a shallow copy, like in Preact or other libraries.
// after the state is updated, the render() method will be invoked.
// ⚠️ do not ever call this.setState() inside this.render()
setState(state, render) {
const target = this.state;
const source = typeof state === 'function' ? state.call(this, target) : state;
for (const key in source) target[key] = source[key];
if (render !== false) this.render();
return this;
}
};
// exposing hyperHTML utilities
HyperHTMLElement.Component = Component;
HyperHTMLElement.bind = bind;
HyperHTMLElement.intent = define;
HyperHTMLElement.wire = wire;
HyperHTMLElement.hyper = hyper;
try {
if (Symbol.hasInstance) classes.push(
defineProperty(HyperHTMLElement, Symbol.hasInstance, {
enumerable: false,
configurable: true,
value(instance) {
return classes.some(isPrototypeOf, getPrototypeOf(instance));
}
}));
} catch(meh) {}
export default HyperHTMLElement;
// ------------------------------//
// DOMContentLoaded VS created() //
// ------------------------------//
const dom = {
type: 'DOMContentLoaded',
handleEvent() {
if (dom.ready()) {
document.removeEventListener(dom.type, dom, false);
dom.list.splice(0).forEach(invoke);
}
else
setTimeout(dom.handleEvent);
},
ready() {
return document.readyState === 'complete';
},
list: []
};
if (!dom.ready()) {
document.addEventListener(dom.type, dom, false);
}
function checkReady(created, attributes, booleanAttributes) {
if (dom.ready() || isReady.call(this, created, attributes, booleanAttributes)) {
if (this._init$) {
const list = this._init$$ || [];
delete this._init$$;
const self = defineProperty(this, '_init$', {value: false});
booleanAttributes.forEach(name => {
if (self.getAttribute(name) === 'false')
self.removeAttribute(name);
});
attributes.forEach(name => {
if (self.hasOwnProperty(name)) {
const curr = self[name];
delete self[name];
list.unshift(() => { self[name] = curr; });
}
});
created.call(self);
list.forEach(invoke);
}
} else {
if (!this.hasOwnProperty('_init$$'))
defineProperty(this, '_init$$', {configurable: true, value: []});
dom.list.push(checkReady.bind(this, created, attributes, booleanAttributes));
}
}
function invoke(fn) {
fn();
}
function isPrototypeOf(Class) {
return this === Class.prototype;
}
function isReady(created, attributes, booleanAttributes) {
let el = this;
do { if (el.nextSibling) return true; }
while (el = el.parentNode);
setTimeout(checkReady.bind(this, created, attributes, booleanAttributes));
return false;
}
================================================
FILE: esm.config.js
================================================
import resolve from 'rollup-plugin-node-resolve';
export default {
input: 'esm/index.js',
plugins: [
resolve({
module: true
})
],
context: 'null',
moduleContext: 'null',
output: {
exports: 'named',
file: 'index.js',
format: 'iife',
name: 'HyperHTMLElement'
}
};
================================================
FILE: index.d.ts
================================================
import { bind, hyper, wire, define, Component, WiredTemplateFunction } from "hyperhtml";
interface HyperHTMLElement<T = {}> extends HTMLElement {
onabort(ev: UIEvent): void;
onactivate(this: HTMLElement, ev: Event): any;
onbeforeactivate(this: HTMLElement, ev: Event): any;
onbeforecopy(this: HTMLElement, ev: Event): any;
onbeforecut(this: HTMLElement, ev: Event): any;
onbeforedeactivate(this: HTMLElement, ev: Event): any;
onbeforepaste(this: HTMLElement, ev: Event): any;
onblur(ev: FocusEvent): void;
oncanplay(ev: Event): void;
oncanplaythrough(ev: Event): void;
onchange(ev: Event): void;
onclick(ev: MouseEvent): void;
oncontextmenu(ev: PointerEvent): void;
oncopy(ev: ClipboardEvent): void;
oncuechange(ev: Event): void;
oncut(ev: ClipboardEvent): void;
ondblclick(ev: MouseEvent): void;
ondeactivate(this: HTMLElement, ev: Event): any;
ondrag(ev: DragEvent): void;
ondragend(ev: DragEvent): void;
ondragenter(ev: DragEvent): void;
ondragleave(ev: DragEvent): void;
ondragover(ev: DragEvent): void;
ondragstart(ev: DragEvent): void;
ondrop(ev: DragEvent): void;
ondurationchange(ev: Event): void;
onemptied(ev: Event): void;
onended(this: HTMLElement, ev: Event): any;
onerror(ev: ErrorEvent): void;
onfocus(ev: FocusEvent): void;
oninput(ev: Event): void;
oninvalid(ev: Event): void;
onkeydown(ev: KeyboardEvent): void;
onkeypress(ev: KeyboardEvent): void;
onkeyup(ev: KeyboardEvent): void;
onload(ev: Event): void;
onloadeddata(ev: Event): void;
onloadedmetadata(ev: Event): void;
onloadstart(ev: Event): void;
onmousedown(ev: MouseEvent): void;
onmouseenter(ev: MouseEvent): void;
onmouseleave(ev: MouseEvent): void;
onmousemove(ev: MouseEvent): void;
onmouseout(ev: MouseEvent): void;
onmouseover(ev: MouseEvent): void;
onmouseup(ev: MouseEvent): void;
onmousewheel(ev: WheelEvent): void;
onmscontentzoom(this: HTMLElement, ev: Event): any;
onmsmanipulationstatechanged(ev: Event): void;
onpaste(ev: ClipboardEvent): void;
onpause(ev: Event): void;
onplay(ev: Event): void;
onplaying(ev: Event): void;
onprogress(ev: ProgressEvent): void;
onratechange(ev: Event): void;
onreset(ev: Event): void;
onscroll(ev: UIEvent): void;
onseeked(ev: Event): void;
onseeking(ev: Event): void;
onselect(ev: UIEvent): void;
onselectstart(ev: Event): void;
onstalled(ev: Event): void;
onsubmit(ev: Event): void;
onsuspend(ev: Event): void;
ontimeupdate(ev: Event): void;
onvolumechange(ev: Event): void;
onwaiting(ev: Event): void;
}
declare class HyperHTMLElement<T = {}> {
static readonly observedAttributes: string[];
constructor();
created(): void;
attributeChangedCallback(name: string, prev: string, curr: string): void;
handleEvent(ev: Event): void;
html: WiredTemplateFunction;
state: T;
get defaultState(): T;
render(): void;
setState(state: Partial<T> | ((this: this, state: T) => Partial<T>)): void;
static bind: typeof bind;
static Component: typeof Component;
static intent: typeof define;
static hyper: typeof hyper;
static wire: typeof wire;
static define(name: string, options?: ElementDefinitionOptions): void;
}
export default HyperHTMLElement;
================================================
FILE: index.js
================================================
var HyperHTMLElement = (function (exports) {
'use strict';
/*! (c) Andrea Giammarchi - ISC */
var self$3 = {};
try { self$3.WeakMap = WeakMap; }
catch (WeakMap) {
// this could be better but 90% of the time
// it's everything developers need as fallback
self$3.WeakMap = (function (id, Object) { var dP = Object.defineProperty;
var hOP = Object.hasOwnProperty;
var proto = WeakMap.prototype;
proto.delete = function (key) {
return this.has(key) && delete key[this._];
};
proto.get = function (key) {
return this.has(key) ? key[this._] : void 0;
};
proto.has = function (key) {
return hOP.call(key, this._);
};
proto.set = function (key, value) {
dP(key, this._, {configurable: true, value: value});
return this;
};
return WeakMap;
function WeakMap(iterable) {
dP(this, '_', {value: '_@ungap/weakmap' + id++});
if (iterable)
iterable.forEach(add, this);
}
function add(pair) {
this.set(pair[0], pair[1]);
}
}(Math.random(), Object));
}
var WeakMap$1 = self$3.WeakMap;
/*! (c) Andrea Giammarchi - ISC */
var self$2 = {};
try { self$2.WeakSet = WeakSet; }
catch (WeakSet) {
(function (id, dP) {
var proto = WeakSet.prototype;
proto.add = function (object) {
if (!this.has(object))
dP(object, this._, {value: true, configurable: true});
return this;
};
proto.has = function (object) {
return this.hasOwnProperty.call(object, this._);
};
proto.delete = function (object) {
return this.has(object) && delete object[this._];
};
self$2.WeakSet = WeakSet;
function WeakSet() { dP(this, '_', {value: '_@ungap/weakmap' + id++});
}
}(Math.random(), Object.defineProperty));
}
var WeakSet$1 = self$2.WeakSet;
const {indexOf: indexOf$1, slice: slice$1} = [];
const append = (get, parent, children, start, end, before) => {
const isSelect = 'selectedIndex' in parent;
let noSelection = isSelect;
while (start < end) {
const child = get(children[start], 1);
parent.insertBefore(child, before);
if (isSelect && noSelection && child.selected) {
noSelection = !noSelection;
let {selectedIndex} = parent;
parent.selectedIndex = selectedIndex < 0 ?
start :
indexOf$1.call(parent.querySelectorAll('option'), child);
}
start++;
}
};
const eqeq = (a, b) => a == b;
const identity = O => O;
const indexOf = (
moreNodes,
moreStart,
moreEnd,
lessNodes,
lessStart,
lessEnd,
compare
) => {
const length = lessEnd - lessStart;
/* istanbul ignore if */
if (length < 1)
return -1;
while ((moreEnd - moreStart) >= length) {
let m = moreStart;
let l = lessStart;
while (
m < moreEnd &&
l < lessEnd &&
compare(moreNodes[m], lessNodes[l])
) {
m++;
l++;
}
if (l === lessEnd)
return moreStart;
moreStart = m + 1;
}
return -1;
};
const isReversed = (
futureNodes,
futureEnd,
currentNodes,
currentStart,
currentEnd,
compare
) => {
while (
currentStart < currentEnd &&
compare(
currentNodes[currentStart],
futureNodes[futureEnd - 1]
)) {
currentStart++;
futureEnd--;
} return futureEnd === 0;
};
const next = (get, list, i, length, before) => i < length ?
get(list[i], 0) :
(0 < i ?
get(list[i - 1], -0).nextSibling :
before);
const remove = (get, children, start, end) => {
while (start < end)
drop(get(children[start++], -1));
};
// - - - - - - - - - - - - - - - - - - -
// diff related constants and utilities
// - - - - - - - - - - - - - - - - - - -
const DELETION = -1;
const INSERTION = 1;
const SKIP = 0;
const SKIP_OND = 50;
const HS = (
futureNodes,
futureStart,
futureEnd,
futureChanges,
currentNodes,
currentStart,
currentEnd,
currentChanges
) => {
let k = 0;
/* istanbul ignore next */
let minLen = futureChanges < currentChanges ? futureChanges : currentChanges;
const link = Array(minLen++);
const tresh = Array(minLen);
tresh[0] = -1;
for (let i = 1; i < minLen; i++)
tresh[i] = currentEnd;
const nodes = currentNodes.slice(currentStart, currentEnd);
for (let i = futureStart; i < futureEnd; i++) {
const index = nodes.indexOf(futureNodes[i]);
if (-1 < index) {
const idxInOld = index + currentStart;
k = findK(tresh, minLen, idxInOld);
/* istanbul ignore else */
if (-1 < k) {
tresh[k] = idxInOld;
link[k] = {
newi: i,
oldi: idxInOld,
prev: link[k - 1]
};
}
}
}
k = --minLen;
--currentEnd;
while (tresh[k] > currentEnd) --k;
minLen = currentChanges + futureChanges - k;
const diff = Array(minLen);
let ptr = link[k];
--futureEnd;
while (ptr) {
const {newi, oldi} = ptr;
while (futureEnd > newi) {
diff[--minLen] = INSERTION;
--futureEnd;
}
while (currentEnd > oldi) {
diff[--minLen] = DELETION;
--currentEnd;
}
diff[--minLen] = SKIP;
--futureEnd;
--currentEnd;
ptr = ptr.prev;
}
while (futureEnd >= futureStart) {
diff[--minLen] = INSERTION;
--futureEnd;
}
while (currentEnd >= currentStart) {
diff[--minLen] = DELETION;
--currentEnd;
}
return diff;
};
// this is pretty much the same petit-dom code without the delete map part
// https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L556-L561
const OND = (
futureNodes,
futureStart,
rows,
currentNodes,
currentStart,
cols,
compare
) => {
const length = rows + cols;
const v = [];
let d, k, r, c, pv, cv, pd;
outer: for (d = 0; d <= length; d++) {
/* istanbul ignore if */
if (d > SKIP_OND)
return null;
pd = d - 1;
/* istanbul ignore next */
pv = d ? v[d - 1] : [0, 0];
cv = v[d] = [];
for (k = -d; k <= d; k += 2) {
if (k === -d || (k !== d && pv[pd + k - 1] < pv[pd + k + 1])) {
c = pv[pd + k + 1];
} else {
c = pv[pd + k - 1] + 1;
}
r = c - k;
while (
c < cols &&
r < rows &&
compare(
currentNodes[currentStart + c],
futureNodes[futureStart + r]
)
) {
c++;
r++;
}
if (c === cols && r === rows) {
break outer;
}
cv[d + k] = c;
}
}
const diff = Array(d / 2 + length / 2);
let diffIdx = diff.length - 1;
for (d = v.length - 1; d >= 0; d--) {
while (
c > 0 &&
r > 0 &&
compare(
currentNodes[currentStart + c - 1],
futureNodes[futureStart + r - 1]
)
) {
// diagonal edge = equality
diff[diffIdx--] = SKIP;
c--;
r--;
}
if (!d)
break;
pd = d - 1;
/* istanbul ignore next */
pv = d ? v[d - 1] : [0, 0];
k = c - r;
if (k === -d || (k !== d && pv[pd + k - 1] < pv[pd + k + 1])) {
// vertical edge = insertion
r--;
diff[diffIdx--] = INSERTION;
} else {
// horizontal edge = deletion
c--;
diff[diffIdx--] = DELETION;
}
}
return diff;
};
const applyDiff = (
diff,
get,
parentNode,
futureNodes,
futureStart,
currentNodes,
currentStart,
currentLength,
before
) => {
const live = [];
const length = diff.length;
let currentIndex = currentStart;
let i = 0;
while (i < length) {
switch (diff[i++]) {
case SKIP:
futureStart++;
currentIndex++;
break;
case INSERTION:
// TODO: bulk appends for sequential nodes
live.push(futureNodes[futureStart]);
append(
get,
parentNode,
futureNodes,
futureStart++,
futureStart,
currentIndex < currentLength ?
get(currentNodes[currentIndex], 0) :
before
);
break;
case DELETION:
currentIndex++;
break;
}
}
i = 0;
while (i < length) {
switch (diff[i++]) {
case SKIP:
currentStart++;
break;
case DELETION:
// TODO: bulk removes for sequential nodes
if (-1 < live.indexOf(currentNodes[currentStart]))
currentStart++;
else
remove(
get,
currentNodes,
currentStart++,
currentStart
);
break;
}
}
};
const findK = (ktr, length, j) => {
let lo = 1;
let hi = length;
while (lo < hi) {
const mid = ((lo + hi) / 2) >>> 0;
if (j < ktr[mid])
hi = mid;
else
lo = mid + 1;
}
return lo;
};
const smartDiff = (
get,
parentNode,
futureNodes,
futureStart,
futureEnd,
futureChanges,
currentNodes,
currentStart,
currentEnd,
currentChanges,
currentLength,
compare,
before
) => {
applyDiff(
OND(
futureNodes,
futureStart,
futureChanges,
currentNodes,
currentStart,
currentChanges,
compare
) ||
HS(
futureNodes,
futureStart,
futureEnd,
futureChanges,
currentNodes,
currentStart,
currentEnd,
currentChanges
),
get,
parentNode,
futureNodes,
futureStart,
currentNodes,
currentStart,
currentLength,
before
);
};
const drop = node => (node.remove || dropChild).call(node);
function dropChild() {
const {parentNode} = this;
/* istanbul ignore else */
if (parentNode)
parentNode.removeChild(this);
}
/*! (c) 2018 Andrea Giammarchi (ISC) */
const domdiff = (
parentNode, // where changes happen
currentNodes, // Array of current items/nodes
futureNodes, // Array of future items/nodes
options // optional object with one of the following properties
// before: domNode
// compare(generic, generic) => true if same generic
// node(generic) => Node
) => {
if (!options)
options = {};
const compare = options.compare || eqeq;
const get = options.node || identity;
const before = options.before == null ? null : get(options.before, 0);
const currentLength = currentNodes.length;
let currentEnd = currentLength;
let currentStart = 0;
let futureEnd = futureNodes.length;
let futureStart = 0;
// common prefix
while (
currentStart < currentEnd &&
futureStart < futureEnd &&
compare(currentNodes[currentStart], futureNodes[futureStart])
) {
currentStart++;
futureStart++;
}
// common suffix
while (
currentStart < currentEnd &&
futureStart < futureEnd &&
compare(currentNodes[currentEnd - 1], futureNodes[futureEnd - 1])
) {
currentEnd--;
futureEnd--;
}
const currentSame = currentStart === currentEnd;
const futureSame = futureStart === futureEnd;
// same list
if (currentSame && futureSame)
return futureNodes;
// only stuff to add
if (currentSame && futureStart < futureEnd) {
append(
get,
parentNode,
futureNodes,
futureStart,
futureEnd,
next(get, currentNodes, currentStart, currentLength, before)
);
return futureNodes;
}
// only stuff to remove
if (futureSame && currentStart < currentEnd) {
remove(
get,
currentNodes,
currentStart,
currentEnd
);
return futureNodes;
}
const currentChanges = currentEnd - currentStart;
const futureChanges = futureEnd - futureStart;
let i = -1;
// 2 simple indels: the shortest sequence is a subsequence of the longest
if (currentChanges < futureChanges) {
i = indexOf(
futureNodes,
futureStart,
futureEnd,
currentNodes,
currentStart,
currentEnd,
compare
);
// inner diff
if (-1 < i) {
append(
get,
parentNode,
futureNodes,
futureStart,
i,
get(currentNodes[currentStart], 0)
);
append(
get,
parentNode,
futureNodes,
i + currentChanges,
futureEnd,
next(get, currentNodes, currentEnd, currentLength, before)
);
return futureNodes;
}
}
/* istanbul ignore else */
else if (futureChanges < currentChanges) {
i = indexOf(
currentNodes,
currentStart,
currentEnd,
futureNodes,
futureStart,
futureEnd,
compare
);
// outer diff
if (-1 < i) {
remove(
get,
currentNodes,
currentStart,
i
);
remove(
get,
currentNodes,
i + futureChanges,
currentEnd
);
return futureNodes;
}
}
// common case with one replacement for many nodes
// or many nodes replaced for a single one
/* istanbul ignore else */
if ((currentChanges < 2 || futureChanges < 2)) {
append(
get,
parentNode,
futureNodes,
futureStart,
futureEnd,
get(currentNodes[currentStart], 0)
);
remove(
get,
currentNodes,
currentStart,
currentEnd
);
return futureNodes;
}
// the half match diff part has been skipped in petit-dom
// https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L391-L397
// accordingly, I think it's safe to skip in here too
// if one day it'll come out like the speediest thing ever to do
// then I might add it in here too
// Extra: before going too fancy, what about reversed lists ?
// This should bail out pretty quickly if that's not the case.
if (
currentChanges === futureChanges &&
isReversed(
futureNodes,
futureEnd,
currentNodes,
currentStart,
currentEnd,
compare
)
) {
append(
get,
parentNode,
futureNodes,
futureStart,
futureEnd,
next(get, currentNodes, currentEnd, currentLength, before)
);
return futureNodes;
}
// last resort through a smart diff
smartDiff(
get,
parentNode,
futureNodes,
futureStart,
futureEnd,
futureChanges,
currentNodes,
currentStart,
currentEnd,
currentChanges,
currentLength,
compare,
before
);
return futureNodes;
};
/*! (c) Andrea Giammarchi - ISC */
var self$1 = {};
self$1.CustomEvent = typeof CustomEvent === 'function' ?
CustomEvent :
(function (__p__) {
CustomEvent[__p__] = new CustomEvent('').constructor[__p__];
return CustomEvent;
function CustomEvent(type, init) {
if (!init) init = {};
var e = document.createEvent('CustomEvent');
e.initCustomEvent(type, !!init.bubbles, !!init.cancelable, init.detail);
return e;
}
}('prototype'));
var CustomEvent$1 = self$1.CustomEvent;
/*! (c) Andrea Giammarchi - ISC */
var self = {};
try { self.Map = Map; }
catch (Map) {
self.Map = function Map() {
var i = 0;
var k = [];
var v = [];
return {
delete: function (key) {
var had = contains(key);
if (had) {
k.splice(i, 1);
v.splice(i, 1);
}
return had;
},
forEach: function forEach(callback, context) {
k.forEach(
function (key, i) {
callback.call(context, v[i], key, this);
},
this
);
},
get: function get(key) {
return contains(key) ? v[i] : void 0;
},
has: function has(key) {
return contains(key);
},
set: function set(key, value) {
v[contains(key) ? i : (k.push(key) - 1)] = value;
return this;
}
};
function contains(v) {
i = k.indexOf(v);
return -1 < i;
}
};
}
var Map$1 = self.Map;
// hyperHTML.Component is a very basic class
// able to create Custom Elements like components
// including the ability to listen to connect/disconnect
// events via onconnect/ondisconnect attributes
// Components can be created imperatively or declaratively.
// The main difference is that declared components
// will not automatically render on setState(...)
// to simplify state handling on render.
function Component() {
return this; // this is needed in Edge !!!
}
// Component is lazily setup because it needs
// wire mechanism as lazy content
function setup(content) {
// there are various weakly referenced variables in here
// and mostly are to use Component.for(...) static method.
const children = new WeakMap$1;
const create = Object.create;
const createEntry = (wm, id, component) => {
wm.set(id, component);
return component;
};
const get = (Class, info, context, id) => {
const relation = info.get(Class) || relate(Class, info);
switch (typeof id) {
case 'object':
case 'function':
const wm = relation.w || (relation.w = new WeakMap$1);
return wm.get(id) || createEntry(wm, id, new Class(context));
default:
const sm = relation.p || (relation.p = create(null));
return sm[id] || (sm[id] = new Class(context));
}
};
const relate = (Class, info) => {
const relation = {w: null, p: null};
info.set(Class, relation);
return relation;
};
const set = context => {
const info = new Map$1;
children.set(context, info);
return info;
};
// The Component Class
Object.defineProperties(
Component,
{
// Component.for(context[, id]) is a convenient way
// to automatically relate data/context to children components
// If not created yet, the new Component(context) is weakly stored
// and after that same instance would always be returned.
for: {
configurable: true,
value(context, id) {
return get(
this,
children.get(context) || set(context),
context,
id == null ?
'default' : id
);
}
}
}
);
Object.defineProperties(
Component.prototype,
{
// all events are handled with the component as context
handleEvent: {value(e) {
const ct = e.currentTarget;
this[
('getAttribute' in ct && ct.getAttribute('data-call')) ||
('on' + e.type)
](e);
}},
// components will lazily define html or svg properties
// as soon as these are invoked within the .render() method
// Such render() method is not provided by the base class
// but it must be available through the Component extend.
// Declared components could implement a
// render(props) method too and use props as needed.
html: lazyGetter('html', content),
svg: lazyGetter('svg', content),
// the state is a very basic/simple mechanism inspired by Preact
state: lazyGetter('state', function () { return this.defaultState; }),
// it is possible to define a default state that'd be always an object otherwise
defaultState: {get() { return {}; }},
// dispatch a bubbling, cancelable, custom event
// through the first known/available node
dispatch: {value(type, detail) {
const {_wire$} = this;
if (_wire$) {
const event = new CustomEvent$1(type, {
bubbles: true,
cancelable: true,
detail
});
event.component = this;
return (_wire$.dispatchEvent ?
_wire$ :
_wire$.firstChild
).dispatchEvent(event);
}
return false;
}},
// setting some property state through a new object
// or a callback, triggers also automatically a render
// unless explicitly specified to not do so (render === false)
setState: {value(state, render) {
const target = this.state;
const source = typeof state === 'function' ? state.call(this, target) : state;
for (const key in source) target[key] = source[key];
if (render !== false)
this.render();
return this;
}}
}
);
}
// instead of a secret key I could've used a WeakMap
// However, attaching a property directly will result
// into better performance with thousands of components
// hanging around, and less memory pressure caused by the WeakMap
const lazyGetter = (type, fn) => {
const secret = '_' + type + '$';
return {
get() {
return this[secret] || setValue(this, secret, fn.call(this, type));
},
set(value) {
setValue(this, secret, value);
}
};
};
// shortcut to set value on get or set(value)
const setValue = (self, secret, value) =>
Object.defineProperty(self, secret, {
configurable: true,
value: typeof value === 'function' ?
function () {
return (self._wire$ = value.apply(this, arguments));
} :
value
})[secret]
;
Object.defineProperties(
Component.prototype,
{
// used to distinguish better than instanceof
ELEMENT_NODE: {value: 1},
nodeType: {value: -1}
}
);
const attributes = {};
const intents = {};
const keys = [];
const hasOwnProperty = intents.hasOwnProperty;
let length = 0;
var Intent = {
// used to invoke right away hyper:attributes
attributes,
// hyperHTML.define('intent', (object, update) => {...})
// can be used to define a third parts update mechanism
// when every other known mechanism failed.
// hyper.define('user', info => info.name);
// hyper(node)`<p>${{user}}</p>`;
define: (intent, callback) => {
if (intent.indexOf('-') < 0) {
if (!(intent in intents)) {
length = keys.push(intent);
}
intents[intent] = callback;
} else {
attributes[intent] = callback;
}
},
// this method is used internally as last resort
// to retrieve a value out of an object
invoke: (object, callback) => {
for (let i = 0; i < length; i++) {
let key = keys[i];
if (hasOwnProperty.call(object, key)) {
return intents[key](object[key], callback);
}
}
}
};
var isArray = Array.isArray || /* istanbul ignore next */ (function (toString) {
/* istanbul ignore next */
var $ = toString.call([]);
/* istanbul ignore next */
return function isArray(object) {
return toString.call(object) === $;
};
}({}.toString));
/*! (c) Andrea Giammarchi - ISC */
var createContent = (function (document) { var FRAGMENT = 'fragment';
var TEMPLATE = 'template';
var HAS_CONTENT = 'content' in create(TEMPLATE);
var createHTML = HAS_CONTENT ?
function (html) {
var template = create(TEMPLATE);
template.innerHTML = html;
return template.content;
} :
function (html) {
var content = create(FRAGMENT);
var template = create(TEMPLATE);
var childNodes = null;
if (/^[^\S]*?<(col(?:group)?|t(?:head|body|foot|r|d|h))/i.test(html)) {
var selector = RegExp.$1;
template.innerHTML = '<table>' + html + '</table>';
childNodes = template.querySelectorAll(selector);
} else {
template.innerHTML = html;
childNodes = template.childNodes;
}
append(content, childNodes);
return content;
};
return function createContent(markup, type) {
return (type === 'svg' ? createSVG : createHTML)(markup);
};
function append(root, childNodes) {
var length = childNodes.length;
while (length--)
root.appendChild(childNodes[0]);
}
function create(element) {
return element === FRAGMENT ?
document.createDocumentFragment() :
document.createElementNS('http://www.w3.org/1999/xhtml', element);
}
// it could use createElementNS when hasNode is there
// but this fallback is equally fast and easier to maintain
// it is also battle tested already in all IE
function createSVG(svg) {
var content = create(FRAGMENT);
var template = create('div');
template.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg">' + svg + '</svg>';
append(content, template.firstChild.childNodes);
return content;
}
}(document));
/*! (c) Andrea Giammarchi */
function disconnected(poly) { var Event = poly.Event;
var WeakSet = poly.WeakSet;
var notObserving = true;
var observer = null;
return function observe(node) {
if (notObserving) {
notObserving = !notObserving;
observer = new WeakSet;
startObserving(node.ownerDocument);
}
observer.add(node);
return node;
};
function startObserving(document) {
var connected = new WeakSet;
var disconnected = new WeakSet;
try {
(new MutationObserver(changes)).observe(
document,
{subtree: true, childList: true}
);
}
catch(o_O) {
var timer = 0;
var records = [];
var reschedule = function (record) {
records.push(record);
clearTimeout(timer);
timer = setTimeout(
function () {
changes(records.splice(timer = 0, records.length));
},
0
);
};
document.addEventListener(
'DOMNodeRemoved',
function (event) {
reschedule({addedNodes: [], removedNodes: [event.target]});
},
true
);
document.addEventListener(
'DOMNodeInserted',
function (event) {
reschedule({addedNodes: [event.target], removedNodes: []});
},
true
);
}
function changes(records) {
for (var
record,
length = records.length,
i = 0; i < length; i++
) {
record = records[i];
dispatchAll(record.removedNodes, 'disconnected', disconnected, connected);
dispatchAll(record.addedNodes, 'connected', connected, disconnected);
}
}
function dispatchAll(nodes, type, wsin, wsout) {
for (var
node,
event = new Event(type),
length = nodes.length,
i = 0; i < length;
(node = nodes[i++]).nodeType === 1 &&
dispatchTarget(node, event, type, wsin, wsout)
);
}
function dispatchTarget(node, event, type, wsin, wsout) {
if (observer.has(node) && !wsin.has(node)) {
wsout.delete(node);
wsin.add(node);
node.dispatchEvent(event);
/*
// The event is not bubbling (perf reason: should it?),
// hence there's no way to know if
// stop/Immediate/Propagation() was called.
// Should DOM Level 0 work at all?
// I say it's a YAGNI case for the time being,
// and easy to implement in user-land.
if (!event.cancelBubble) {
var fn = node['on' + type];
if (fn)
fn.call(node, event);
}
*/
}
for (var
// apparently is node.children || IE11 ... ^_^;;
// https://github.com/WebReflection/disconnected/issues/1
children = node.children || [],
length = children.length,
i = 0; i < length;
dispatchTarget(children[i++], event, type, wsin, wsout)
);
}
}
}
/*! (c) Andrea Giammarchi - ISC */
var importNode = (function (
document,
appendChild,
cloneNode,
createTextNode,
importNode
) {
var native = importNode in document;
// IE 11 has problems with cloning templates:
// it "forgets" empty childNodes. This feature-detects that.
var fragment = document.createDocumentFragment();
fragment[appendChild](document[createTextNode]('g'));
fragment[appendChild](document[createTextNode](''));
/* istanbul ignore next */
var content = native ?
document[importNode](fragment, true) :
fragment[cloneNode](true);
return content.childNodes.length < 2 ?
function importNode(node, deep) {
var clone = node[cloneNode]();
for (var
/* istanbul ignore next */
childNodes = node.childNodes || [],
length = childNodes.length,
i = 0; deep && i < length; i++
) {
clone[appendChild](importNode(childNodes[i], deep));
}
return clone;
} :
/* istanbul ignore next */
(native ?
document[importNode] :
function (node, deep) {
return node[cloneNode](!!deep);
}
);
}(
document,
'appendChild',
'cloneNode',
'createTextNode',
'importNode'
));
var trim = ''.trim || /* istanbul ignore next */ function () {
return String(this).replace(/^\s+|\s+/g, '');
};
/*! (c) Andrea Giammarchi - ISC */
// Custom
var UID = '-' + Math.random().toFixed(6) + '%';
// Edge issue!
var UID_IE = false;
try {
if (!(function (template, content, tabindex) {
return content in template && (
(template.innerHTML = '<p ' + tabindex + '="' + UID + '"></p>'),
template[content].childNodes[0].getAttribute(tabindex) == UID
);
}(document.createElement('template'), 'content', 'tabindex'))) {
UID = '_dt: ' + UID.slice(1, -1) + ';';
UID_IE = true;
}
} catch(meh) {}
var UIDC = '<!--' + UID + '-->';
// DOM
var COMMENT_NODE = 8;
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var SHOULD_USE_TEXT_CONTENT = /^(?:plaintext|script|style|textarea|title|xmp)$/i;
var VOID_ELEMENTS = /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
/*! (c) Andrea Giammarchi - ISC */
function sanitize (template) {
return template.join(UIDC)
.replace(selfClosing, fullClosing)
.replace(attrSeeker, attrReplacer);
}
var spaces = ' \\f\\n\\r\\t';
var almostEverything = '[^' + spaces + '\\/>"\'=]+';
var attrName = '[' + spaces + ']+' + almostEverything;
var tagName = '<([A-Za-z]+[A-Za-z0-9:._-]*)((?:';
var attrPartials = '(?:\\s*=\\s*(?:\'[^\']*?\'|"[^"]*?"|<[^>]*?>|' + almostEverything.replace('\\/', '') + '))?)';
var attrSeeker = new RegExp(tagName + attrName + attrPartials + '+)([' + spaces + ']*/?>)', 'g');
var selfClosing = new RegExp(tagName + attrName + attrPartials + '*)([' + spaces + ']*/>)', 'g');
var findAttributes = new RegExp('(' + attrName + '\\s*=\\s*)([\'"]?)' + UIDC + '\\2', 'gi');
function attrReplacer($0, $1, $2, $3) {
return '<' + $1 + $2.replace(findAttributes, replaceAttributes) + $3;
}
function replaceAttributes($0, $1, $2) {
return $1 + ($2 || '"') + UID + ($2 || '"');
}
function fullClosing($0, $1, $2) {
return VOID_ELEMENTS.test($1) ? $0 : ('<' + $1 + $2 + '></' + $1 + '>');
}
var umap = _ => ({
// About: get: _.get.bind(_)
// It looks like WebKit/Safari didn't optimize bind at all,
// so that using bind slows it down by 60%.
// Firefox and Chrome are just fine in both cases,
// so let's use the approach that works fast everywhere 👍
get: key => _.get(key),
set: (key, value) => (_.set(key, value), value)
});
/* istanbul ignore next */
var normalizeAttributes = UID_IE ?
function (attributes, parts) {
var html = parts.join(' ');
return parts.slice.call(attributes, 0).sort(function (left, right) {
return html.indexOf(left.name) <= html.indexOf(right.name) ? -1 : 1;
});
} :
function (attributes, parts) {
return parts.slice.call(attributes, 0);
}
;
function find(node, path) {
var length = path.length;
var i = 0;
while (i < length)
node = node.childNodes[path[i++]];
return node;
}
function parse(node, holes, parts, path) {
var childNodes = node.childNodes;
var length = childNodes.length;
var i = 0;
while (i < length) {
var child = childNodes[i];
switch (child.nodeType) {
case ELEMENT_NODE:
var childPath = path.concat(i);
parseAttributes(child, holes, parts, childPath);
parse(child, holes, parts, childPath);
break;
case COMMENT_NODE:
var textContent = child.textContent;
if (textContent === UID) {
parts.shift();
holes.push(
// basicHTML or other non standard engines
// might end up having comments in nodes
// where they shouldn't, hence this check.
SHOULD_USE_TEXT_CONTENT.test(node.nodeName) ?
Text(node, path) :
Any(child, path.concat(i))
);
} else {
switch (textContent.slice(0, 2)) {
case '/*':
if (textContent.slice(-2) !== '*/')
break;
case '\uD83D\uDC7B': // ghost
node.removeChild(child);
i--;
length--;
}
}
break;
case TEXT_NODE:
// the following ignore is actually covered by browsers
// only basicHTML ends up on previous COMMENT_NODE case
// instead of TEXT_NODE because it knows nothing about
// special style or textarea behavior
/* istanbul ignore if */
if (
SHOULD_USE_TEXT_CONTENT.test(node.nodeName) &&
trim.call(child.textContent) === UIDC
) {
parts.shift();
holes.push(Text(node, path));
}
break;
}
i++;
}
}
function parseAttributes(node, holes, parts, path) {
var attributes = node.attributes;
var cache = [];
var remove = [];
var array = normalizeAttributes(attributes, parts);
var length = array.length;
var i = 0;
while (i < length) {
var attribute = array[i++];
var direct = attribute.value === UID;
var sparse;
if (direct || 1 < (sparse = attribute.value.split(UIDC)).length) {
var name = attribute.name;
// the following ignore is covered by IE
// and the IE9 double viewBox test
/* istanbul ignore else */
if (cache.indexOf(name) < 0) {
cache.push(name);
var realName = parts.shift().replace(
direct ?
/^(?:|[\S\s]*?\s)(\S+?)\s*=\s*('|")?$/ :
new RegExp(
'^(?:|[\\S\\s]*?\\s)(' + name + ')\\s*=\\s*(\'|")[\\S\\s]*',
'i'
),
'$1'
);
var value = attributes[realName] ||
// the following ignore is covered by browsers
// while basicHTML is already case-sensitive
/* istanbul ignore next */
attributes[realName.toLowerCase()];
if (direct)
holes.push(Attr(value, path, realName, null));
else {
var skip = sparse.length - 2;
while (skip--)
parts.shift();
holes.push(Attr(value, path, realName, sparse));
}
}
remove.push(attribute);
}
}
length = remove.length;
i = 0;
/* istanbul ignore next */
var cleanValue = 0 < length && UID_IE && !('ownerSVGElement' in node);
while (i < length) {
// Edge HTML bug #16878726
var attr = remove[i++];
// IE/Edge bug lighterhtml#63 - clean the value or it'll persist
/* istanbul ignore next */
if (cleanValue)
attr.value = '';
// IE/Edge bug lighterhtml#64 - don't use removeAttributeNode
node.removeAttribute(attr.name);
}
// This is a very specific Firefox/Safari issue
// but since it should be a not so common pattern,
// it's probably worth patching regardless.
// Basically, scripts created through strings are death.
// You need to create fresh new scripts instead.
// TODO: is there any other node that needs such nonsense?
var nodeName = node.nodeName;
if (/^script$/i.test(nodeName)) {
// this used to be like that
// var script = createElement(node, nodeName);
// then Edge arrived and decided that scripts created
// through template documents aren't worth executing
// so it became this ... hopefully it won't hurt in the wild
var script = document.createElement(nodeName);
length = attributes.length;
i = 0;
while (i < length)
script.setAttributeNode(attributes[i++].cloneNode(true));
script.textContent = node.textContent;
node.parentNode.replaceChild(script, node);
}
}
function Any(node, path) {
return {
type: 'any',
node: node,
path: path
};
}
function Attr(node, path, name, sparse) {
return {
type: 'attr',
node: node,
path: path,
name: name,
sparse: sparse
};
}
function Text(node, path) {
return {
type: 'text',
node: node,
path: path
};
}
// globals
var parsed = umap(new WeakMap$1);
function createInfo(options, template) {
var markup = (options.convert || sanitize)(template);
var transform = options.transform;
if (transform)
markup = transform(markup);
var content = createContent(markup, options.type);
cleanContent(content);
var holes = [];
parse(content, holes, template.slice(0), []);
return {
content: content,
updates: function (content) {
var updates = [];
var len = holes.length;
var i = 0;
var off = 0;
while (i < len) {
var info = holes[i++];
var node = find(content, info.path);
switch (info.type) {
case 'any':
updates.push({fn: options.any(node, []), sparse: false});
break;
case 'attr':
var sparse = info.sparse;
var fn = options.attribute(node, info.name, info.node);
if (sparse === null)
updates.push({fn: fn, sparse: false});
else {
off += sparse.length - 2;
updates.push({fn: fn, sparse: true, values: sparse});
}
break;
case 'text':
updates.push({fn: options.text(node), sparse: false});
node.textContent = '';
break;
}
}
len += off;
return function () {
var length = arguments.length;
if (len !== (length - 1)) {
throw new Error(
(length - 1) + ' values instead of ' + len + '\n' +
template.join('${value}')
);
}
var i = 1;
var off = 1;
while (i < length) {
var update = updates[i - off];
if (update.sparse) {
var values = update.values;
var value = values[0];
var j = 1;
var l = values.length;
off += l - 2;
while (j < l)
value += arguments[i++] + values[j++];
update.fn(value);
}
else
update.fn(arguments[i++]);
}
return content;
};
}
};
}
function createDetails(options, template) {
var info = parsed.get(template) || parsed.set(template, createInfo(options, template));
return info.updates(importNode.call(document, info.content, true));
}
var empty = [];
function domtagger(options) {
var previous = empty;
var updates = cleanContent;
return function (template) {
if (previous !== template)
updates = createDetails(options, (previous = template));
return updates.apply(null, arguments);
};
}
function cleanContent(fragment) {
var childNodes = fragment.childNodes;
var i = childNodes.length;
while (i--) {
var child = childNodes[i];
if (
child.nodeType !== 1 &&
trim.call(child.textContent).length === 0
) {
fragment.removeChild(child);
}
}
}
/*! (c) Andrea Giammarchi - ISC */
var hyperStyle = (function (){ // from https://github.com/developit/preact/blob/33fc697ac11762a1cb6e71e9847670d047af7ce5/src/varants.js
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
var hyphen = /([^A-Z])([A-Z]+)/g;
return function hyperStyle(node, original) {
return 'ownerSVGElement' in node ? svg(node, original) : update(node.style, false);
};
function ized($0, $1, $2) {
return $1 + '-' + $2.toLowerCase();
}
function svg(node, original) {
var style;
if (original)
style = original.cloneNode(true);
else {
node.setAttribute('style', '--hyper:style;');
style = node.getAttributeNode('style');
}
style.value = '';
node.setAttributeNode(style);
return update(style, true);
}
function toStyle(object) {
var key, css = [];
for (key in object)
css.push(key.replace(hyphen, ized), ':', object[key], ';');
return css.join('');
}
function update(style, isSVG) {
var oldType, oldValue;
return function (newValue) {
var info, key, styleValue, value;
switch (typeof newValue) {
case 'object':
if (newValue) {
if (oldType === 'object') {
if (!isSVG) {
if (oldValue !== newValue) {
for (key in oldValue) {
if (!(key in newValue)) {
style[key] = '';
}
}
}
}
} else {
if (isSVG)
style.value = '';
else
style.cssText = '';
}
info = isSVG ? {} : style;
for (key in newValue) {
value = newValue[key];
styleValue = typeof value === 'number' &&
!IS_NON_DIMENSIONAL.test(key) ?
(value + 'px') : value;
if (!isSVG && /^--/.test(key))
info.setProperty(key, styleValue);
else
info[key] = styleValue;
}
oldType = 'object';
if (isSVG)
style.value = toStyle((oldValue = info));
else
oldValue = newValue;
break;
}
default:
if (oldValue != newValue) {
oldType = 'string';
oldValue = newValue;
if (isSVG)
style.value = newValue || '';
else
style.cssText = newValue || '';
}
break;
}
};
}
}());
/*! (c) Andrea Giammarchi - ISC */
var Wire = (function (slice, proto) {
proto = Wire.prototype;
proto.ELEMENT_NODE = 1;
proto.nodeType = 111;
proto.remove = function (keepFirst) {
var childNodes = this.childNodes;
var first = this.firstChild;
var last = this.lastChild;
this._ = null;
if (keepFirst && childNodes.length === 2) {
last.parentNode.removeChild(last);
} else {
var range = this.ownerDocument.createRange();
range.setStartBefore(keepFirst ? childNodes[1] : first);
range.setEndAfter(last);
range.deleteContents();
}
return first;
};
proto.valueOf = function (forceAppend) {
var fragment = this._;
var noFragment = fragment == null;
if (noFragment)
fragment = (this._ = this.ownerDocument.createDocumentFragment());
if (noFragment || forceAppend) {
for (var n = this.childNodes, i = 0, l = n.length; i < l; i++)
fragment.appendChild(n[i]);
}
return fragment;
};
return Wire;
function Wire(childNodes) {
var nodes = (this.childNodes = slice.call(childNodes, 0));
this.firstChild = nodes[0];
this.lastChild = nodes[nodes.length - 1];
this.ownerDocument = nodes[0].ownerDocument;
this._ = null;
}
}([].slice));
// Node.CONSTANTS
const DOCUMENT_FRAGMENT_NODE = 11;
// SVG related constants
const OWNER_SVG_ELEMENT = 'ownerSVGElement';
// Custom Elements / MutationObserver constants
const CONNECTED = 'connected';
const DISCONNECTED = 'dis' + CONNECTED;
const componentType = Component.prototype.nodeType;
const wireType = Wire.prototype.nodeType;
const observe = disconnected({Event: CustomEvent$1, WeakSet: WeakSet$1});
// returns an intent to explicitly inject content as html
const asHTML = html => ({html});
// returns nodes from wires and components
const asNode = (item, i) => {
switch (item.nodeType) {
case wireType:
// in the Wire case, the content can be
// removed, post-pended, inserted, or pre-pended and
// all these cases are handled by domdiff already
/* istanbul ignore next */
return (1 / i) < 0 ?
(i ? item.remove(true) : item.lastChild) :
(i ? item.valueOf(true) : item.firstChild);
case componentType:
return asNode(item.render(), i);
default:
return item;
}
};
// returns true if domdiff can handle the value
const canDiff = value => 'ELEMENT_NODE' in value;
// borrowed from uhandlers
// https://github.com/WebReflection/uhandlers
const booleanSetter = (node, key, oldValue) => newValue => {
if (oldValue !== !!newValue) {
if ((oldValue = !!newValue))
node.setAttribute(key, '');
else
node.removeAttribute(key);
}
};
const hyperSetter = (node, name, svg) => svg ?
value => {
try {
node[name] = value;
}
catch (nope) {
node.setAttribute(name, value);
}
} :
value => {
node[name] = value;
};
// when a Promise is used as interpolation value
// its result must be parsed once resolved.
// This callback is in charge of understanding what to do
// with a returned value once the promise is resolved.
const invokeAtDistance = (value, callback) => {
callback(value.placeholder);
if ('text' in value) {
Promise.resolve(value.text).then(String).then(callback);
} else if ('any' in value) {
Promise.resolve(value.any).then(callback);
} else if ('html' in value) {
Promise.resolve(value.html).then(asHTML).then(callback);
} else {
Promise.resolve(Intent.invoke(value, callback)).then(callback);
}
};
// quick and dirty way to check for Promise/ish values
const isPromise_ish = value => value != null && 'then' in value;
// list of attributes that should not be directly assigned
const readOnly = /^(?:form|list)$/i;
// reused every slice time
const slice = [].slice;
// simplifies text node creation
const text = (node, text) => node.ownerDocument.createTextNode(text);
function Tagger(type) {
this.type = type;
return domtagger(this);
}
Tagger.prototype = {
// there are four kind of attributes, and related behavior:
// * events, with a name starting with `on`, to add/remove event listeners
// * special, with a name present in their inherited prototype, accessed directly
// * regular, accessed through get/setAttribute standard DOM methods
// * style, the only regular attribute that also accepts an object as value
// so that you can style=${{width: 120}}. In this case, the behavior has been
// fully inspired by Preact library and its simplicity.
attribute(node, name, original) {
const isSVG = OWNER_SVG_ELEMENT in node;
let oldValue;
// if the attribute is the style one
// handle it differently from others
if (name === 'style')
return hyperStyle(node, original, isSVG);
// direct accessors for <input .value=${...}> and friends
else if (name.slice(0, 1) === '.')
return hyperSetter(node, name.slice(1), isSVG);
// boolean accessors for <input .value=${...}> and friends
else if (name.slice(0, 1) === '?')
return booleanSetter(node, name.slice(1));
// the name is an event one,
// add/remove event listeners accordingly
else if (/^on/.test(name)) {
let type = name.slice(2);
if (type === CONNECTED || type === DISCONNECTED) {
observe(node);
}
else if (name.toLowerCase()
in node) {
type = type.toLowerCase();
}
return newValue => {
if (oldValue !== newValue) {
if (oldValue)
node.removeEventListener(type, oldValue, false);
oldValue = newValue;
if (newValue)
node.addEventListener(type, newValue, false);
}
};
}
// the attribute is special ('value' in input)
// and it's not SVG *or* the name is exactly data,
// in this case assign the value directly
else if (
name === 'data' ||
(!isSVG && name in node && !readOnly.test(name))
) {
return newValue => {
if (oldValue !== newValue) {
oldValue = newValue;
if (node[name] !== newValue && newValue == null) {
// cleanup on null to avoid silly IE/Edge bug
node[name] = '';
node.removeAttribute(name);
}
else
node[name] = newValue;
}
};
}
else if (name in Intent.attributes) {
return any => {
const newValue = Intent.attributes[name](node, any);
if (oldValue !== newValue) {
oldValue = newValue;
if (newValue == null)
node.removeAttribute(name);
else
node.setAttribute(name, newValue);
}
};
}
// in every other case, use the attribute node as it is
// update only the value, set it as node only when/if needed
else {
let owner = false;
const attribute = original.cloneNode(true);
return newValue => {
if (oldValue !== newValue) {
oldValue = newValue;
if (attribute.value !== newValue) {
if (newValue == null) {
if (owner) {
owner = false;
node.removeAttributeNode(attribute);
}
attribute.value = newValue;
} else {
attribute.value = newValue;
if (!owner) {
owner = true;
node.setAttributeNode(attribute);
}
}
}
}
};
}
},
// in a hyper(node)`<div>${content}</div>` case
// everything could happen:
// * it's a JS primitive, stored as text
// * it's null or undefined, the node should be cleaned
// * it's a component, update the content by rendering it
// * it's a promise, update the content once resolved
// * it's an explicit intent, perform the desired operation
// * it's an Array, resolve all values if Promises and/or
// update the node with the resulting list of content
any(node, childNodes) {
const diffOptions = {node: asNode, before: node};
const nodeType = OWNER_SVG_ELEMENT in node ? /* istanbul ignore next */ 'svg' : 'html';
let fastPath = false;
let oldValue;
const anyContent = value => {
switch (typeof value) {
case 'string':
case 'number':
case 'boolean':
if (fastPath) {
if (oldValue !== value) {
oldValue = value;
childNodes[0].textContent = value;
}
} else {
fastPath = true;
oldValue = value;
childNodes = domdiff(
node.parentNode,
childNodes,
[text(node, value)],
diffOptions
);
}
break;
case 'function':
anyContent(value(node));
break;
case 'object':
case 'undefined':
if (value == null) {
fastPath = false;
childNodes = domdiff(
node.parentNode,
childNodes,
[],
diffOptions
);
break;
}
default:
fastPath = false;
oldValue = value;
if (isArray(value)) {
if (value.length === 0) {
if (childNodes.length) {
childNodes = domdiff(
node.parentNode,
childNodes,
[],
diffOptions
);
}
} else {
switch (typeof value[0]) {
case 'string':
case 'number':
case 'boolean':
anyContent({html: value});
break;
case 'object':
if (isArray(value[0])) {
value = value.concat.apply([], value);
}
if (isPromise_ish(value[0])) {
Promise.all(value).then(anyContent);
break;
}
default:
childNodes = domdiff(
node.parentNode,
childNodes,
value,
diffOptions
);
break;
}
}
} else if (canDiff(value)) {
childNodes = domdiff(
node.parentNode,
childNodes,
value.nodeType === DOCUMENT_FRAGMENT_NODE ?
slice.call(value.childNodes) :
[value],
diffOptions
);
} else if (isPromise_ish(value)) {
value.then(anyContent);
} else if ('placeholder' in value) {
invokeAtDistance(value, anyContent);
} else if ('text' in value) {
anyContent(String(value.text));
} else if ('any' in value) {
anyContent(value.any);
} else if ('html' in value) {
childNodes = domdiff(
node.parentNode,
childNodes,
slice.call(
createContent(
[].concat(value.html).join(''),
nodeType
).childNodes
),
diffOptions
);
} else if ('length' in value) {
anyContent(slice.call(value));
} else {
anyContent(Intent.invoke(value, anyContent));
}
break;
}
};
return anyContent;
},
// style or textareas don't accept HTML as content
// it's pointless to transform or analyze anything
// different from text there but it's worth checking
// for possible defined intents.
text(node) {
let oldValue;
const textContent = value => {
if (oldValue !== value) {
oldValue = value;
const type = typeof value;
if (type === 'object' && value) {
if (isPromise_ish(value)) {
value.then(textContent);
} else if ('placeholder' in value) {
invokeAtDistance(value, textContent);
} else if ('text' in value) {
textContent(String(value.text));
} else if ('any' in value) {
textContent(value.any);
} else if ('html' in value) {
textContent([].concat(value.html).join(''));
} else if ('length' in value) {
textContent(slice.call(value).join(''));
} else {
textContent(Intent.invoke(value, textContent));
}
} else if (type === 'function') {
textContent(value(node));
} else {
node.textContent = value == null ? '' : value;
}
}
};
return textContent;
}
};
var isNoOp = typeof document !== 'object';
var templateLiteral = function (tl) {
var RAW = 'raw';
var isBroken = function (UA) {
return /(Firefox|Safari)\/(\d+)/.test(UA) &&
!/(Chrom[eium]+|Android)\/(\d+)/.test(UA);
};
var broken = isBroken((document.defaultView.navigator || {}).userAgent);
var FTS = !(RAW in tl) ||
tl.propertyIsEnumerable(RAW) ||
!Object.isFrozen(tl[RAW]);
if (broken || FTS) {
var forever = {};
var foreverCache = function (tl) {
for (var key = '.', i = 0; i < tl.length; i++)
key += tl[i].length + '.' + tl[i];
return forever[key] || (forever[key] = tl);
};
// Fallback TypeScript shenanigans
if (FTS)
templateLiteral = foreverCache;
// try fast path for other browsers:
// store the template as WeakMap key
// and forever cache it only when it's not there.
// this way performance is still optimal,
// penalized only when there are GC issues
else {
var wm = new WeakMap$1;
var set = function (tl, unique) {
wm.set(tl, unique);
return unique;
};
templateLiteral = function (tl) {
return wm.get(tl) || set(tl, foreverCache(tl));
};
}
} else {
isNoOp = true;
}
return TL(tl);
};
function TL(tl) {
return isNoOp ? tl : templateLiteral(tl);
}
function tta (template) {
var length = arguments.length;
var args = [TL(template)];
var i = 1;
while (i < length)
args.push(arguments[i++]);
return args;
}
/**
* best benchmark goes here
* https://jsperf.com/tta-bench
* I should probably have an @ungap/template-literal-es too
export default (...args) => {
args[0] = unique(args[0]);
return args;
};
*/
// all wires used per each context
const wires = new WeakMap$1;
// A wire is a callback used as tag function
// to lazily relate a generic object to a template literal.
// hyper.wire(user)`<div id=user>${user.name}</div>`; => the div#user
// This provides the ability to have a unique DOM structure
// related to a unique JS object through a reusable template literal.
// A wire can specify a type, as svg or html, and also an id
// via html:id or :id convention. Such :id allows same JS objects
// to be associated to different DOM structures accordingly with
// the used template literal without losing previously rendered parts.
const wire = (obj, type) => obj == null ?
content(type || 'html') :
weakly(obj, type || 'html');
// A wire content is a virtual reference to one or more nodes.
// It's represented by either a DOM node, or an Array.
// In both cases, the wire content role is to simply update
// all nodes through the list of related callbacks.
// In few words, a wire content is like an invisible parent node
// in charge of updating its content like a bound element would do.
const content = type => {
let wire, tagger, template;
return function () {
const args = tta.apply(null, arguments);
if (template !== args[0]) {
template = args[0];
tagger = new Tagger(type);
wire = wireContent(tagger.apply(tagger, args));
} else {
tagger.apply(tagger, args);
}
return wire;
};
};
// wires are weakly created through objects.
// Each object can have multiple wires associated
// and this is thanks to the type + :id feature.
const weakly = (obj, type) => {
const i = type.indexOf(':');
let wire = wires.get(obj);
let id = type;
if (-1 < i) {
id = type.slice(i + 1);
type = type.slice(0, i) || 'html';
}
if (!wire)
wires.set(obj, wire = {});
return wire[id] || (wire[id] = content(type));
};
// A document fragment loses its nodes
// as soon as it is appended into another node.
// This has the undesired effect of losing wired content
// on a second render call, because (by then) the fragment would be empty:
// no longer providing access to those sub-nodes that ultimately need to
// stay associated with the original interpolation.
// To prevent hyperHTML from forgetting about a fragment's sub-nodes,
// fragments are instead returned as an Array of nodes or, if there's only one entry,
// as a single referenced node which, unlike fragments, will indeed persist
// wire content throughout multiple renderings.
// The initial fragment, at this point, would be used as unique reference to this
// array of nodes or to this single referenced node.
const wireContent = node => {
const childNodes = node.childNodes;
const {length} = childNodes;
return length === 1 ?
childNodes[0] :
(length ? new Wire(childNodes) : node);
};
// a weak collection of contexts that
// are already known to hyperHTML
const bewitched = new WeakMap$1;
// better known as hyper.bind(node), the render is
// the main tag function in charge of fully upgrading
// or simply updating, contexts used as hyperHTML targets.
// The `this` context is either a regular DOM node or a fragment.
function render() {
const wicked = bewitched.get(this);
const args = tta.apply(null, arguments);
if (wicked && wicked.template === args[0]) {
wicked.tagger.apply(null, args);
} else {
upgrade.apply(this, args);
}
return this;
}
// an upgrade is in charge of collecting template info,
// parse it once, if unknown, to map all interpolations
// as single DOM callbacks, relate such template
// to the current context, and render it after cleaning the context up
function upgrade(template) {
const type = OWNER_SVG_ELEMENT in this ? 'svg' : 'html';
const tagger = new Tagger(type);
bewitched.set(this, {tagger, template: template});
this.textContent = '';
this.appendChild(tagger.apply(null, arguments));
}
/*! (c) Andrea Giammarchi (ISC) */
// all functions are self bound to the right context
// you can do the following
// const {bind, wire} = hyperHTML;
// and use them right away: bind(node)`hello!`;
const bind = context => render.bind(context);
const define = Intent.define;
const tagger = Tagger.prototype;
hyper.Component = Component;
hyper.bind = bind;
hyper.define = define;
hyper.diff = domdiff;
hyper.hyper = hyper;
hyper.observe = observe;
hyper.tagger = tagger;
hyper.wire = wire;
// exported as shared utils
// for projects based on hyperHTML
// that don't necessarily need upfront polyfills
// i.e. those still targeting IE
hyper._ = {
WeakMap: WeakMap$1,
WeakSet: WeakSet$1
};
// the wire content is the lazy defined
// html or svg property of each hyper.Component
setup(content);
// by default, hyperHTML is a smart function
// that "magically" understands what's the best
// thing to do with passed arguments
function hyper(HTML) {
return arguments.length < 2 ?
(HTML == null ?
content('html') :
(typeof HTML === 'string' ?
hyper.wire(null, HTML) :
('raw' in HTML ?
content('html')(HTML) :
('nodeType' in HTML ?
hyper.bind(HTML) :
weakly(HTML, 'html')
)
)
)) :
('raw' in HTML ?
content('html') : hyper.wire
).apply(null, arguments);
}
/*! (C) 2017-2018 Andrea Giammarchi - ISC Style License */
// utils to deal with custom elements builtin extends
const ATTRIBUTE_CHANGED_CALLBACK = 'attributeChangedCallback';
const O = Object;
const classes = [];
const defineProperty = O.defineProperty;
const getOwnPropertyDescriptor = O.getOwnPropertyDescriptor;
const getOwnPropertyNames = O.getOwnPropertyNames;
/* istanbul ignore next */
const getOwnPropertySymbols = O.getOwnPropertySymbols || (() => []);
/* istanbul ignore next */
const getPrototypeOf = O.getPrototypeOf || (o => o.__proto__);
/* istanbul ignore next */
const ownKeys = typeof Reflect === 'object' && Reflect.ownKeys ||
(o => getOwnPropertyNames(o).concat(getOwnPropertySymbols(o)));
/* istanbul ignore next */
const setPrototypeOf = O.setPrototypeOf ||
((o, p) => (o.__proto__ = p, o));
/* istanbul ignore stop */
const camel = name => name.replace(/-([a-z])/g, ($0, $1) => $1.toUpperCase());
const {attachShadow} = HTMLElement.prototype;
const sr = new WeakMap;
class HyperHTMLElement extends HTMLElement {
// define a custom-element in the CustomElementsRegistry
// class MyEl extends HyperHTMLElement {}
// MyEl.define('my-el');
static define(name, options) {
const Class = this;
const proto = Class.prototype;
const onChanged = proto[ATTRIBUTE_CHANGED_CALLBACK];
const hasChange = !!onChanged;
// Class.booleanAttributes
// -----------------------------------------------
// attributes defined as boolean will have
// an either available or not available attribute
// regardless of the value.
// All falsy values, or "false", mean attribute removed
// while truthy values will be set as is.
// Boolean attributes are also automatically observed.
const booleanAttributes = Class.booleanAttributes || [];
booleanAttributes.forEach(attribute => {
const name = camel(attribute);
if (!(name in proto)) defineProperty(
proto,
name,
{
configurable: true,
get() {
return this.hasAttribute(attribute);
},
set(value) {
if (!value || value === 'false')
this.removeAttribute(attribute);
else
this.setAttribute(attribute, '');
}
}
);
});
// Class.observedAttributes
// -------------------------------------------------------
// HyperHTMLElement will directly reflect get/setAttribute
// operation once these attributes are used, example:
// el.observed = 123;
// will automatically do
// el.setAttribute('observed', 123);
// triggering also the attributeChangedCallback
const observedAttributes = (Class.observedAttributes || []).filter(
attribute => booleanAttributes.indexOf(attribute) < 0
);
observedAttributes.forEach(attribute => {
// it is possible to redefine the behavior at any time
// simply overwriting get prop() and set prop(value)
const name = camel(attribute);
if (!(name in proto)) defineProperty(
proto,
name,
{
configurable: true,
get() {
return this.getAttribute(attribute);
},
set(value) {
if (value == null)
this.removeAttribute(attribute);
else
this.setAttribute(attribute, value);
}
}
);
});
// if these are defined, overwrite the observedAttributes getter
// to include also booleanAttributes
const attributes = booleanAttributes.concat(observedAttributes);
if (attributes.length)
defineProperty(Class, 'observedAttributes', {
get() { return attributes; }
});
// created() {}
// ---------------------------------
// an initializer method that grants
// the node is fully known to the browser.
// It is ensured to run either after DOMContentLoaded,
// or once there is a next sibling (stream-friendly) so that
// you have full access to element attributes and/or childNodes.
const created = proto.created || function () {
this.render();
};
// used to ensure create() is called once and once only
defineProperty(
proto,
'_init$',
{
configurable: true,
writable: true,
value: true
}
);
defineProperty(
proto,
ATTRIBUTE_CHANGED_CALLBACK,
{
configurable: true,
value: function aCC(name, prev, curr) {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$)
return this._init$$.push(aCC.bind(this, name, prev, curr));
}
// ensure setting same value twice
// won't trigger twice attributeChangedCallback
if (hasChange && prev !== curr) {
onChanged.apply(this, arguments);
}
}
}
);
const onConnected = proto.connectedCallback;
const hasConnect = !!onConnected;
defineProperty(
proto,
'connectedCallback',
{
configurable: true,
value: function cC() {
if (this._init$) {
checkReady.call(this, created, attributes, booleanAttributes);
if (this._init$)
return this._init$$.push(cC.bind(this));
}
if (hasConnect) {
onConnected.apply(this, arguments);
}
}
}
);
// define lazily all handlers
// class { handleClick() { ... }
// render() { `<a onclick=${this.handleClick}>` } }
getOwnPropertyNames(proto).forEach(key => {
if (/^handle[A-Z]/.test(key)) {
const _key$ = '_' + key + '$';
const method = proto[key];
defineProperty(proto, key, {
configurable: true,
get() {
return this[_key$] ||
(this[_key$] = method.bind(this));
}
});
}
});
// whenever you want to directly use the component itself
// as EventListener, you can pass it directly.
// https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
// class Reactive extends HyperHTMLElement {
// oninput(e) { console.log(this, 'changed', e.target.value); }
// render() { this.html`<input oninput="${this}">`; }
// }
if (!('handleEvent' in proto)) {
defineProperty(
proto,
'handleEvent',
{
configurable: true,
value(event) {
this[
(event.currentTarget.dataset || {}).call ||
('on' + event.type)
](event);
}
}
);
}
if (options && options.extends) {
const Native = document.createElement(options.extends).constructor;
const Intermediate = class extends Native {};
const ckeys = ['length', 'name', 'arguments', 'caller', 'prototype'];
const pkeys = [];
let Super = null;
let BaseClass = Class;
while (Super = getPrototypeOf(BaseClass)) {
[
{target: Intermediate, base: Super, keys: ckeys},
{target: Intermediate.prototype, base: Super.prototype, keys: pkeys}
]
.forEach(({target, base, keys}) => {
ownKeys(base)
.filter(key => keys.indexOf(key) < 0)
.forEach((key) => {
keys.push(key);
defineProperty(
target,
key,
getOwnPropertyDescriptor(base, key)
);
});
});
BaseClass = Super;
if (Super === HyperHTMLElement)
break;
}
setPrototypeOf(Class, Intermediate);
setPrototypeOf(proto, Intermediate.prototype);
customElements.define(name, Class, options);
} else {
customElements.define(name, Class);
}
classes.push(Class);
return Class;
}
// weakly relate the shadowRoot for refs usage
attachShadow() {
const shadowRoot = attachShadow.apply(this, arguments);
sr.set(this, shadowRoot);
return shadowRoot;
}
// returns elements by ref
get refs() {
const value = {};
if ('_html$' in this) {
const all = (sr.get(this) || this).querySelectorAll('[ref]');
for (let {length} = all, i = 0; i < length; i++) {
const node = all[i];
value[node.getAttribute('ref')] = node;
}
Object.defineProperty(this, 'refs', {value});
return value;
}
return value;
}
// lazily bind once hyperHTML logic
// to either the shadowRoot, if present and open,
// the _shadowRoot property, if set due closed shadow root,
// or the custom-element itself if no Shadow DOM is used.
get html() {
return this._html$ || (this.html = bind(
// in a way or another, bind to the right node
// backward compatible, first two could probably go already
this.shadowRoot || this._shadowRoot || sr.get(this) || this
));
}
// it can be set too if necessary, it won't invoke render()
set html(value) {
defineProperty(this, '_html$', {configurable: true, value: value});
}
// overwrite this method with your own render
render() {}
// ---------------------//
// Basic State Handling //
// ---------------------//
// define the default state object
// you could use observed properties too
get defaultState() { return {}; }
// the state with a default
get state() {
return this._state$ || (this.state = this.defaultState);
}
// it can be set too if necessary, it won't invoke render()
set state(value) {
defineProperty(this, '_state$', {configurable: true, value: value});
}
// currently a state is a shallow copy, like in Preact or other libraries.
// after the state is updated, the render() method will be invoked.
// ⚠️ do not ever call this.setState() inside this.render()
setState(state, render) {
const target = this.state;
const source = typeof state === 'function' ? state.call(this, target) : state;
for (const key in source) target[key] = source[key];
if (render !== false) this.render();
return this;
}
}
// exposing hyperHTML utilities
HyperHTMLElement.Component = Component;
HyperHTMLElement.bind = bind;
HyperHTMLElement.intent = define;
HyperHTMLElement.wire = wire;
HyperHTMLElement.hyper = hyper;
try {
if (Symbol.hasInstance) classes.push(
defineProperty(HyperHTMLElement, Symbol.hasInstance, {
enumerable: false,
configurable: true,
value(instance) {
return classes.some(isPrototypeOf, getPrototypeOf(instance));
}
}));
} catch(meh) {}
// ------------------------------//
// DOMContentLoaded VS created() //
// ------------------------------//
const dom = {
type: 'DOMContentLoaded',
handleEvent() {
if (dom.ready()) {
document.removeEventListener(dom.type, dom, false);
dom.list.splice(0).forEach(invoke);
}
else
setTimeout(dom.handleEvent);
},
ready() {
return document.readyState === 'complete';
},
list: []
};
if (!dom.ready()) {
document.addEventListener(dom.type, dom, false);
}
function checkReady(created, attributes, booleanAttributes) {
if (dom.ready() || isReady.call(this, created, attributes, booleanAttributes)) {
if (this._init$) {
const list = this._init$$ || [];
delete this._init$$;
const self = defineProperty(this, '_init$', {value: false});
booleanAttributes.forEach(name => {
if (self.getAttribute(name) === 'false')
self.removeAttribute(name);
});
attributes.forEach(name => {
if (self.hasOwnProperty(name)) {
const curr = self[name];
delete self[name];
list.unshift(() => { self[name] = curr; });
}
});
created.call(self);
list.forEach(invoke);
}
} else {
if (!this.hasOwnProperty('_init$$'))
defineProperty(this, '_init$$', {configurable: true, value: []});
dom.list.push(checkReady.bind(this, created, attributes, booleanAttributes));
}
}
function invoke(fn) {
fn();
}
function isPrototypeOf(Class) {
return this === Class.prototype;
}
function isReady(created, attributes, booleanAttributes) {
let el = this;
do { if (el.nextSibling) return true; }
while (el = el.parentNode);
setTimeout(checkReady.bind(this, created, attributes, booleanAttributes));
return false;
}
exports['default'] = HyperHTMLElement;
Object.defineProperty(exports, '__esModule', { value: true });
return exports.default;
}({}));
================================================
FILE: min.js
================================================
/*! (c) Andrea Giammarchi - ISC */
var HyperHTMLElement=function(e){"use strict";var t={};try{t.WeakMap=WeakMap}catch(e){t.WeakMap=function(e,t){var n=t.defineProperty,r=t.hasOwnProperty,i=o.prototype;return i.delete=function(e){return this.has(e)&&delete e[this._]},i.get=function(e){return this.has(e)?e[this._]:void 0},i.has=function(e){return r.call(e,this._)},i.set=function(e,t){return n(e,this._,{configurable:!0,value:t}),this},o;function o(t){n(this,"_",{value:"_@ungap/weakmap"+e++}),t&&t.forEach(s,this)}function s(e){this.set(e[0],e[1])}}(Math.random(),Object)}var n=t.WeakMap,r={};try{r.WeakSet=WeakSet}catch(e){!function(e,t){var n=i.prototype;function i(){t(this,"_",{value:"_@ungap/weakmap"+e++})}n.add=function(e){return this.has(e)||t(e,this._,{value:!0,configurable:!0}),this},n.has=function(e){return this.hasOwnProperty.call(e,this._)},n.delete=function(e){return this.has(e)&&delete e[this._]},r.WeakSet=i}(Math.random(),Object.defineProperty)}var i=r.WeakSet;const{indexOf:o,slice:s}=[],a=(e,t,n,r,i,s)=>{const a="selectedIndex"in t;let l=a;for(;r<i;){const i=e(n[r],1);if(t.insertBefore(i,s),a&&l&&i.selected){l=!l;let{s
gitextract_91jr2tdp/ ├── .github/ │ └── workflows/ │ └── node.js.yml ├── .gitignore ├── .npmignore ├── .npmrc ├── LICENSE.txt ├── README.md ├── cjs/ │ ├── index.d.ts │ ├── index.js │ └── package.json ├── es5.config.js ├── es5.js ├── esm/ │ ├── index.d.ts │ └── index.js ├── esm.config.js ├── index.d.ts ├── index.js ├── min.js ├── package.json ├── test/ │ ├── boolean.html │ ├── builtin.html │ ├── button.html │ ├── ce.js │ ├── checked.html │ ├── index.html │ ├── test.es5.js │ └── test.js ├── test.js └── typescript.md
SYMBOL INDEX (304 symbols across 10 files)
FILE: cjs/index.js
constant ATTRIBUTE_CHANGED_CALLBACK (line 7) | const ATTRIBUTE_CHANGED_CALLBACK = 'attributeChangedCallback';
class HyperHTMLElement (line 28) | class HyperHTMLElement extends HTMLElement {
method define (line 33) | static define(name, options) {
method attachShadow (line 252) | attachShadow() {
method refs (line 259) | get refs() {
method html (line 277) | get html() {
method html (line 286) | set html(value) {
method render (line 291) | render() {}
method defaultState (line 299) | get defaultState() { return {}; }
method state (line 302) | get state() {
method state (line 307) | set state(value) {
method setState (line 314) | setState(state, render) {
method value (line 336) | value(instance) {
method handleEvent (line 349) | handleEvent() {
method ready (line 357) | ready() {
function checkReady (line 367) | function checkReady(created, attributes, booleanAttributes) {
function invoke (line 394) | function invoke(fn) {
function isPrototypeOf (line 398) | function isPrototypeOf(Class) {
function isReady (line 402) | function isReady(created, attributes, booleanAttributes) {
FILE: es5.js
function _typeof (line 4) | function _typeof(obj) {
function _classCallCheck (line 20) | function _classCallCheck(instance, Constructor) {
function _defineProperties (line 26) | function _defineProperties(target, props) {
function _createClass (line 36) | function _createClass(Constructor, protoProps, staticProps) {
function _inherits (line 42) | function _inherits(subClass, superClass) {
function _getPrototypeOf (line 57) | function _getPrototypeOf(o) {
function _setPrototypeOf (line 64) | function _setPrototypeOf(o, p) {
function _isNativeReflectConstruct (line 73) | function _isNativeReflectConstruct() {
function _construct (line 86) | function _construct(Parent, args, Class) {
function _isNativeFunction (line 103) | function _isNativeFunction(fn) {
function _wrapNativeSuper (line 107) | function _wrapNativeSuper(Class) {
function _assertThisInitialized (line 141) | function _assertThisInitialized(self) {
function _possibleConstructorReturn (line 149) | function _possibleConstructorReturn(self, call) {
function _createSuper (line 159) | function _createSuper(Derived) {
function WeakMap (line 214) | function WeakMap(iterable) {
function add (line 221) | function add(pair) {
function WeakSet (line 256) | function WeakSet() {
function dropChild (line 548) | function dropChild() {
function CustomEvent (line 659) | function CustomEvent(type, init) {
function contains (line 706) | function contains(v) {
function Component (line 723) | function Component() {
function setup (line 728) | function setup(content) {
function append (line 959) | function append(root, childNodes) {
function create (line 967) | function create(element) {
function createSVG (line 974) | function createSVG(svg) {
function disconnected (line 984) | function disconnected(poly) {
function sanitize (line 1134) | function sanitize (template) {
function attrReplacer (line 1146) | function attrReplacer($0, $1, $2, $3) {
function replaceAttributes (line 1150) | function replaceAttributes($0, $1, $2) {
function fullClosing (line 1154) | function fullClosing($0, $1, $2) {
function find (line 1185) | function find(node, path) {
function parse (line 1196) | function parse(node, holes, parts, path) {
function parseAttributes (line 1254) | function parseAttributes(node, holes, parts, path) {
function Any (line 1340) | function Any(node, path) {
function Attr (line 1348) | function Attr(node, path, name, sparse) {
function Text (line 1358) | function Text(node, path) {
function createInfo (line 1369) | function createInfo(options, template) {
function createDetails (line 1458) | function createDetails(options, template) {
function domtagger (line 1465) | function domtagger(options) {
function cleanContent (line 1474) | function cleanContent(fragment) {
function ized (line 1496) | function ized($0, $1, $2) {
function svg (line 1500) | function svg(node, original) {
function toStyle (line 1511) | function toStyle(object) {
function update (line 1522) | function update(style, isSVG) {
function Wire (line 1610) | function Wire(childNodes) {
function Tagger (line 1718) | function Tagger(type) {
function TL (line 2007) | function TL(tl) {
function tta (line 2011) | function tta (template) {
function render (line 2111) | function render() {
function upgrade (line 2128) | function upgrade(template) {
function hyper (line 2172) | function hyper(HTML) {
function HyperHTMLElement (line 2222) | function HyperHTMLElement() {
function Intermediate (line 2471) | function Intermediate() {
function checkReady (line 2560) | function checkReady(created, attributes, booleanAttributes) {
function invoke (line 2592) | function invoke(fn) {
function isPrototypeOf (line 2596) | function isPrototypeOf(Class) {
function isReady (line 2600) | function isReady(created, attributes, booleanAttributes) {
FILE: esm/index.js
constant ATTRIBUTE_CHANGED_CALLBACK (line 6) | const ATTRIBUTE_CHANGED_CALLBACK = 'attributeChangedCallback';
class HyperHTMLElement (line 27) | class HyperHTMLElement extends HTMLElement {
method define (line 32) | static define(name, options) {
method attachShadow (line 251) | attachShadow() {
method refs (line 258) | get refs() {
method html (line 276) | get html() {
method html (line 285) | set html(value) {
method render (line 290) | render() {}
method defaultState (line 298) | get defaultState() { return {}; }
method state (line 301) | get state() {
method state (line 306) | set state(value) {
method setState (line 313) | setState(state, render) {
method value (line 335) | value(instance) {
method handleEvent (line 348) | handleEvent() {
method ready (line 356) | ready() {
function checkReady (line 366) | function checkReady(created, attributes, booleanAttributes) {
function invoke (line 393) | function invoke(fn) {
function isPrototypeOf (line 397) | function isPrototypeOf(Class) {
function isReady (line 401) | function isReady(created, attributes, booleanAttributes) {
FILE: index.d.ts
type HyperHTMLElement (line 3) | interface HyperHTMLElement<T = {}> extends HTMLElement {
class HyperHTMLElement (line 73) | class HyperHTMLElement<T = {}> {
FILE: index.js
function WeakMap (line 27) | function WeakMap(iterable) {
function add (line 32) | function add(pair) {
function WeakSet (line 57) | function WeakSet() { dP(this, '_', {value: '_@ungap/weakmap' + id++});
function dropChild (line 435) | function dropChild() {
function CustomEvent (line 661) | function CustomEvent(type, init) {
function contains (line 706) | function contains(v) {
function Component (line 722) | function Component() {
function setup (line 728) | function setup(content) {
method get (line 844) | get() {
method set (line 847) | set(value) {
function append (line 954) | function append(root, childNodes) {
function create (line 960) | function create(element) {
function createSVG (line 969) | function createSVG(svg) {
function disconnected (line 980) | function disconnected(poly) { var Event = poly.Event;
function sanitize (line 1164) | function sanitize (template) {
function attrReplacer (line 1180) | function attrReplacer($0, $1, $2, $3) {
function replaceAttributes (line 1184) | function replaceAttributes($0, $1, $2) {
function fullClosing (line 1188) | function fullClosing($0, $1, $2) {
function find (line 1215) | function find(node, path) {
function parse (line 1223) | function parse(node, holes, parts, path) {
function parseAttributes (line 1278) | function parseAttributes(node, holes, parts, path) {
function Any (line 1361) | function Any(node, path) {
function Attr (line 1369) | function Attr(node, path, name, sparse) {
function Text (line 1379) | function Text(node, path) {
function createInfo (line 1391) | function createInfo(options, template) {
function createDetails (line 1462) | function createDetails(options, template) {
function domtagger (line 1468) | function domtagger(options) {
function cleanContent (line 1478) | function cleanContent(fragment) {
function ized (line 1499) | function ized($0, $1, $2) {
function svg (line 1502) | function svg(node, original) {
function toStyle (line 1514) | function toStyle(object) {
function update (line 1520) | function update(style, isSVG) {
function Wire (line 1614) | function Wire(childNodes) {
function Tagger (line 1716) | function Tagger(type) {
method attribute (line 1730) | attribute(node, name, original) {
method any (line 1833) | any(node, childNodes) {
method text (line 1956) | text(node) {
function TL (line 2032) | function TL(tl) {
function tta (line 2036) | function tta (template) {
function render (line 2135) | function render() {
function upgrade (line 2150) | function upgrade(template) {
function hyper (line 2193) | function hyper(HTML) {
class HyperHTMLElement (line 2236) | class HyperHTMLElement extends HTMLElement {
method define (line 2241) | static define(name, options) {
method attachShadow (line 2460) | attachShadow() {
method refs (line 2467) | get refs() {
method html (line 2485) | get html() {
method html (line 2494) | set html(value) {
method render (line 2499) | render() {}
method defaultState (line 2507) | get defaultState() { return {}; }
method state (line 2510) | get state() {
method state (line 2515) | set state(value) {
method setState (line 2522) | setState(state, render) {
method value (line 2543) | value(instance) {
method handleEvent (line 2554) | handleEvent() {
method ready (line 2562) | ready() {
function checkReady (line 2572) | function checkReady(created, attributes, booleanAttributes) {
function invoke (line 2599) | function invoke(fn) {
function isPrototypeOf (line 2603) | function isPrototypeOf(Class) {
function isReady (line 2607) | function isReady(created, attributes, booleanAttributes) {
FILE: min.js
function o (line 2) | function o(t){n(this,"_",{value:"_@ungap/weakmap"+e++}),t&&t.forEach(s,t...
function s (line 2) | function s(e){this.set(e[0],e[1])}
function i (line 2) | function i(){t(this,"_",{value:"_@ungap/weakmap"+e++})}
function t (line 2) | function t(e,t){t||(t={});var n=document.createEvent("CustomEvent");retu...
function r (line 2) | function r(n){return-1<(e=t.indexOf(n))}
function E (line 2) | function E(){return this}
method get (line 2) | get(){return this[n]||N(this,n,t.call(this,e))}
method set (line 2) | set(e){N(this,n,e)}
function r (line 2) | function r(e,t){for(var n=t.length;n--;)e.appendChild(t[0])}
function i (line 2) | function i(n){return n===t?e.createDocumentFragment():e.createElementNS(...
function Y (line 2) | function Y(e,t,n,r){return"<"+t+n.replace(X,ee)+r}
function ee (line 2) | function ee(e,t,n){return t+(n||'"')+W+(n||'"')}
function te (line 2) | function te(e,t,n){return V.test(t)?e:"<"+t+n+"></"+t+">"}
function re (line 2) | function re(e,t){for(var n=t.length,r=0;r<n;)e=e.childNodes[t[r++]];retu...
function ie (line 2) | function ie(e,t,n,r){for(var i=e.attributes,o=[],s=[],a=ne(i,n),l=a.leng...
function oe (line 2) | function oe(e,t){return{type:"any",node:e,path:t}}
function se (line 2) | function se(e,t,n,r){return{type:"attr",node:e,path:t,name:n,sparse:r}}
function ae (line 2) | function ae(e,t){return{type:"text",node:e,path:t}}
function ce (line 2) | function ce(e,t){var n=(e.convert||function(e){return e.join(H).replace(...
function he (line 2) | function he(e){var t=ue,n=fe;return function(r){return t!==r&&(n=functio...
function fe (line 2) | function fe(e){for(var t=e.childNodes,n=t.length;n--;){var r=t[n];1!==r....
function n (line 2) | function n(e,t,n){return t+"-"+n.toLowerCase()}
function r (line 2) | function r(r,i){var o,s;return function(a){var l,c,u,h;switch(typeof a){...
function n (line 2) | function n(t){var n=this.childNodes=e.call(t,0);this.firstChild=n[0],thi...
function c (line 2) | function c(e){for(var t,n=e.length,i=0;i<n;i++)u((t=e[i]).removedNodes,"...
function u (line 2) | function u(e,n,r,i){for(var o,s=new t(n),a=e.length,l=0;l<a;1===(o=e[l++...
function h (line 2) | function h(e,t,n,r,o){i.has(e)&&!r.has(e)&&(o.delete(e),r.add(e),e.dispa...
function Ce (line 2) | function Ce(e){return this.type=e,he(this)}
method attribute (line 2) | attribute(e,t,n){const r=ve in e;let i;if("style"===t)return de(e,n,r);i...
method any (line 2) | any(e,t){const n={node:we,before:e},r=ve in e?"svg":"html";let i,o=!1;co...
method text (line 2) | text(e){let t;const n=r=>{if(t!==r){t=r;const i=typeof r;"object"===i&&r...
function Oe (line 2) | function Oe(e){return Ae?e:ke(e)}
function Se (line 2) | function Se(e){for(var t=arguments.length,n=[Oe(e)],r=1;r<t;)n.push(argu...
function De (line 2) | function De(){const e=Le.get(this),t=Se.apply(null,arguments);return e&&...
function Ie (line 2) | function Ie(e){return arguments.length<2?null==e?Me("html"):"string"==ty...
method value (line 2) | value(e,o){return((e,t,o,s)=>{const a=t.get(e)||i(e,t);switch(typeof s){...
method value (line 2) | value(e){const t=e.currentTarget;this["getAttribute"in t&&t.getAttribute...
method value (line 2) | value(e,t){const{_wire$:n}=this;if(n){const r=new b(e,{bubbles:!0,cancel...
method value (line 2) | value(e,t){const n=this.state,r="function"==typeof e?e.call(this,n):e;fo...
class et (line 2) | class et extends HTMLElement{static define(e,t){const n=this,r=n.prototy...
method define (line 2) | static define(e,t){const n=this,r=n.prototype,i=r[Fe],o=!!i,s=n.boolea...
method attachShadow (line 2) | attachShadow(){const e=Xe.apply(this,arguments);return Ye.set(this,e),e}
method refs (line 2) | get refs(){const e={};if("_html$"in this){const t=(Ye.get(this)||this)...
method html (line 2) | get html(){return this._html$||(this.html=We(this.shadowRoot||this._sh...
method html (line 2) | set html(e){Ve(this,"_html$",{configurable:!0,value:e})}
method render (line 2) | render(){}
method defaultState (line 2) | get defaultState(){return{}}
method state (line 2) | get state(){return this._state$||(this.state=this.defaultState)}
method state (line 2) | set state(e){Ve(this,"_state$",{configurable:!0,value:e})}
method setState (line 2) | setState(e,t){const n=this.state,r="function"==typeof e?e.call(this,n)...
method handleEvent (line 2) | handleEvent(){tt.ready()?(document.removeEventListener(tt.type,tt,!1),tt...
function nt (line 2) | function nt(e,t,n){if(tt.ready()||function(e,t,n){let r=this;do{if(r.nex...
function rt (line 2) | function rt(e){e()}
function it (line 2) | function it(e){return this===e.prototype}
FILE: test.js
class MyElement (line 28) | class MyElement extends HyperHTMLElement {
method booleanAttributes (line 30) | static get booleanAttributes() {
method special (line 34) | get special() { return false; }
method observedAttributes (line 36) | static get observedAttributes() {
method constructor (line 40) | constructor(...args) {
method nextSibling (line 46) | get nextSibling() {
method created (line 51) | created() {
method attributeChangedCallback (line 55) | attributeChangedCallback() {
method connectedCallback (line 59) | connectedCallback() {
method render (line 63) | render() {
class MyLink (line 71) | class MyLink extends HyperHTMLElement {}
class MyInput (line 102) | class MyInput extends HyperHTMLElement {
method booleanAttributes (line 104) | static get booleanAttributes() {
method observedAttributes (line 108) | static get observedAttributes() {
method value (line 112) | get value() {
method value (line 116) | set value(value) {
method attributeChangedCallback (line 120) | attributeChangedCallback() {
class MyEmptiness (line 146) | class MyEmptiness extends HyperHTMLElement {}
class MyAttr (line 151) | class MyAttr extends HyperHTMLElement {
method observedAttributes (line 152) | static get observedAttributes() {
method created (line 155) | created() {
method attributeChangedCallback (line 158) | attributeChangedCallback() {}
class MyConnect (line 165) | class MyConnect extends HyperHTMLElement {
method created (line 166) | created() { this.counter = 0; }
method connectedCallback (line 167) | connectedCallback() {
class MyCreate (line 178) | class MyCreate extends HyperHTMLElement {
method created (line 179) | created() {
class MyAttrHack (line 187) | class MyAttrHack extends HyperHTMLElement {
method observedAttributes (line 188) | static get observedAttributes() {
method attributeChangedCallback (line 191) | attributeChangedCallback() {
class MyAttrHack2 (line 217) | class MyAttrHack2 extends HyperHTMLElement {
method observedAttributes (line 218) | static get observedAttributes() {
method created (line 221) | created() {
class MyHandler (line 233) | class MyHandler extends HyperHTMLElement {
method booleanAttributes (line 234) | static get booleanAttributes() {
method handleEvent (line 237) | handleEvent() { this.value = 123; return this; }
class MyRealHandler (line 250) | class MyRealHandler extends HyperHTMLElement {
method onclick (line 251) | onclick() { tressa.assert(true, 'click event dispatched'); }
method created (line 252) | created() { this.html`<span onclick="${this}">click me</span>`; }
class MyDelegatedHandler (line 268) | class MyDelegatedHandler extends HyperHTMLElement {
method whenClickHappens (line 269) | whenClickHappens() { tressa.assert(true, 'whenClickHappens event dispa...
method created (line 270) | created() { this.html`<span ref="span" data-call="whenClickHappens" on...
class MyShadow (line 286) | class MyShadow extends HyperHTMLElement {
method constructor (line 287) | constructor() {
class MyCreated (line 300) | class MyCreated extends HyperHTMLElement {
method created (line 301) | created() { createdInstances++; }
class StateHandlerDefault (line 312) | class StateHandlerDefault extends HyperHTMLElement {
method updateState (line 313) | updateState(state) {
class StateHandler (line 329) | class StateHandler extends HyperHTMLElement {
method defaultState (line 330) | get defaultState() {
method updateState (line 333) | updateState(state) {
class StateHandlerCallback (line 349) | class StateHandlerCallback extends HyperHTMLElement {}
class DefaultState (line 361) | class DefaultState extends HyperHTMLElement {
method defaultState (line 362) | get defaultState() { return {a: 'a'}; }
method render (line 363) | render() {}
class State (line 366) | class State extends HyperHTMLElement {}
class LateToTheParty (line 381) | class LateToTheParty extends HyperHTMLElement {
method booleanAttributes (line 382) | static get booleanAttributes() { return ['test']; }
method attributeChangedCallback (line 383) | attributeChangedCallback(name, prev, curr) {
class KebabHouse (line 395) | class KebabHouse extends HyperHTMLElement {
method observedAttributes (line 396) | static get observedAttributes() {
method kebabSold (line 400) | get kebabSold () {
FILE: test/ce.js
function then (line 18) | function then(fn) {
function HTMLBuiltIn (line 432) | function HTMLBuiltIn() {
FILE: test/test.es5.js
function _typeof (line 3) | function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol ===...
function _taggedTemplateLiteral (line 7) | function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = string...
function _classCallCheck (line 9) | function _classCallCheck(instance, Constructor) { if (!(instance instanc...
function _defineProperties (line 11) | function _defineProperties(target, props) { for (var i = 0; i < props.le...
function _createClass (line 13) | function _createClass(Constructor, protoProps, staticProps) { if (protoP...
function _inherits (line 15) | function _inherits(subClass, superClass) { if (typeof superClass !== "fu...
function _setPrototypeOf (line 17) | function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf...
function _createSuper (line 19) | function _createSuper(Derived) { var hasNativeReflectConstruct = _isNati...
function _possibleConstructorReturn (line 21) | function _possibleConstructorReturn(self, call) { if (call && (_typeof(c...
function _assertThisInitialized (line 23) | function _assertThisInitialized(self) { if (self === void 0) { throw new...
function _isNativeReflectConstruct (line 25) | function _isNativeReflectConstruct() { if (typeof Reflect === "undefined...
function _getPrototypeOf (line 27) | function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? ...
function MySelf (line 34) | function MySelf() {
function MyInput (line 77) | function MyInput() {
function MyLink (line 117) | function MyLink() {
FILE: test/test.js
class MySelf (line 1) | class MySelf extends HyperHTMLElement {
method booleanAttributes (line 2) | static get booleanAttributes() { return ['active']; }
method observedAttributes (line 3) | static get observedAttributes() { return ['name', 'age']; }
method created (line 4) | created() { this.render(); }
method attributeChangedCallback (line 5) | attributeChangedCallback() { this.render(); }
method render (line 6) | render() { return this.html`
class MyInput (line 13) | class MyInput extends HyperHTMLElement {
method observedAttributes (line 14) | static get observedAttributes() { return ['value', 'boolean']; }
method attributeChangedCallback (line 15) | attributeChangedCallback() { this.render(); }
method oninput (line 16) | oninput(e) {
method render (line 21) | render() { return this.html`
class MyLink (line 27) | class MyLink extends HyperHTMLElement {
method created (line 28) | created() {
method render (line 32) | render () {
Condensed preview — 28 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (276K chars).
[
{
"path": ".github/workflows/node.js.yml",
"chars": 872,
"preview": "# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests ac"
},
{
"path": ".gitignore",
"chars": 48,
"preview": ".DS_Store\n.nyc_output/\nnode_modules/\ncoverage/\n\n"
},
{
"path": ".npmignore",
"chars": 144,
"preview": ".nyc_output/\ncoverage/\nnode_modules/\ntest/*\n.babelrc\n.gitignore\n.travis.yml\nes5.config.js\nesm.config.js\npackage-lock.jso"
},
{
"path": ".npmrc",
"chars": 36,
"preview": "package-lock=true\npackage-lock=true\n"
},
{
"path": "LICENSE.txt",
"chars": 770,
"preview": "ISC License\n\nCopyright (c) 2017-2018, Andrea Giammarchi, @WebReflection\n\nPermission to use, copy, modify, and/or distrib"
},
{
"path": "README.md",
"chars": 4789,
"preview": "# hyperHTML-Element\n\n[](https://opensource.org/licen"
},
{
"path": "cjs/index.d.ts",
"chars": 89,
"preview": "import HyperHTMLElement from \"..\";\r\nexport * from '..';\r\nexport default HyperHTMLElement;"
},
{
"path": "cjs/index.js",
"chars": 12646,
"preview": "'use strict';\n/*! (C) 2017-2018 Andrea Giammarchi - ISC Style License */\n\nconst {Component, bind, define, hyper, wire} ="
},
{
"path": "cjs/package.json",
"chars": 19,
"preview": "{\"type\":\"commonjs\"}"
},
{
"path": "es5.config.js",
"chars": 379,
"preview": "import resolve from 'rollup-plugin-node-resolve';\nimport babel from 'rollup-plugin-babel';\n\nexport default {\n input: 'e"
},
{
"path": "es5.js",
"chars": 81887,
"preview": "var HyperHTMLElement = (function (exports) {\n 'use strict';\n\n function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n"
},
{
"path": "esm/index.d.ts",
"chars": 89,
"preview": "import HyperHTMLElement from \"..\";\r\nexport * from '..';\r\nexport default HyperHTMLElement;"
},
{
"path": "esm/index.js",
"chars": 12572,
"preview": "/*! (C) 2017-2018 Andrea Giammarchi - ISC Style License */\n\nimport {Component, bind, define, hyper, wire} from 'hyperhtm"
},
{
"path": "esm.config.js",
"chars": 307,
"preview": "import resolve from 'rollup-plugin-node-resolve';\n\nexport default {\n input: 'esm/index.js',\n plugins: [\n resolve({\n"
},
{
"path": "index.d.ts",
"chars": 3380,
"preview": "import { bind, hyper, wire, define, Component, WiredTemplateFunction } from \"hyperhtml\";\n\ninterface HyperHTMLElement<T ="
},
{
"path": "index.js",
"chars": 78813,
"preview": "var HyperHTMLElement = (function (exports) {\n 'use strict';\n\n /*! (c) Andrea Giammarchi - ISC */\n var self$3 = {};\n "
},
{
"path": "min.js",
"chars": 22326,
"preview": "/*! (c) Andrea Giammarchi - ISC */\nvar HyperHTMLElement=function(e){\"use strict\";var t={};try{t.WeakMap=WeakMap}catch(e)"
},
{
"path": "package.json",
"chars": 2955,
"preview": "{\n \"name\": \"hyperhtml-element\",\n \"version\": \"3.15.2\",\n \"description\": \"An extensible class to define hyperHTML based "
},
{
"path": "test/boolean.html",
"chars": 1053,
"preview": "<!doctype html>\n<html lang=\"en\">\n<head>\n <script>document.write(\n '<script src=\"../' + (location.search.toLoca"
},
{
"path": "test/builtin.html",
"chars": 2501,
"preview": "<!doctype html>\n<html lang=\"en\">\n<head>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/document-register-elemen"
},
{
"path": "test/button.html",
"chars": 1157,
"preview": "<!doctype html>\n<html>\n <head>\n <title>HyperHTMLElement Custom Elements BuiltIn</title>\n <script>if(this.customEl"
},
{
"path": "test/ce.js",
"chars": 15647,
"preview": "/*! (c) Andrea Giammarchi @webreflection ISC */\n(function () {\n 'use strict';\n\n var Lie = typeof Promise === 'function"
},
{
"path": "test/checked.html",
"chars": 1157,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">"
},
{
"path": "test/index.html",
"chars": 678,
"preview": "<!doctype html>\n<html>\n <head>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/document-register-element/1.9.1/"
},
{
"path": "test/test.es5.js",
"chars": 6298,
"preview": "\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iter"
},
{
"path": "test/test.js",
"chars": 1282,
"preview": "class MySelf extends HyperHTMLElement {\n static get booleanAttributes() { return ['active']; }\n static get observedAtt"
},
{
"path": "test.js",
"chars": 11514,
"preview": "const tressa = require('tressa');\nconst {parseHTML} = require('linkedom');\n\nconst {document, customElements, HTMLElement"
},
{
"path": "typescript.md",
"chars": 2219,
"preview": "# Usage with Typescript\nYou can import the library and use it with Typescript:\n\n```ts\nimport HyperHTMLElement from \"hype"
}
]
About this extraction
This page contains the full source code of the WebReflection/hyperHTML-Element GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 28 files (259.4 KB), approximately 66.5k tokens, and a symbol index with 304 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.