move demo/static/src/ts/core to src/

This commit is contained in:
Géry Debongnie
2019-03-14 11:23:10 +01:00
parent 2ffb0fd64c
commit f08ff9e5c2
103 changed files with 32 additions and 32 deletions
+333
View File
@@ -0,0 +1,333 @@
import h from "./snabbdom/src/h";
import sdAttrs from "./snabbdom/src/modules/attributes";
import sdListeners from "./snabbdom/src/modules/eventlisteners";
import { init } from "./snabbdom/src/snabbdom";
import { VNode } from "./snabbdom/src/vnode";
import { EventBus } from "./event_bus";
import { QWeb } from "./qweb_vdom";
import { idGenerator } from "./utils";
let getId = idGenerator();
//------------------------------------------------------------------------------
// Types/helpers
//------------------------------------------------------------------------------
export interface WEnv {
qweb: QWeb;
}
let wl: any[] = [];
(<any>window).wl = wl;
export interface Meta<T extends WEnv, Props> {
readonly id: number;
vnode: VNode | null;
isStarted: boolean;
isMounted: boolean;
isDestroyed: boolean;
parent: Component<T, any, any> | null;
children: { [key: number]: Component<T, any, any> };
// children mapping: from templateID to widgetID
// should it be a map number => Widget?
cmap: { [key: number]: number };
renderId: number;
renderProps: Props | null;
renderPromise: Promise<VNode> | null;
boundHandlers: { [key: number]: any };
}
const patch = init([sdListeners, sdAttrs]);
export interface Type<T> extends Function {
new (...args: any[]): T;
}
//------------------------------------------------------------------------------
// Widget
//------------------------------------------------------------------------------
export class Component<
T extends WEnv,
Props,
State extends {}
> extends EventBus {
readonly __widget__: Meta<WEnv, Props>;
template: string = "default";
inlineTemplate: string | null = null;
get el(): HTMLElement | null {
return this.__widget__.vnode ? (<any>this).__widget__.vnode.elm : null;
}
env: T;
state: State = <State>{};
props: Props;
refs: {
[key: string]: Component<T, any, any> | HTMLElement | undefined;
} = {};
//--------------------------------------------------------------------------
// Lifecycle
//--------------------------------------------------------------------------
constructor(parent: Component<T, any, any> | T, props?: Props) {
super();
wl.push(this);
// is this a good idea?
// Pro: if props is empty, we can create easily a widget
// Con: this is not really safe
// Pro: but creating widget (by a template) is always unsafe anyway
this.props = <Props>props;
let id: number;
let p: Component<T, any, any> | null = null;
if (parent instanceof Component) {
p = parent;
this.env = parent.env;
id = getId();
parent.__widget__.children[id] = this;
} else {
this.env = parent;
id = getId();
}
this.__widget__ = {
id: id,
vnode: null,
isStarted: false,
isMounted: false,
isDestroyed: false,
parent: p,
children: {},
cmap: {},
renderId: 1,
renderPromise: null,
renderProps: props || null,
boundHandlers: {}
};
}
async willStart() {}
mounted() {}
shouldUpdate(nextProps: Props): boolean {
return true;
}
willUnmount() {}
destroyed() {}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Attach a child widget to a given html element
*
* This is most of the time not necessary, since widgets should primarily be
* created/managed with the t-widget directive in a qweb template. However,
* for the cases where we need more control, this method will do what is
* necessary to make sure all the proper hooks are called (for example,
* mounted/willUnmount)
*
* Note that this method makes a few assumptions:
* - the child widget is indeed a child of the current widget
* - the target is inside the dom of the current widget (typically a ref)
*/
attachChild(child: Component<T, any, any>, target: HTMLElement) {
target.appendChild(child.el!);
child.__mount();
}
async mount(target: HTMLElement): Promise<void> {
const vnode = await this._start();
if (this.__widget__.isDestroyed) {
// widget was destroyed before we get here...
return;
}
this._patch(vnode);
target.appendChild(this.el!);
if (document.body.contains(target)) {
this.visitSubTree(w => {
if (!w.__widget__.isMounted && this.el!.contains(w.el)) {
w.__widget__.isMounted = true;
w.mounted();
return true;
}
return false;
});
}
}
detach() {
if (this.el) {
this.visitSubTree(w => {
if (w.__widget__.isMounted) {
w.willUnmount();
w.__widget__.isMounted = false;
return true;
}
return false;
});
this.el.remove();
}
}
destroy() {
if (!this.__widget__.isDestroyed) {
for (let id in this.__widget__.children) {
this.__widget__.children[id].destroy();
}
if (this.__widget__.isMounted) {
this.willUnmount();
}
if (this.el) {
this.el.remove();
this.__widget__.isMounted = false;
delete this.__widget__.vnode;
}
if (this.__widget__.parent) {
let id = this.__widget__.id;
delete this.__widget__.parent.__widget__.children[id];
this.__widget__.parent = null;
}
this.clear();
this.__widget__.isDestroyed = true;
this.destroyed();
}
}
/**
* This is the safest update method for widget: its job is to update the state
* and rerender (if widget is mounted).
*
* Notes:
* - it checks if we do not add extra keys to the state.
* - it is ok to call updateState before the widget is started. In that
* case, it will simply update the state and will not rerender
*/
async updateState(nextState: Partial<State>) {
if (Object.keys(nextState).length === 0) {
return;
}
Object.assign(this.state, nextState);
if (this.__widget__.isStarted) {
return this.render();
}
}
async updateProps(nextProps: Props): Promise<void> {
if (nextProps === this.__widget__.renderProps) {
await this.__widget__.renderPromise;
return;
}
const shouldUpdate = this.shouldUpdate(nextProps);
return shouldUpdate ? this._updateProps(nextProps) : Promise.resolve();
}
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
async _updateProps(nextProps: Props): Promise<void> {
this.props = nextProps;
return this.render();
}
async render(): Promise<void> {
if (this.__widget__.isDestroyed) {
return;
}
const renderVDom = this._render();
const renderId = this.__widget__.renderId;
const vnode = await renderVDom;
if (renderId === this.__widget__.renderId) {
// we only update the vnode and the actual DOM if no other rendering
// occurred between now and when the render method was initially called.
this._patch(vnode);
}
}
_patch(vnode) {
this.__widget__.renderPromise = null;
this.__widget__.vnode = patch(
this.__widget__.vnode || document.createElement(vnode.sel!),
vnode
);
}
async _start(): Promise<VNode> {
this.__widget__.renderProps = this.props;
this.__widget__.renderPromise = this.willStart().then(() => {
if (this.__widget__.isDestroyed) {
return Promise.resolve(h("div"));
}
this.__widget__.isStarted = true;
if (this.inlineTemplate) {
this.env.qweb.addTemplate(
this.inlineTemplate,
this.inlineTemplate,
true
);
}
return this._render();
});
return this.__widget__.renderPromise;
}
async _render(): Promise<VNode> {
this.__widget__.renderId++;
const promises: Promise<void>[] = [];
const template = this.inlineTemplate || this.template;
let vnode = this.env.qweb.render(template, this, {
promises,
handlers: this.__widget__.boundHandlers
});
// this part is critical for the patching process to be done correctly. The
// tricky part is that a child widget can be rerendered on its own, which
// will update its own vnode representation without the knowledge of the
// parent widget. With this, we make sure that the parent widget will be
// able to patch itself properly after
vnode.key = this.__widget__.id;
this.__widget__.renderProps = this.props;
this.__widget__.renderPromise = Promise.all(promises).then(() => vnode);
return this.__widget__.renderPromise;
}
/**
* Only called by qweb t-widget directive
*/
_mount(vnode: VNode, elm: HTMLElement): VNode {
this.__widget__.vnode = patch(elm, vnode);
this.__mount();
return this.__widget__.vnode;
}
__mount() {
if (this.__widget__.isMounted) {
return;
}
if (this.__widget__.parent) {
if (this.__widget__.parent!.__widget__.isMounted) {
this.__widget__.isMounted = true;
this.mounted();
const children = this.__widget__.children;
for (let id in children) {
children[id].__mount();
}
}
}
}
visitSubTree(callback: (w: Component<T, any, any>) => boolean) {
const shouldVisitChildren = callback(this);
if (shouldVisitChildren) {
const children = this.__widget__.children;
for (let id in children) {
children[id].visitSubTree(callback);
}
}
}
}
+77
View File
@@ -0,0 +1,77 @@
/**
* We define here a simple event bus: it can
* - emit events
* - add/remove listeners.
*
* This is a useful pattern of communication in some cases.
*/
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
export type Callback = (...args: any[]) => void;
export interface Subscription {
owner: any;
callback: Callback;
}
//------------------------------------------------------------------------------
// EventBus
//------------------------------------------------------------------------------
export class EventBus {
subscriptions: { [eventType: string]: Subscription[] } = {};
/**
* Add a listener for the 'eventType' events.
*
* Note that the 'owner' of this event can be anything, but will more likely
* be a widget or a class. The idea is that the callback will be called with
* the proper owner bound.
*
* Also, the owner should be kind of unique. This will be used to remove the
* listener.
*/
on(eventType: string, owner: any, callback: Callback) {
if (!callback) {
throw new Error("Missing callback");
}
if (!this.subscriptions[eventType]) {
this.subscriptions[eventType] = [];
}
this.subscriptions[eventType].push({
owner,
callback
});
}
/**
* Remove a listener
*/
off(eventType: string, owner: any) {
const subs = this.subscriptions[eventType];
if (subs) {
this.subscriptions[eventType] = subs.filter(s => s.owner !== owner);
}
}
/**
* Emit an event of type 'eventType'. Any extra arguments will be passed to
* the listeners callback.
*/
trigger(eventType: string, ...args: any[]) {
const subs = this.subscriptions[eventType] || [];
for (let sub of subs) {
sub.callback.call(sub.owner, ...args);
}
}
/**
* Remove all subscriptions.
*/
clear() {
this.subscriptions = {};
}
}
+5
View File
@@ -0,0 +1,5 @@
import { QWeb } from "./qweb_vdom";
import { EventBus } from "./event_bus";
import { Component } from "./component";
export const core = { QWeb, EventBus, Component };
+939
View File
@@ -0,0 +1,939 @@
import h from "./snabbdom/src/h";
import { VNode } from "./snabbdom/src/vnode";
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
export type EvalContext = { [key: string]: any };
export type RawTemplate = string;
export type CompiledTemplate<T> = (context: EvalContext, extra: any) => T;
type ProcessedTemplate = Element;
const RESERVED_WORDS = "true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,this,typeof,eval,void,Math,RegExp,Array,Object,Date".split(
","
);
const WORD_REPLACEMENT = {
and: "&&",
or: "||",
gt: ">",
gte: ">=",
lt: "<",
lte: "<="
};
//------------------------------------------------------------------------------
// Compilation Context
//------------------------------------------------------------------------------
export class Context {
nextID: number = 1;
code: string[] = [];
variables: { [key: string]: any } = {};
escaping: boolean = false;
parentNode: number | null = null;
rootNode: number | null = null;
indentLevel: number = 0;
rootContext: Context;
caller: Element | undefined;
shouldDefineOwner: boolean = false;
shouldProtectContext: boolean = false;
inLoop: boolean = false;
constructor() {
this.rootContext = this;
this.addLine("let h = this.utils.h;");
}
generateID(): number {
const id = this.rootContext.nextID++;
return id;
}
withParent(node: number): Context {
const newContext: Context = Object.create(this);
if (this === this.rootContext && this.parentNode) {
throw new Error("A template should not have more than one root node");
}
newContext.parentNode = node;
if (!this.rootContext.rootNode) {
this.rootContext.rootNode = node;
}
return newContext;
}
withVariables(variables: { [key: string]: any }) {
const newContext = Object.create(this);
newContext.variables = Object.create(variables);
return newContext;
}
withInLoop(): Context {
const newContext = Object.create(this);
newContext.inLoop = true;
return newContext;
}
withCaller(node: Element): Context {
const newContext = Object.create(this);
newContext.caller = node;
return newContext;
}
withEscaping(): Context {
const newContext = Object.create(this);
newContext.escaping = true;
return newContext;
}
indent() {
this.indentLevel++;
}
dedent() {
this.indentLevel--;
}
addLine(line: string) {
const prefix = new Array(this.indentLevel + 2).join(" ");
this.code.push(prefix + line);
}
addIf(condition: string) {
this.addLine(`if (${condition}) {`);
this.indent();
}
addElse() {
this.dedent();
this.addLine("} else {");
this.indent();
}
closeIf() {
this.dedent();
this.addLine("}");
}
getValue(val: any): any {
return val in this.variables ? this.getValue(this.variables[val]) : val;
}
}
//------------------------------------------------------------------------------
// QWeb rendering engine
//------------------------------------------------------------------------------
export class QWeb {
processedTemplates: { [name: string]: ProcessedTemplate } = {};
templates: { [name: string]: CompiledTemplate<VNode> } = {};
exprCache: { [key: string]: string } = {};
directives: Directive[] = [];
constructor() {
[
forEachDirective,
escDirective,
rawDirective,
setDirective,
elseDirective,
elifDirective,
ifDirective,
callDirective,
onDirective,
refDirective,
widgetDirective
].forEach(d => this.addDirective(d));
}
utils = {
h: h,
getFragment(str: string): DocumentFragment {
const temp = document.createElement("template");
temp.innerHTML = str;
return temp.content;
}
};
addDirective(dir: Directive) {
this.directives.push(dir);
this.directives.sort((d1, d2) => d1.priority - d2.priority);
}
/**
* Add a template to the internal template map. Note that it is not
* immediately compiled.
*/
addTemplate(
name: string,
template: RawTemplate,
allowDuplicates: boolean = false
) {
if (name in this.processedTemplates) {
if (allowDuplicates) {
return;
} else {
throw new Error(`Template ${name} already defined`);
}
}
const parser = new DOMParser();
const doc = parser.parseFromString(template, "text/xml");
if (!doc.firstChild) {
throw new Error("Invalid template (should not be empty)");
}
if (doc.getElementsByTagName("parsererror").length) {
throw new Error("Invalid XML in template");
}
let elem = doc.firstChild as Element;
this._processTemplate(elem);
this.processedTemplates[name] = elem;
}
_processTemplate(elem: Element) {
let tbranch = elem.querySelectorAll("[t-elif], [t-else]");
for (let i = 0, ilen = tbranch.length; i < ilen; i++) {
let node = tbranch[i];
let prevElem = node.previousElementSibling!;
let pattr = function(name) {
return prevElem.getAttribute(name);
};
let nattr = function(name) {
return +!!node.getAttribute(name);
};
if (prevElem && (pattr("t-if") || pattr("t-elif"))) {
if (pattr("t-foreach")) {
throw new Error(
"t-if cannot stay at the same level as t-foreach when using t-elif or t-else"
);
}
if (
["t-if", "t-elif", "t-else"].map(nattr).reduce(function(a, b) {
return a + b;
}) > 1
) {
throw new Error(
"Only one conditional branching directive is allowed per node"
);
}
// All text nodes between branch nodes are removed
let textNode;
while ((textNode = node.previousSibling) !== prevElem) {
if (textNode.nodeValue.trim().length) {
throw new Error("text is not allowed between branching directives");
}
textNode.remove();
}
} else {
throw new Error(
"t-elif and t-else directives must be preceded by a t-if or t-elif directive"
);
}
}
}
/**
* Load templates from a xml (as a string). This will look up for the first
* <templates> tag, and will consider each child of this as a template, with
* the name given by the t-name attribute.
*/
loadTemplates(xmlstr: string) {
const parser = new DOMParser();
const doc = parser.parseFromString(xmlstr, "text/xml");
const templates = doc.getElementsByTagName("templates")[0];
if (!templates) {
return;
}
for (let elem of <any>templates.children) {
const name = elem.getAttribute("t-name");
this._processTemplate(elem);
this.processedTemplates[name] = elem;
}
}
/**
* Render a template
*
* @param {string} name the template should already have been added
*/
render(name: string, context: EvalContext = {}, extra: any = null): VNode {
if (!(name in this.processedTemplates)) {
throw new Error(`Template ${name} does not exist`);
}
const template = this.templates[name] || this._compile(name);
return template.call(this, context, extra);
}
_compile(name: string): CompiledTemplate<VNode> {
if (name in this.templates) {
return this.templates[name];
}
const mainNode = this.processedTemplates[name];
const isDebug = (<Element>mainNode).attributes.hasOwnProperty("t-debug");
const ctx = new Context();
this._compileNode(mainNode, ctx);
if (ctx.shouldProtectContext) {
ctx.code.unshift(" context = Object.create(context);");
}
if (ctx.shouldDefineOwner) {
// this is necessary to prevent some directives (t-forach for ex) to
// pollute the rendering context by adding some keys in it.
ctx.code.unshift(" let owner = context;");
}
if (!ctx.rootNode) {
throw new Error("A template should have one root node");
}
ctx.addLine(`return vn${ctx.rootNode};`);
if (isDebug) {
ctx.code.unshift(" debugger");
}
let template;
try {
template = new Function(
"context",
"extra",
ctx.code.join("\n")
) as CompiledTemplate<VNode>;
} catch (e) {
throw new Error(`Invalid template (or compiled code): ${e.message}`);
}
if (isDebug) {
console.log(
`Template: ${
this.processedTemplates[name].outerHTML
}\nCompiled code:\n` + template.toString()
);
}
this.templates[name] = template;
return template;
}
/**
* Generate code from an xml node
*
*/
_compileNode(node: ChildNode, ctx: Context) {
if (!(node instanceof Element)) {
// this is a text node, there are no directive to apply
let text = node.textContent!;
if (ctx.parentNode) {
ctx.addLine(`c${ctx.parentNode}.push({text: \`${text}\`});`);
} else {
// this is an unusual situation: this text node is the result of the
// template rendering.
let nodeID = ctx.generateID();
ctx.addLine(`let vn${nodeID} = {text: \`${text}\`};`);
ctx.rootContext.rootNode = nodeID;
ctx.rootContext.parentNode = nodeID;
}
return;
}
const attributes = (<Element>node).attributes;
const validDirectives: {
directive: Directive;
value: string;
fullName: string;
}[] = [];
let withHandlers = false;
for (let directive of this.directives) {
// const value = attributes[i].textContent!;
let fullName;
let value;
for (let i = 0; i < attributes.length; i++) {
const name = attributes[i].name;
if (
name === "t-" + directive.name ||
name.startsWith("t-" + directive.name + "-")
) {
fullName = name;
value = attributes[i].textContent;
validDirectives.push({ directive, value, fullName });
if (directive.name === "on") {
withHandlers = true;
}
}
}
}
for (let { directive, value, fullName } of validDirectives) {
if (directive.atNodeEncounter) {
const isDone = directive.atNodeEncounter({
node,
qweb: this,
ctx,
fullName,
value
});
if (isDone) {
return;
}
}
}
if (node.nodeName !== "t") {
let nodeID = this._compileGenericNode(node, ctx, withHandlers);
ctx = ctx.withParent(nodeID);
for (let { directive, value, fullName } of validDirectives) {
if (directive.atNodeCreation) {
directive.atNodeCreation({
node,
qweb: this,
ctx,
fullName,
value,
nodeID
});
}
}
}
this._compileChildren(node, ctx);
for (let { directive, value, fullName } of validDirectives) {
if (directive.finalize) {
directive.finalize({ node, qweb: this, ctx, fullName, value });
}
}
}
_compileGenericNode(
node: ChildNode,
ctx: Context,
withHandlers: boolean = true
): number {
// nodeType 1 is generic tag
if (node.nodeType !== 1) {
throw new Error("unsupported node type");
}
const attributes = (<Element>node).attributes;
const attrs: string[] = [];
const tattrs: number[] = [];
for (let i = 0; i < attributes.length; i++) {
let name = attributes[i].name;
const value = attributes[i].textContent!;
// regular attributes
if (!name.startsWith("t-")) {
const attID = ctx.generateID();
ctx.addLine(`let _${attID} = '${value}';`);
if (!name.match(/^[a-zA-Z]+$/)) {
// attribute contains 'non letters' => we want to quote it
name = '"' + name + '"';
}
attrs.push(`${name}: _${attID}`);
}
// dynamic attributes
if (name.startsWith("t-att-")) {
let attName = name.slice(6);
let formattedValue = this._formatExpression(ctx.getValue(value!));
const attID = ctx.generateID();
if (!attName.match(/^[a-zA-Z]+$/)) {
// attribute contains 'non letters' => we want to quote it
attName = '"' + attName + '"';
}
// we need to combine dynamic with non dynamic attributes:
// class="a" t-att-class="'yop'" should be rendered as class="a yop"
const attValue = (<Element>node).getAttribute(attName);
if (attValue) {
const attValueID = ctx.generateID();
ctx.addLine(`let _${attValueID} = ${formattedValue};`);
formattedValue = `'${attValue}' + (_${attValueID} ? ' ' + _${attValueID} : '')`;
}
ctx.addLine(`let _${attID} = ${formattedValue};`);
attrs.push(`${attName}: _${attID}`);
}
if (name.startsWith("t-attf-")) {
let attName = name.slice(7);
if (!attName.match(/^[a-zA-Z]+$/)) {
// attribute contains 'non letters' => we want to quote it
attName = '"' + attName + '"';
}
const formattedExpr = value!.replace(
/\{\{.*?\}\}/g,
s => "${" + this._formatExpression(s.slice(2, -2)) + "}"
);
const attID = ctx.generateID();
ctx.addLine(`let _${attID} = \`${formattedExpr}\`;`);
attrs.push(`${attName}: _${attID}`);
}
// t-att= attributes
if (name === "t-att") {
let id = ctx.generateID();
ctx.addLine(`let _${id} = ${this._formatExpression(value!)};`);
tattrs.push(id);
}
}
let nodeID = ctx.generateID();
const parts = [`key:${nodeID}`];
if (attrs.length + tattrs.length > 0) {
parts.push(`attrs:{${attrs.join(",")}}`);
}
if (withHandlers) {
parts.push(`on:{}`);
}
ctx.addLine(`let c${nodeID} = [], p${nodeID} = {${parts.join(",")}};`);
for (let id of tattrs) {
ctx.addIf(`_${id} instanceof Array`);
ctx.addLine(`p${nodeID}.attrs[_${id}[0]] = _${id}[1];`);
ctx.addElse();
ctx.addLine(`for (let key in _${id}) {`);
ctx.indent();
ctx.addLine(`p${nodeID}.attrs[key] = _${id}[key];`);
ctx.dedent();
ctx.addLine(`}`);
ctx.closeIf();
}
ctx.addLine(
`let vn${nodeID} = h('${node.nodeName}', p${nodeID}, c${nodeID});`
);
if (ctx.parentNode) {
ctx.addLine(`c${ctx.parentNode}.push(vn${nodeID});`);
}
return nodeID;
}
_compileChildren(node: ChildNode, ctx: Context) {
if (node.childNodes.length > 0) {
for (let child of Array.from(node.childNodes)) {
this._compileNode(child, ctx);
}
}
}
_formatExpression(e: string): string {
if (e in this.exprCache) {
return this.exprCache[e];
}
// Thanks CHM for this code...
const chars = e.split("");
let instring = "";
let invar = "";
let invarPos = 0;
let r = "";
chars.push(" ");
for (var i = 0, ilen = chars.length; i < ilen; i++) {
var c = chars[i];
if (instring.length) {
if (c === instring && chars[i - 1] !== "\\") {
instring = "";
}
} else if (c === '"' || c === "'") {
instring = c;
} else if (c.match(/[a-zA-Z_\$]/) && !invar.length) {
invar = c;
invarPos = i;
continue;
} else if (c.match(/\W/) && invar.length) {
// TODO: Should check for possible spaces before dot
if (chars[invarPos - 1] !== "." && RESERVED_WORDS.indexOf(invar) < 0) {
invar = WORD_REPLACEMENT[invar] || "context['" + invar + "']";
}
r += invar;
invar = "";
} else if (invar.length) {
invar += c;
continue;
}
r += c;
}
const result = r.slice(0, -1);
this.exprCache[e] = result;
return result;
}
}
//------------------------------------------------------------------------------
// QWeb Directives
//------------------------------------------------------------------------------
interface CompilationInfo {
nodeID?: number;
node: Element;
qweb: QWeb;
ctx: Context;
fullName: string;
value: string;
}
export interface Directive {
name: string;
priority: number;
// if return true, then directive is fully applied and there is no need to
// keep processing node. Otherwise, we keep going.
atNodeEncounter?(info: CompilationInfo): boolean;
atNodeCreation?(info: CompilationInfo): void;
finalize?(info: CompilationInfo): void;
}
function compileValueNode(value: any, node: Element, qweb: QWeb, ctx: Context) {
if (value === "0" && ctx.caller) {
qweb._compileNode(ctx.caller, ctx);
return;
}
if (typeof value === "string") {
const exprID = ctx.generateID();
ctx.addLine(`let e${exprID} = ${qweb._formatExpression(value)};`);
ctx.addIf(`e${exprID} || e${exprID} === 0`);
let text = `e${exprID}`;
if (!ctx.parentNode) {
throw new Error("Should not have a text node without a parent");
}
if (ctx.escaping) {
ctx.addLine(`c${ctx.parentNode}.push({text: ${text}});`);
} else {
let fragID = ctx.generateID();
ctx.addLine(`let frag${fragID} = this.utils.getFragment(e${exprID})`);
let tempNodeID = ctx.generateID();
ctx.addLine(`let p${tempNodeID} = {hook: {`);
ctx.addLine(
` insert: n => n.elm.parentNode.replaceChild(frag${fragID}, n.elm),`
);
ctx.addLine(`}};`);
ctx.addLine(`let vn${tempNodeID} = h('div', p${tempNodeID})`);
ctx.addLine(`c${ctx.parentNode}.push(vn${tempNodeID});`);
}
if (node.childNodes.length) {
ctx.addElse();
qweb._compileChildren(node, ctx);
}
ctx.closeIf();
return;
}
if (value instanceof NodeList) {
for (let node of Array.from(value)) {
qweb._compileNode(<ChildNode>node, ctx);
}
}
}
const escDirective: Directive = {
name: "esc",
priority: 70,
atNodeEncounter({ node, qweb, ctx }): boolean {
if (node.nodeName !== "t") {
let nodeID = qweb._compileGenericNode(node, ctx);
ctx = ctx.withParent(nodeID);
}
let value = ctx.getValue(node.getAttribute("t-esc")!);
compileValueNode(value, node, qweb, ctx.withEscaping());
return true;
}
};
const rawDirective: Directive = {
name: "raw",
priority: 80,
atNodeEncounter({ node, qweb, ctx }): boolean {
if (node.nodeName !== "t") {
let nodeID = qweb._compileGenericNode(node, ctx);
ctx = ctx.withParent(nodeID);
}
let value = ctx.getValue(node.getAttribute("t-raw")!);
compileValueNode(value, node, qweb, ctx);
return true;
}
};
const setDirective: Directive = {
name: "set",
priority: 60,
atNodeEncounter({ node, ctx }): boolean {
const variable = node.getAttribute("t-set")!;
let value = node.getAttribute("t-value")!;
if (value) {
ctx.variables[variable] = value;
} else {
ctx.variables[variable] = node.childNodes;
}
return true;
}
};
const ifDirective: Directive = {
name: "if",
priority: 20,
atNodeEncounter({ node, qweb, ctx }): boolean {
let cond = ctx.getValue(node.getAttribute("t-if")!);
ctx.addIf(`${qweb._formatExpression(cond)}`);
return false;
},
finalize({ ctx }) {
ctx.closeIf();
}
};
const elifDirective: Directive = {
name: "elif",
priority: 30,
atNodeEncounter({ node, qweb, ctx }): boolean {
let cond = ctx.getValue(node.getAttribute("t-elif")!);
ctx.addLine(`else if (${qweb._formatExpression(cond)}) {`);
ctx.indent();
return false;
},
finalize({ ctx }) {
ctx.closeIf();
}
};
const elseDirective: Directive = {
name: "else",
priority: 40,
atNodeEncounter({ ctx }): boolean {
ctx.addLine(`else {`);
ctx.indent();
return false;
},
finalize({ ctx }) {
ctx.closeIf();
}
};
const callDirective: Directive = {
name: "call",
priority: 50,
atNodeEncounter({ node, qweb, ctx }): boolean {
if (node.nodeName !== "t") {
throw new Error("Invalid tag for t-call directive (should be 't')");
}
const subTemplate = node.getAttribute("t-call")!;
const nodeTemplate = qweb.processedTemplates[subTemplate];
if (!nodeTemplate) {
throw new Error(`Cannot find template "${subTemplate}" (t-call)`);
}
const nodeCopy = node.cloneNode(true) as Element;
nodeCopy.removeAttribute("t-call");
// extract variables from nodecopy
const tempCtx = new Context();
qweb._compileNode(nodeCopy, tempCtx);
const vars = Object.assign({}, ctx.variables, tempCtx.variables);
const subCtx = ctx.withCaller(nodeCopy).withVariables(vars);
qweb._compileNode(nodeTemplate, subCtx);
return true;
}
};
const forEachDirective: Directive = {
name: "foreach",
priority: 10,
atNodeEncounter({ node, qweb, ctx }): boolean {
ctx.rootContext.shouldProtectContext = true;
ctx = ctx.withInLoop();
const elems = node.getAttribute("t-foreach")!;
const name = node.getAttribute("t-as")!;
let arrayID = ctx.generateID();
ctx.addLine(`let _${arrayID} = ${qweb._formatExpression(elems)};`);
ctx.addLine(
`if (!_${arrayID}) { throw new Error('QWeb error: Invalid loop expression')}`
);
ctx.addLine(
`if (typeof _${arrayID} === 'number') { _${arrayID} = Array.from(Array(_${arrayID}).keys())}`
);
let keysID = ctx.generateID();
ctx.addLine(
`let _${keysID} = _${arrayID} instanceof Array ? _${arrayID} : Object.keys(_${arrayID});`
);
let valuesID = ctx.generateID();
ctx.addLine(
`let _${valuesID} = _${arrayID} instanceof Array ? _${arrayID} : Object.values(_${arrayID});`
);
ctx.addLine(`for (let i = 0; i < _${keysID}.length; i++) {`);
ctx.indent();
ctx.addLine(`context.${name}_first = i === 0;`);
ctx.addLine(`context.${name}_last = i === _${keysID}.length - 1;`);
ctx.addLine(`context.${name}_parity = i % 2 === 0 ? 'even' : 'odd';`);
ctx.addLine(`context.${name}_index = i;`);
ctx.addLine(`context.${name} = _${keysID}[i];`);
ctx.addLine(`context.${name}_value = _${valuesID}[i];`);
const nodeCopy = <Element>node.cloneNode(true);
nodeCopy.removeAttribute("t-foreach");
qweb._compileNode(nodeCopy, ctx);
ctx.dedent();
ctx.addLine("}");
return true;
}
};
const onDirective: Directive = {
name: "on",
priority: 90,
atNodeCreation({ ctx, fullName, value, nodeID, qweb }) {
ctx.rootContext.shouldDefineOwner = true;
const eventName = fullName.slice(5);
let extraArgs;
let handler = value.replace(/\(.*\)/, function(args) {
extraArgs = args.slice(1, -1);
return "";
});
if (extraArgs) {
ctx.addLine(
`p${nodeID}.on['${eventName}'] = context['${handler}'].bind(owner, ${qweb._formatExpression(
extraArgs
)});`
);
} else {
ctx.addLine(
`extra.handlers['${eventName}' + ${nodeID}] = extra.handlers['${eventName}' + ${nodeID}] || context['${handler}'].bind(owner);`
);
ctx.addLine(
`p${nodeID}.on['${eventName}'] = extra.handlers['${eventName}' + ${nodeID}];`
);
}
}
};
const refDirective: Directive = {
name: "ref",
priority: 95,
atNodeCreation({ ctx, node, nodeID }) {
let ref = node.getAttribute("t-ref");
ctx.addLine(`p${ctx.parentNode}.hook = {
create: (_, n) => context.refs['${ref}'] = n.elm,
};`);
}
};
const widgetDirective: Directive = {
name: "widget",
priority: 100,
atNodeEncounter({ ctx, value, node, qweb }): boolean {
ctx.addLine("//WIDGET");
ctx.rootContext.shouldDefineOwner = true;
let props = node.getAttribute("t-props");
let keepAlive = node.getAttribute("t-keep-alive") ? true : false;
// t-on- events...
const events: [string, string][] = [];
const attributes = (<Element>node).attributes;
for (let i = 0; i < attributes.length; i++) {
const name = attributes[i].name;
if (name.startsWith("t-on-")) {
events.push([name.slice(5), attributes[i].textContent!]);
}
}
let key = node.getAttribute("t-key");
if (key) {
key = `"${key}"`;
} else {
key = node.getAttribute("t-att-key");
if (key) {
key = qweb._formatExpression(key);
}
}
if (props) {
props = props.trim();
if (props[0] === "{" && props[props.length - 1] === "}") {
const innerProp = props
.slice(1, -1)
.split(",")
.map(p => {
let [key, val] = p.split(":");
return `${key}: ${qweb._formatExpression(val)}`;
})
.join(",");
props = "{" + innerProp + "}";
} else {
props = qweb._formatExpression(props);
}
}
let dummyID = ctx.generateID();
let defID = ctx.generateID();
let widgetID = ctx.generateID();
let keyID = key && ctx.generateID();
if (key) {
// we bind a variable to the key (could be a complex expression, so we
// want to evaluate it only once)
ctx.addLine(`let key${keyID} = ${key};`);
}
ctx.addLine(`let _${dummyID}_index = c${ctx.parentNode}.length;`);
ctx.addLine(`c${ctx.parentNode}.push(null);`);
ctx.addLine(`let def${defID};`);
let templateID = key
? `key${keyID}`
: ctx.inLoop
? `String(-${widgetID} - i)`
: String(widgetID);
ctx.addLine(
`let w${widgetID} = ${templateID} in context.__widget__.cmap ? context.__widget__.children[context.__widget__.cmap[${templateID}]] : false;`
);
ctx.addLine(`let props${widgetID} = ${props};`);
ctx.addLine(`let isNew${widgetID} = !w${widgetID};`);
// check if we can reuse current rendering promise
ctx.addIf(`w${widgetID} && w${widgetID}.__widget__.renderPromise`);
ctx.addIf(`w${widgetID}.__widget__.isStarted`);
ctx.addLine(`def${defID} = w${widgetID}.updateProps(props${widgetID});`);
ctx.addElse();
ctx.addLine(`isNew${widgetID} = true`);
ctx.addIf(`props${widgetID} === w${widgetID}.__widget__.renderProps`);
ctx.addLine(`def${defID} = w${widgetID}.__widget__.renderPromise;`);
ctx.addElse();
ctx.addLine(`w${widgetID}.destroy();`);
ctx.addLine(`w${widgetID} = false`);
ctx.closeIf();
ctx.closeIf();
ctx.closeIf();
ctx.addIf(`!def${defID}`);
ctx.addIf(`w${widgetID}`);
ctx.addLine(`def${defID} = w${widgetID}.updateProps(props${widgetID});`);
ctx.addElse();
ctx.addLine(
`w${widgetID} = new context.widgets['${value}'](owner, props${widgetID});`
);
ctx.addLine(
`context.__widget__.cmap[${templateID}] = w${widgetID}.__widget__.id;`
);
for (let [event, method] of events) {
ctx.addLine(`w${widgetID}.on('${event}', owner, owner['${method}'])`);
}
let ref = node.getAttribute("t-ref");
if (ref) {
ctx.addLine(`context.refs['${ref}'] = w${widgetID};`);
}
ctx.addLine(`def${defID} = w${widgetID}._start();`);
ctx.closeIf();
ctx.closeIf();
ctx.addIf(`isNew${widgetID}`);
ctx.addLine(
`def${defID} = def${defID}.then(vnode=>{let pvnode=h(vnode.sel, {key: ${templateID}});c${
ctx.parentNode
}[_${dummyID}_index]=pvnode;pvnode.data.hook = {insert(vn){let nvn=w${widgetID}._mount(vnode, vn.elm);pvnode.elm=nvn.elm},remove(){w${widgetID}.${
keepAlive ? "detach" : "destroy"
}()}}; w${widgetID}.__widget__.pvnode = pvnode;});`
);
ctx.addElse();
ctx.addLine(
`def${defID} = def${defID}.then(()=>{if (w${widgetID}.__widget__.isDestroyed) {return};let vnode;if (!w${widgetID}.__widget__.vnode){vnode=w${widgetID}.__widget__.pvnode} else { vnode=h(w${widgetID}.__widget__.vnode.sel, {key: ${templateID}});vnode.elm=w${widgetID}.el;vnode.data.hook = {insert(a){a.elm.parentNode.replaceChild(w${widgetID}.el,a.elm);a.elm=w${widgetID}.el;w${widgetID}.__mount();},remove(){w${widgetID}.${
keepAlive ? "detach" : "destroy"
}()}}}c${ctx.parentNode}[_${dummyID}_index]=vnode;});`
);
ctx.closeIf();
ctx.addLine(`extra.promises.push(def${defID});`);
if (node.getAttribute("t-if") || node.getAttribute("t-else")) {
ctx.closeIf();
}
return true;
}
};
+28
View File
@@ -0,0 +1,28 @@
/**
* The registry is basically a simple hashmap. It is only a little safer and
* more structured than a simple object.
*/
export class Registry<T> {
private map: { [key: string]: T } = {};
/**
* Add an element to the registry. Note that the add method returns the
* registry, to it can be chained.
*/
add(key: string, item: T): Registry<T> {
if (key in this.map) {
throw new Error(`Key ${key} already exists!`);
}
this.map[key] = item;
return this;
}
/**
* Returns the element corresponding to the key
*
* Nothing is done to check that the key actually exists.
*/
get(key: string): T | undefined {
return this.map[key];
}
}
+64
View File
@@ -0,0 +1,64 @@
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
# Vim
*.swp
# Generated JavaScript
/test/browserified.js
/browserified.js
/h.d.ts
/h.js
/h.js.map
/hooks.d.ts
/hooks.js
/hooks.js.map
/htmldomapi.d.ts
/htmldomapi.js
/htmldomapi.js.map
/is.d.ts
/is.js
/is.js.map
/snabbdom.bundle.d.ts
/snabbdom.bundle.js
/snabbdom.bundle.js.map
/snabbdom.d.ts
/snabbdom.js
/snabbdom.js.map
/thunk.d.ts
/thunk.js
/thunk.js.map
/tovnode.d.ts
/tovnode.js
/tovnode.js.map
/vnode.d.ts
/vnode.js
/vnode.js.map
/modules
/helpers
/es
+33
View File
@@ -0,0 +1,33 @@
/test
/perf
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
# Vim
*.swp
+17
View File
@@ -0,0 +1,17 @@
sudo: false
language: node_js
node_js:
- '6.10.1'
script:
- export IP_ADDR=$(ip addr | grep eth -A 4 | grep 'inet ' | awk '{ print $2 }' | sed 's/\/..//')
- npm test
addons:
browserstack:
username:
secure: <TODO>
access_key:
secure: <TODO>
env:
global:
- secure: <TODO>
- secure: <TODO>
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Simon Friis Vindum
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+758
View File
@@ -0,0 +1,758 @@
# Snabbdom
A virtual DOM library with focus on simplicity, modularity, powerful features
and performance.
[![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) [![npm version](https://badge.fury.io/js/snabbdom.svg)](https://badge.fury.io/js/snabbdom) [![npm downloads](https://img.shields.io/npm/dm/snabbdom.svg)](https://www.npmjs.com/package/snabbdom)
[![Join the chat at https://gitter.im/paldepind/snabbdom](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/paldepind/snabbdom?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Table of contents
* [Introduction](#introduction)
* [Features](#features)
* [Inline example](#inline-example)
* [Examples](#examples)
* [Core documentation](#core-documentation)
* [Modules documentation](#modules-documentation)
* [Helpers](#helpers)
* [Virtual Node documentation](#virtual-node)
* [Structuring applications](#structuring-applications)
## Why
Virtual DOM is awesome. It allows us to express our application's view
as a function of its state. But existing solutions were way way too
bloated, too slow, lacked features, had an API biased towards OOP
and/or lacked features I needed.
## Introduction
Snabbdom consists of an extremely simple, performant and extensible
core that is only ≈ 200 SLOC. It offers a modular architecture with
rich functionality for extensions through custom modules. To keep the
core simple, all non-essential functionality is delegated to modules.
You can mold Snabbdom into whatever you desire! Pick, choose and
customize the functionality you want. Alternatively you can just use
the default extensions and get a virtual DOM library with high
performance, small size and all the features listed below.
## Features
* Core features
* About 200 SLOC you could easily read through the entire core and fully
understand how it works.
* Extendable through modules.
* A rich set of hooks available, both per vnode and globally for modules,
to hook into any part of the diff and patch process.
* Splendid performance. Snabbdom is among the fastest virtual DOM libraries
in the [Virtual DOM Benchmark](http://vdom-benchmark.github.io/vdom-benchmark/).
* Patch function with a function signature equivalent to a reduce/scan
function. Allows for easier integration with a FRP library.
* Features in modules
* `h` function for easily creating virtual DOM nodes.
* [SVG _just works_ with the `h` helper](#svg).
* Features for doing complex CSS animations.
* Powerful event listener functionality.
* [Thunks](#thunks) to optimize the diff and patch process even further.
* Third party features
* JSX support thanks to [snabbdom-pragma](https://github.com/Swizz/snabbdom-pragma).
* Server-side HTML output provided by [snabbdom-to-html](https://github.com/acstll/snabbdom-to-html).
* Compact virtual DOM creation with [snabbdom-helpers](https://github.com/krainboltgreene/snabbdom-helpers).
* Template string support using [snabby](https://github.com/jamen/snabby).
* Virtual DOM assertion with [snabbdom-looks-like](https://github.com/jvanbruegge/snabbdom-looks-like)
## Inline example
```javascript
var snabbdom = require('snabbdom');
var patch = snabbdom.init([ // Init patch function with chosen modules
require('snabbdom/modules/class').default, // makes it easy to toggle classes
require('snabbdom/modules/props').default, // for setting properties on DOM elements
require('snabbdom/modules/style').default, // handles styling on elements with support for animations
require('snabbdom/modules/eventlisteners').default, // attaches event listeners
]);
var h = require('snabbdom/h').default; // helper function for creating vnodes
var container = document.getElementById('container');
var vnode = h('div#container.two.classes', {on: {click: someFn}}, [
h('span', {style: {fontWeight: 'bold'}}, 'This is bold'),
' and this is just normal text',
h('a', {props: {href: '/foo'}}, 'I\'ll take you places!')
]);
// Patch into empty DOM element this modifies the DOM as a side effect
patch(container, vnode);
var newVnode = h('div#container.two.classes', {on: {click: anotherEventHandler}}, [
h('span', {style: {fontWeight: 'normal', fontStyle: 'italic'}}, 'This is now italic type'),
' and this is still just normal text',
h('a', {props: {href: '/bar'}}, 'I\'ll take you places!')
]);
// Second `patch` invocation
patch(vnode, newVnode); // Snabbdom efficiently updates the old view to the new state
```
## Examples
* [Animated reordering of elements](http://snabbdom.github.io/snabbdom/examples/reorder-animation/)
* [Hero transitions](http://snabbdom.github.io/snabbdom/examples/hero/)
* [SVG Carousel](http://snabbdom.github.io/snabbdom/examples/carousel-svg/)
## Core documentation
The core of Snabbdom provides only the most essential functionality.
It is designed to be as simple as possible while still being fast and
extendable.
### `snabbdom.init`
The core exposes only one single function `snabbdom.init`. This `init`
takes a list of modules and returns a `patch` function that uses the
specified set of modules.
```javascript
var patch = snabbdom.init([
require('snabbdom/modules/class').default,
require('snabbdom/modules/style').default,
]);
```
### `patch`
The `patch` function returned by `init` takes two arguments. The first
is a DOM element or a vnode representing the current view. The second
is a vnode representing the new, updated view.
If a DOM element with a parent is passed, `newVnode` will be turned
into a DOM node, and the passed element will be replaced by the
created DOM node. If an old vnode is passed, Snabbdom will efficiently
modify it to match the description in the new vnode.
Any old vnode passed must be the resulting vnode from a previous call
to `patch`. This is necessary since Snabbdom stores information in the
vnode. This makes it possible to implement a simpler and more
performant architecture. This also avoids the creation of a new old
vnode tree.
```javascript
patch(oldVnode, newVnode);
```
### `snabbdom/h`
It is recommended that you use `snabbdom/h` to create vnodes. `h` accepts a
tag/selector as a string, an optional data object and an optional string or
array of children.
```javascript
var h = require('snabbdom/h').default;
var vnode = h('div', {style: {color: '#000'}}, [
h('h1', 'Headline'),
h('p', 'A paragraph'),
]);
```
### `snabbdom/tovnode`
Converts a DOM node into a virtual node. Especially good for patching over an pre-existing,
server-side generated content.
```javascript
var snabbdom = require('snabbdom')
var patch = snabbdom.init([ // Init patch function with chosen modules
require('snabbdom/modules/class').default, // makes it easy to toggle classes
require('snabbdom/modules/props').default, // for setting properties on DOM elements
require('snabbdom/modules/style').default, // handles styling on elements with support for animations
require('snabbdom/modules/eventlisteners').default, // attaches event listeners
]);
var h = require('snabbdom/h').default; // helper function for creating vnodes
var toVNode = require('snabbdom/tovnode').default;
var newVNode = h('div', {style: {color: '#000'}}, [
h('h1', 'Headline'),
h('p', 'A paragraph'),
]);
patch(toVNode(document.querySelector('.container')), newVNode)
```
### Hooks
Hooks are a way to hook into the lifecycle of DOM nodes. Snabbdom
offers a rich selection of hooks. Hooks are used both by modules to
extend Snabbdom, and in normal code for executing arbitrary code at
desired points in the life of a virtual node.
#### Overview
| Name | Triggered when | Arguments to callback |
| ----------- | -------------- | ----------------------- |
| `pre` | the patch process begins | none |
| `init` | a vnode has been added | `vnode` |
| `create` | a DOM element has been created based on a vnode | `emptyVnode, vnode` |
| `insert` | an element has been inserted into the DOM | `vnode` |
| `prepatch` | an element is about to be patched | `oldVnode, vnode` |
| `update` | an element is being updated | `oldVnode, vnode` |
| `postpatch` | an element has been patched | `oldVnode, vnode` |
| `destroy` | an element is directly or indirectly being removed | `vnode` |
| `remove` | an element is directly being removed from the DOM | `vnode, removeCallback` |
| `post` | the patch process is done | none |
The following hooks are available for modules: `pre`, `create`,
`update`, `destroy`, `remove`, `post`.
The following hooks are available in the `hook` property of individual
elements: `init`, `create`, `insert`, `prepatch`, `update`,
`postpatch`, `destroy`, `remove`.
#### Usage
To use hooks, pass them as an object to `hook` field of the data
object argument.
```javascript
h('div.row', {
key: movie.rank,
hook: {
insert: (vnode) => { movie.elmHeight = vnode.elm.offsetHeight; }
}
});
```
#### The `init` hook
This hook is invoked during the patch process when a new virtual node
has been found. The hook is called before Snabbdom has processed the
node in any way. I.e., before it has created a DOM node based on the
vnode.
#### The `insert` hook
This hook is invoked once the DOM element for a vnode has been
inserted into the document _and_ the rest of the patch cycle is done.
This means that you can do DOM measurements (like using
[getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect)
in this hook safely, knowing that no elements will be changed
afterwards that could affect the position of the inserted elements.
#### The `remove` hook
Allows you to hook into the removal of an element. The hook is called
once a vnode is to be removed from the DOM. The handling function
receives both the vnode and a callback. You can control and delay the
removal with the callback. The callback should be invoked once the
hook is done doing its business, and the element will only be removed
once all `remove` hooks have invoked their callback.
The hook is only triggered when an element is to be removed from its
parent not if it is the child of an element that is removed. For
that, see the `destroy` hook.
#### The `destroy` hook
This hook is invoked on a virtual node when its DOM element is removed
from the DOM or if its parent is being removed from the DOM.
To see the difference between this hook and the `remove` hook,
consider an example.
```js
var vnode1 = h('div', [h('div', [h('span', 'Hello')])]);
var vnode2 = h('div', []);
patch(container, vnode1);
patch(vnode1, vnode2);
```
Here `destroy` is triggered for both the inner `div` element _and_ the
`span` element it contains. `remove`, on the other hand, is only
triggered on the `div` element because it is the only element being
detached from its parent.
You can, for instance, use `remove` to trigger an animation when an
element is being removed and use the `destroy` hook to additionally
animate the disappearance of the removed element's children.
### Creating modules
Modules works by registering global listeners for [hooks](#hooks). A module is simply a dictionary mapping hook names to functions.
```javascript
var myModule = {
create: function(oldVnode, vnode) {
// invoked whenever a new virtual node is created
},
update: function(oldVnode, vnode) {
// invoked whenever a virtual node is updated
}
};
```
With this mechanism you can easily augment the behaviour of Snabbdom.
For demonstration, take a look at the implementations of the default
modules.
## Modules documentation
This describes the core modules. All modules are optional.
### The class module
The class module provides an easy way to dynamically toggle classes on
elements. It expects an object in the `class` data property. The
object should map class names to booleans that indicates whether or
not the class should stay or go on the vnode.
```javascript
h('a', {class: {active: true, selected: false}}, 'Toggle');
```
### The props module
Allows you to set properties on DOM elements.
```javascript
h('a', {props: {href: '/foo'}}, 'Go to Foo');
```
### The attributes module
Same as props, but set attributes instead of properties on DOM elements.
```javascript
h('a', {attrs: {href: '/foo'}}, 'Go to Foo');
```
Attributes are added and updated using `setAttribute`. In case of an
attribute that had been previously added/set and is no longer present
in the `attrs` object, it is removed from the DOM element's attribute
list using `removeAttribute`.
In the case of boolean attributes (e.g. `disabled`, `hidden`,
`selected` ...), the meaning doesn't depend on the attribute value
(`true` or `false`) but depends instead on the presence/absence of the
attribute itself in the DOM element. Those attributes are handled
differently by the module: if a boolean attribute is set to a
[falsy value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
(`0`, `-0`, `null`, `false`,`NaN`, `undefined`, or the empty string
(`""`)), then the attribute will be removed from the attribute list of
the DOM element.
### The dataset module
Allows you to set custom data attributes (`data-*`) on DOM elements. These can then be accessed with the [HTMLElement.dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) property.
```javascript
h('button', {dataset: {action: 'reset'}}, 'Reset');
```
### The style module
The style module is for making your HTML look slick and animate smoothly. At
its core it allows you to set CSS properties on elements.
```javascript
h('span', {
style: {border: '1px solid #bada55', color: '#c0ffee', fontWeight: 'bold'}
}, 'Say my name, and every colour illuminates');
```
Note that the style module does not remove style attributes if they
are removed as properties from the style object. To remove a style,
you should instead set it to the empty string.
```javascript
h('div', {
style: {position: shouldFollow ? 'fixed' : ''}
}, 'I, I follow, I follow you');
```
#### Custom properties (CSS variables)
CSS custom properties (aka CSS variables) are supported, they must be prefixed
with `--`
```javascript
h('div', {
style: {'--warnColor': 'yellow'}
}, 'Warning');
```
#### Delayed properties
You can specify properties as being delayed. Whenever these properties
change, the change is not applied until after the next frame.
```javascript
h('span', {
style: {opacity: '0', transition: 'opacity 1s', delayed: {opacity: '1'}}
}, 'Imma fade right in!');
```
This makes it easy to declaratively animate the entry of elements.
#### Set properties on `remove`
Styles set in the `remove` property will take effect once the element
is about to be removed from the DOM. The applied styles should be
animated with CSS transitions. Only once all the styles are done
animating will the element be removed from the DOM.
```javascript
h('span', {
style: {opacity: '1', transition: 'opacity 1s',
remove: {opacity: '0'}}
}, 'It\'s better to fade out than to burn away');
```
This makes it easy to declaratively animate the removal of elements.
#### Set properties on `destroy`
```javascript
h('span', {
style: {opacity: '1', transition: 'opacity 1s',
destroy: {opacity: '0'}}
}, 'It\'s better to fade out than to burn away');
```
### Eventlisteners module
The event listeners module gives powerful capabilities for attaching
event listeners.
You can attach a function to an event on a vnode by supplying an
object at `on` with a property corresponding to the name of the event
you want to listen to. The function will be called when the event
happens and will be passed the event object that belongs to it.
```javascript
function clickHandler(ev) { console.log('got clicked'); }
h('div', {on: {click: clickHandler}});
```
Very often, however, you're not really interested in the event object
itself. Often you have some data associated with the element that
triggers an event and you want that data passed along instead.
Consider a counter application with three buttons, one to increment
the counter by 1, one to increment the counter by 2 and one to
increment the counter by 3. You don't really care exactly which button
was pressed. Instead you're interested in what number was associated
with the clicked button. The event listeners module allows one to
express that by supplying an array at the named event property. The
first element in the array should be a function that will be invoked
with the value in the second element once the event occurs.
```javascript
function clickHandler(number) { console.log('button ' + number + ' was clicked!'); }
h('div', [
h('a', {on: {click: [clickHandler, 1]}}),
h('a', {on: {click: [clickHandler, 2]}}),
h('a', {on: {click: [clickHandler, 3]}}),
]);
```
Each handler is called not only with the given arguments but also with the current event and vnode appended to the argument list. It also supports using multiple listeners per event by specifying an array of handlers:
```javascript
stopPropagation = function(ev) { ev.stopPropagation() }
sendValue = function(func, ev, vnode) { func(vnode.elm.value) }
h('a', { on:{ click:[[sendValue, console.log], stopPropagation] } });
```
Snabbdom allows swapping event handlers between renders. This happens without
actually touching the event handlers attached to the DOM.
Note, however, that **you should be careful when sharing event
handlers between vnodes**, because of the technique this module uses
to avoid re-binding event handlers to the DOM. (And in general,
sharing data between vnodes is not guaranteed to work, because modules
are allowed to mutate the given data).
In particular, you should **not** do something like this:
```javascript
// Does not work
var sharedHandler = {
change: function(e){ console.log('you chose: ' + e.target.value); }
};
h('div', [
h('input', {props: {type: 'radio', name: 'test', value: '0'},
on: sharedHandler}),
h('input', {props: {type: 'radio', name: 'test', value: '1'},
on: sharedHandler}),
h('input', {props: {type: 'radio', name: 'test', value: '2'},
on: sharedHandler})
]);
```
For many such cases, you can use array-based handlers instead (described above).
Alternatively, simply make sure each node is passed unique `on` values:
```javascript
// Works
var sharedHandler = function(e){ console.log('you chose: ' + e.target.value); };
h('div', [
h('input', {props: {type: 'radio', name: 'test', value: '0'},
on: {change: sharedHandler}}),
h('input', {props: {type: 'radio', name: 'test', value: '1'},
on: {change: sharedHandler}}),
h('input', {props: {type: 'radio', name: 'test', value: '2'},
on: {change: sharedHandler}})
]);
```
## Helpers
### SVG
SVG just works when using the `h` function for creating virtual
nodes. SVG elements are automatically created with the appropriate
namespaces.
```javascript
var vnode = h('div', [
h('svg', {attrs: {width: 100, height: 100}}, [
h('circle', {attrs: {cx: 50, cy: 50, r: 40, stroke: 'green', 'stroke-width': 4, fill: 'yellow'}})
])
]);
```
See also the [SVG example](./examples/svg) and the [SVG Carousel example](./examples/carousel-svg/).
#### Using Classes in SVG Elements
Certain browsers (like IE <=11) [do not support `classList` property in SVG elements](http://caniuse.com/#feat=classlist).
Hence, the _class_ module (which uses `classList` property internally) will not work for these browsers.
The classes in selectors for SVG elements work fine from version 0.6.7.
You can add dynamic classes to SVG elements for these cases by using the _attributes_ module and an Array as shown below:
```js
h('svg', [
h('text.underline', { // 'underline' is a selector class, remain unchanged between renders.
attrs: {
// 'active' and 'red' are dynamic classes, they can change between renders
// so we need to put them in the class attribute.
// (Normally we'd use the classModule, but it doesn't work inside SVG)
class: [isActive && "active", isColored && "red"].filter(Boolean).join(" ")
}
},
'Hello World'
)
])
```
### Thunks
The `thunk` function takes a selector, a key for identifying a thunk,
a function that returns a vnode and a variable amount of state
parameters. If invoked, the render function will receive the state
arguments.
`thunk(selector, key, renderFn, [stateArguments])`
The `key` is optional. It should be supplied when the `selector` is
not unique among the thunks siblings. This ensures that the thunk is
always matched correctly when diffing.
Thunks are an optimization strategy that can be used when one is
dealing with immutable data.
Consider a simple function for creating a virtual node based on a number.
```js
function numberView(n) {
return h('div', 'Number is: ' + n);
}
```
The view depends only on `n`. This means that if `n` is unchanged,
then creating the virtual DOM node and patching it against the old
vnode is wasteful. To avoid the overhead we can use the `thunk` helper
function.
```js
function render(state) {
return thunk('num', numberView, [state.number]);
}
```
Instead of actually invoking the `numberView` function this will only
place a dummy vnode in the virtual tree. When Snabbdom patches this
dummy vnode against a previous vnode, it will compare the value of
`n`. If `n` is unchanged it will simply reuse the old vnode. This
avoids recreating the number view and the diff process altogether.
The view function here is only an example. In practice thunks are only
relevant if you are rendering a complicated view that takes
significant computational time to generate.
## Virtual Node
**Properties**
- [sel](#sel--string)
- [data](#data--object)
- [children](#children--array)
- [text](#text--string)
- [elm](#elm--element)
- [key](#key--string--number)
#### sel : String
The `.sel` property of a virtual node is the CSS selector passed to
[`h()`](#snabbdomh) during creation. For example: `h('div#container',
{}, [...])` will create a a virtual node which has `div#container` as
its `.sel` property.
#### data : Object
The `.data` property of a virtual node is the place to add information
for [modules](#modules-documentation) to access and manipulate the
real DOM element when it is created; Add styles, CSS classes,
attributes, etc.
The data object is the (optional) second parameter to [`h()`](#snabbdomh)
For example `h('div', {props: {className: 'container'}}, [...])` will produce a virtual node with
```js
{
"props": {
className: "container"
}
}
```
as its `.data` object.
#### children : Array<vnode>
The `.children` property of a virtual node is the third (optional)
parameter to [`h()`](#snabbdomh) during creation. `.children` is
simply an Array of virtual nodes that should be added as children of
the parent DOM node upon creation.
For example `h('div', {}, [ h('h1', {}, 'Hello, World') ])` will
create a virtual node with
```js
[
{
sel: 'h1',
data: {},
children: undefined,
text: 'Hello, World',
elm: Element,
key: undefined,
}
]
```
as its `.children` property.
#### text : string
The `.text` property is created when a virtual node is created with
only a single child that possesses text and only requires
`document.createTextNode()` to be used.
For example: `h('h1', {}, 'Hello')` will create a virtual node with
`Hello` as its `.text` property.
#### elm : Element
The `.elm` property of a virtual node is a pointer to the real DOM
node created by snabbdom. This property is very useful to do
calculations in [hooks](#hooks) as well as
[modules](#modules-documentation).
#### key : string | number
The `.key` property is created when a key is provided inside of your
[`.data`](#data--object) object. The `.key` property is used to keep
pointers to DOM nodes that existed previously to avoid recreating them
if it is unnecessary. This is very useful for things like list
reordering. A key must be either a string or a number to allow for
proper lookup as it is stored internally as a key/value pair inside of
an object, where `.key` is the key and the value is the
[`.elm`](#elm--element) property created.
For example: `h('div', {key: 1}, [])` will create a virtual node
object with a `.key` property with the value of `1`.
## Structuring applications
Snabbdom is a low-level virtual DOM library. It is unopinionated with
regards to how you should structure your application.
Here are some approaches to building applications with Snabbdom.
* [functional-frontend-architecture](https://github.com/paldepind/functional-frontend-architecture)
a repository containing several example applications that
demonstrates an architecture that uses Snabbdom.
* [Cycle.js](https://cycle.js.org/)
"A functional and reactive JavaScript framework for cleaner code"
uses Snabbdom
* [Vue.js](http://vuejs.org/) use a fork of snabbdom.
* [scheme-todomvc](https://github.com/amirouche/scheme-todomvc/) build
redux-like architecture on top of snabbdom bindings.
* [kaiju](https://github.com/AlexGalays/kaiju) -
Stateful components and observables on top of snabbdom
* [Tweed](https://tweedjs.github.io)
An Object Oriented approach to reactive interfaces.
* [Cyclow](http://cyclow.js.org) -
"A reactive frontend framework for JavaScript"
uses Snabbdom
* [Tung](https://github.com/Reon90/tung)
A JavaScript library for rendering html. Tung helps to divide html and JavaScript development.
* [sprotty](https://github.com/theia-ide/sprotty) - "A web-based diagramming framework" uses Snabbdom.
* [Mark Text](https://github.com/marktext/marktext) - "Realtime preview Markdown Editor" build on Snabbdom.
* [puddles](https://github.com/flintinatux/puddles) -
"Tiny vdom app framework. Pure Redux. No boilerplate." - Built with :heart: on Snabbdom.
* [Backbone.VDOMView](https://github.com/jcbrand/backbone.vdomview) - A [Backbone](http://backbonejs.org/) View with VirtualDOM capability via Snabbdom.
Be sure to share it if you're building an application in another way
using Snabbdom.
## Common errors
```
Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node':
The node before which the new node is to be inserted is not a child of this node.
```
The reason for this error is reusing of vnodes between patches (see code example), snabbdom stores actual dom nodes inside the virtual dom nodes passed to it as performance improvement, so reusing nodes between patches is not supported.
```js
var sharedNode = h('div', {}, 'Selected');
var vnode1 = h('div', [
h('div', {}, ['One']),
h('div', {}, ['Two']),
h('div', {}, [sharedNode]),
]);
var vnode2 = h('div', [
h('div', {}, ['One']),
h('div', {}, [sharedNode]),
h('div', {}, ['Three']),
]);
patch(container, vnode1);
patch(vnode1, vnode2);
```
You can fix this issue by creating a shallow copy of the object (here with object spread syntax):
```js
var vnode2 = h('div', [
h('div', {}, ['One']),
h('div', {}, [{ ...sharedNode }]),
h('div', {}, ['Three']),
]);
```
Another solution would be to wrap shared vnodes in a factory function:
```js
var sharedNode = () => h('div', {}, 'Selected');
var vnode1 = h('div', [
h('div', {}, ['One']),
h('div', {}, ['Two']),
h('div', {}, [sharedNode()]),
]);
```
+95
View File
@@ -0,0 +1,95 @@
module.exports = {
// Latest mainstream
BS_Chrome_Current: {
base: 'BrowserStack',
browser: 'chrome',
browser_version: 'latest',
os: 'Windows',
os_version: '10',
},
BS_Firefox_Current: {
base: 'BrowserStack',
browser: 'firefox',
browser_version: 'latest',
os: 'Windows',
os_version: '10',
},
BS_Safari_Current: {
base: 'BrowserStack',
browser: 'safari',
browser_version: 'latest',
os: 'OS X',
os_version: 'High Sierra',
},
BS_Android_8: {
base: 'BrowserStack',
browser: 'Android',
device: 'Google Pixel 2',
os: 'Android',
os_version: '8.0',
real_mobile: true,
},
// Older mainstream
BS_Chrome_49: {
base: 'BrowserStack',
browser: 'chrome',
browser_version: '49',
os: 'Windows',
os_version: '10',
},
BS_Firefox_52: {
base: 'BrowserStack',
browser: 'firefox',
browser_version: '52',
os: 'Windows',
os_version: '10',
},
BS_Safari_9: {
base: 'BrowserStack',
browser: 'safari',
browser_version: '9.1',
os: 'OS X',
os_version: 'El Capitan',
},
// Misc
BS_Android_4_4: {
base: 'BrowserStack',
device_browser: 'ucbrowser',
device: 'Google Nexus 5',
os: 'Android',
os_version: '4.4',
real_mobile: true,
},
BS_iphone_10: {
base: 'BrowserStack',
browser: 'Mobile Safari',
browser_version: null,
device: 'iPhone 7',
real_mobile: true,
os: 'ios',
os_version: '10.3',
},
BS_MS_Edge: {
base: 'BrowserStack',
browser: 'edge',
browser_version: 'latest',
os: 'Windows',
os_version: '10',
},
BS_IE_11: {
base: 'BrowserStack',
browser: 'ie',
browser_version: '11.0',
os: 'Windows',
os_version: '7',
},
BS_IE_10: {
base: 'BrowserStack',
browser: 'ie',
browser_version: '10.0',
os: 'Windows',
os_version: '7',
},
};
Vendored Executable
+83
View File
@@ -0,0 +1,83 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.h = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var vnode_1 = require("./vnode");
var is = require("./is");
function addNS(data, children, sel) {
data.ns = 'http://www.w3.org/2000/svg';
if (sel !== 'foreignObject' && children !== undefined) {
for (var i = 0; i < children.length; ++i) {
var childData = children[i].data;
if (childData !== undefined) {
addNS(childData, children[i].children, children[i].sel);
}
}
}
}
function h(sel, b, c) {
var data = {}, children, text, i;
if (c !== undefined) {
data = b;
if (is.array(c)) {
children = c;
}
else if (is.primitive(c)) {
text = c;
}
else if (c && c.sel) {
children = [c];
}
}
else if (b !== undefined) {
if (is.array(b)) {
children = b;
}
else if (is.primitive(b)) {
text = b;
}
else if (b && b.sel) {
children = [b];
}
else {
data = b;
}
}
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
if (is.primitive(children[i]))
children[i] = vnode_1.vnode(undefined, undefined, undefined, children[i]);
}
}
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g' &&
(sel.length === 3 || sel[3] === '.' || sel[3] === '#')) {
addNS(data, children, sel);
}
return vnode_1.vnode(sel, data, children, text, undefined);
}
exports.h = h;
;
exports.default = h;
},{"./is":2,"./vnode":3}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.array = Array.isArray;
function primitive(s) {
return typeof s === 'string' || typeof s === 'number';
}
exports.primitive = primitive;
},{}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function vnode(sel, data, children, text, elm) {
var key = data === undefined ? undefined : data.key;
return { sel: sel, data: data, children: children,
text: text, elm: elm, key: key };
}
exports.vnode = vnode;
exports.default = vnode;
},{}]},{},[1])(1)
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy8ucmVnaXN0cnkubnBtanMub3JnL2Jyb3dzZXItcGFjay82LjAuMi9ub2RlX21vZHVsZXMvYnJvd3Nlci1wYWNrL19wcmVsdWRlLmpzIiwiaC5qcyIsImlzLmpzIiwidm5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUNBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQzFEQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQ1BBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24gZSh0LG4scil7ZnVuY3Rpb24gcyhvLHUpe2lmKCFuW29dKXtpZighdFtvXSl7dmFyIGE9dHlwZW9mIHJlcXVpcmU9PVwiZnVuY3Rpb25cIiYmcmVxdWlyZTtpZighdSYmYSlyZXR1cm4gYShvLCEwKTtpZihpKXJldHVybiBpKG8sITApO3ZhciBmPW5ldyBFcnJvcihcIkNhbm5vdCBmaW5kIG1vZHVsZSAnXCIrbytcIidcIik7dGhyb3cgZi5jb2RlPVwiTU9EVUxFX05PVF9GT1VORFwiLGZ9dmFyIGw9bltvXT17ZXhwb3J0czp7fX07dFtvXVswXS5jYWxsKGwuZXhwb3J0cyxmdW5jdGlvbihlKXt2YXIgbj10W29dWzFdW2VdO3JldHVybiBzKG4/bjplKX0sbCxsLmV4cG9ydHMsZSx0LG4scil9cmV0dXJuIG5bb10uZXhwb3J0c312YXIgaT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2Zvcih2YXIgbz0wO288ci5sZW5ndGg7bysrKXMocltvXSk7cmV0dXJuIHN9KSIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xudmFyIHZub2RlXzEgPSByZXF1aXJlKFwiLi92bm9kZVwiKTtcbnZhciBpcyA9IHJlcXVpcmUoXCIuL2lzXCIpO1xuZnVuY3Rpb24gYWRkTlMoZGF0YSwgY2hpbGRyZW4sIHNlbCkge1xuICAgIGRhdGEubnMgPSAnaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnO1xuICAgIGlmIChzZWwgIT09ICdmb3JlaWduT2JqZWN0JyAmJiBjaGlsZHJlbiAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIGZvciAodmFyIGkgPSAwOyBpIDwgY2hpbGRyZW4ubGVuZ3RoOyArK2kpIHtcbiAgICAgICAgICAgIHZhciBjaGlsZERhdGEgPSBjaGlsZHJlbltpXS5kYXRhO1xuICAgICAgICAgICAgaWYgKGNoaWxkRGF0YSAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgYWRkTlMoY2hpbGREYXRhLCBjaGlsZHJlbltpXS5jaGlsZHJlbiwgY2hpbGRyZW5baV0uc2VsKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbn1cbmZ1bmN0aW9uIGgoc2VsLCBiLCBjKSB7XG4gICAgdmFyIGRhdGEgPSB7fSwgY2hpbGRyZW4sIHRleHQsIGk7XG4gICAgaWYgKGMgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICBkYXRhID0gYjtcbiAgICAgICAgaWYgKGlzLmFycmF5KGMpKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IGM7XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoaXMucHJpbWl0aXZlKGMpKSB7XG4gICAgICAgICAgICB0ZXh0ID0gYztcbiAgICAgICAgfVxuICAgICAgICBlbHNlIGlmIChjICYmIGMuc2VsKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IFtjXTtcbiAgICAgICAgfVxuICAgIH1cbiAgICBlbHNlIGlmIChiICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKGlzLmFycmF5KGIpKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IGI7XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoaXMucHJpbWl0aXZlKGIpKSB7XG4gICAgICAgICAgICB0ZXh0ID0gYjtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIGlmIChiICYmIGIuc2VsKSB7XG4gICAgICAgICAgICBjaGlsZHJlbiA9IFtiXTtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgIGRhdGEgPSBiO1xuICAgICAgICB9XG4gICAgfVxuICAgIGlmIChpcy5hcnJheShjaGlsZHJlbikpIHtcbiAgICAgICAgZm9yIChpID0gMDsgaSA8IGNoaWxkcmVuLmxlbmd0aDsgKytpKSB7XG4gICAgICAgICAgICBpZiAoaXMucHJpbWl0aXZlKGNoaWxkcmVuW2ldKSlcbiAgICAgICAgICAgICAgICBjaGlsZHJlbltpXSA9IHZub2RlXzEudm5vZGUodW5kZWZpbmVkLCB1bmRlZmluZWQsIHVuZGVmaW5lZCwgY2hpbGRyZW5baV0pO1xuICAgICAgICB9XG4gICAgfVxuICAgIGlmIChzZWxbMF0gPT09ICdzJyAmJiBzZWxbMV0gPT09ICd2JyAmJiBzZWxbMl0gPT09ICdnJyAmJlxuICAgICAgICAoc2VsLmxlbmd0aCA9PT0gMyB8fCBzZWxbM10gPT09ICcuJyB8fCBzZWxbM10gPT09ICcjJykpIHtcbiAgICAgICAgYWRkTlMoZGF0YSwgY2hpbGRyZW4sIHNlbCk7XG4gICAgfVxuICAgIHJldHVybiB2bm9kZV8xLnZub2RlKHNlbCwgZGF0YSwgY2hpbGRyZW4sIHRleHQsIHVuZGVmaW5lZCk7XG59XG5leHBvcnRzLmggPSBoO1xuO1xuZXhwb3J0cy5kZWZhdWx0ID0gaDtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPWguanMubWFwIiwiXCJ1c2Ugc3RyaWN0XCI7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoZXhwb3J0cywgXCJfX2VzTW9kdWxlXCIsIHsgdmFsdWU6IHRydWUgfSk7XG5leHBvcnRzLmFycmF5ID0gQXJyYXkuaXNBcnJheTtcbmZ1bmN0aW9uIHByaW1pdGl2ZShzKSB7XG4gICAgcmV0dXJuIHR5cGVvZiBzID09PSAnc3RyaW5nJyB8fCB0eXBlb2YgcyA9PT0gJ251bWJlcic7XG59XG5leHBvcnRzLnByaW1pdGl2ZSA9IHByaW1pdGl2ZTtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPWlzLmpzLm1hcCIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xuZnVuY3Rpb24gdm5vZGUoc2VsLCBkYXRhLCBjaGlsZHJlbiwgdGV4dCwgZWxtKSB7XG4gICAgdmFyIGtleSA9IGRhdGEgPT09IHVuZGVmaW5lZCA/IHVuZGVmaW5lZCA6IGRhdGEua2V5O1xuICAgIHJldHVybiB7IHNlbDogc2VsLCBkYXRhOiBkYXRhLCBjaGlsZHJlbjogY2hpbGRyZW4sXG4gICAgICAgIHRleHQ6IHRleHQsIGVsbTogZWxtLCBrZXk6IGtleSB9O1xufVxuZXhwb3J0cy52bm9kZSA9IHZub2RlO1xuZXhwb3J0cy5kZWZhdWx0ID0gdm5vZGU7XG4vLyMgc291cmNlTWFwcGluZ1VSTD12bm9kZS5qcy5tYXAiXX0=
Vendored Executable
+2
View File
@@ -0,0 +1,2 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.h=e()}}(function(){return function e(r,n,i){function t(f,u){if(!n[f]){if(!r[f]){var d="function"==typeof require&&require;if(!u&&d)return d(f,!0);if(o)return o(f,!0);var a=new Error("Cannot find module '"+f+"'");throw a.code="MODULE_NOT_FOUND",a}var v=n[f]={exports:{}};r[f][0].call(v.exports,function(e){var n=r[f][1][e];return t(n?n:e)},v,v.exports,e,r,n,i)}return n[f].exports}for(var o="function"==typeof require&&require,f=0;f<i.length;f++)t(i[f]);return t}({1:[function(e,r,n){"use strict";function i(e,r,n){if(e.ns="http://www.w3.org/2000/svg","foreignObject"!==n&&void 0!==r)for(var t=0;t<r.length;++t){var o=r[t].data;void 0!==o&&i(o,r[t].children,r[t].sel)}}function t(e,r,n){var t,u,d,a={};if(void 0!==n?(a=r,f.array(n)?t=n:f.primitive(n)?u=n:n&&n.sel&&(t=[n])):void 0!==r&&(f.array(r)?t=r:f.primitive(r)?u=r:r&&r.sel?t=[r]:a=r),f.array(t))for(d=0;d<t.length;++d)f.primitive(t[d])&&(t[d]=o.vnode(void 0,void 0,void 0,t[d]));return"s"!==e[0]||"v"!==e[1]||"g"!==e[2]||3!==e.length&&"."!==e[3]&&"#"!==e[3]||i(a,t,e),o.vnode(e,a,t,u,void 0)}var o=e("./vnode"),f=e("./is");n.h=t,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=t},{"./is":2,"./vnode":3}],2:[function(e,r,n){"use strict";function i(e){return"string"==typeof e||"number"==typeof e}n.array=Array.isArray,n.primitive=i},{}],3:[function(e,r,n){"use strict";function i(e,r,n,i,t){var o=void 0===r?void 0:r.key;return{sel:e,data:r,children:n,text:i,elm:t,key:o}}n.vnode=i,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=i},{}]},{},[1])(1)});
//# sourceMappingURL=h.min.js.map
+1
View File
File diff suppressed because one or more lines are too long
+71
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.snabbdom_attributes=e()}}(function(){return function e(t,r,n){function o(a,u){if(!r[a]){if(!t[a]){var d="function"==typeof require&&require;if(!u&&d)return d(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var f=r[a]={exports:{}};t[a][0].call(f.exports,function(e){var r=t[a][1][e];return o(r?r:e)},f,f.exports,e,t,r,n)}return r[a].exports}for(var i="function"==typeof require&&require,a=0;a<n.length;a++)o(n[a]);return o}({1:[function(e,t,r){"use strict";function n(e,t){var r,n,i,u,d=t.elm,l=e.data.attrs,f=t.data.attrs;if((l||f)&&l!==f){l=l||{},f=f||{};for(r in f)n=f[r],i=l[r],i!==n&&(!n&&a[r]?d.removeAttribute(r):(u=r.split(":"),u.length>1&&o.hasOwnProperty(u[0])?d.setAttributeNS(o[u[0]],r,n):d.setAttribute(r,n)));for(r in l)r in f||d.removeAttribute(r)}}for(var o={xlink:"http://www.w3.org/1999/xlink"},i=["allowfullscreen","async","autofocus","autoplay","checked","compact","controls","declare","default","defaultchecked","defaultmuted","defaultselected","defer","disabled","draggable","enabled","formnovalidate","hidden","indeterminate","inert","ismap","itemscope","loop","multiple","muted","nohref","noresize","noshade","novalidate","nowrap","open","pauseonexit","readonly","required","reversed","scoped","seamless","selected","sortable","spellcheck","translate","truespeed","typemustmatch","visible"],a=Object.create(null),u=0,d=i.length;u<d;u++)a[i[u]]=!0;r.attributesModule={create:n,update:n},Object.defineProperty(r,"__esModule",{value:!0}),r["default"]=r.attributesModule},{}]},{},[1])(1)});
//# sourceMappingURL=snabbdom-attributes.min.js.map
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snabbdom_class = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function updateClass(oldVnode, vnode) {
var cur, name, elm = vnode.elm, oldClass = oldVnode.data.class, klass = vnode.data.class;
if (!oldClass && !klass)
return;
if (oldClass === klass)
return;
oldClass = oldClass || {};
klass = klass || {};
for (name in oldClass) {
if (!klass[name]) {
elm.classList.remove(name);
}
}
for (name in klass) {
cur = klass[name];
if (cur !== oldClass[name]) {
elm.classList[cur ? 'add' : 'remove'](name);
}
}
}
exports.classModule = { create: updateClass, update: updateClass };
exports.default = exports.classModule;
},{}]},{},[1])(1)
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy8ucmVnaXN0cnkubnBtanMub3JnL2Jyb3dzZXItcGFjay82LjAuMi9ub2RlX21vZHVsZXMvYnJvd3Nlci1wYWNrL19wcmVsdWRlLmpzIiwibW9kdWxlcy9jbGFzcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQ0FBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24gZSh0LG4scil7ZnVuY3Rpb24gcyhvLHUpe2lmKCFuW29dKXtpZighdFtvXSl7dmFyIGE9dHlwZW9mIHJlcXVpcmU9PVwiZnVuY3Rpb25cIiYmcmVxdWlyZTtpZighdSYmYSlyZXR1cm4gYShvLCEwKTtpZihpKXJldHVybiBpKG8sITApO3ZhciBmPW5ldyBFcnJvcihcIkNhbm5vdCBmaW5kIG1vZHVsZSAnXCIrbytcIidcIik7dGhyb3cgZi5jb2RlPVwiTU9EVUxFX05PVF9GT1VORFwiLGZ9dmFyIGw9bltvXT17ZXhwb3J0czp7fX07dFtvXVswXS5jYWxsKGwuZXhwb3J0cyxmdW5jdGlvbihlKXt2YXIgbj10W29dWzFdW2VdO3JldHVybiBzKG4/bjplKX0sbCxsLmV4cG9ydHMsZSx0LG4scil9cmV0dXJuIG5bb10uZXhwb3J0c312YXIgaT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2Zvcih2YXIgbz0wO288ci5sZW5ndGg7bysrKXMocltvXSk7cmV0dXJuIHN9KSIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xuZnVuY3Rpb24gdXBkYXRlQ2xhc3Mob2xkVm5vZGUsIHZub2RlKSB7XG4gICAgdmFyIGN1ciwgbmFtZSwgZWxtID0gdm5vZGUuZWxtLCBvbGRDbGFzcyA9IG9sZFZub2RlLmRhdGEuY2xhc3MsIGtsYXNzID0gdm5vZGUuZGF0YS5jbGFzcztcbiAgICBpZiAoIW9sZENsYXNzICYmICFrbGFzcylcbiAgICAgICAgcmV0dXJuO1xuICAgIGlmIChvbGRDbGFzcyA9PT0ga2xhc3MpXG4gICAgICAgIHJldHVybjtcbiAgICBvbGRDbGFzcyA9IG9sZENsYXNzIHx8IHt9O1xuICAgIGtsYXNzID0ga2xhc3MgfHwge307XG4gICAgZm9yIChuYW1lIGluIG9sZENsYXNzKSB7XG4gICAgICAgIGlmICgha2xhc3NbbmFtZV0pIHtcbiAgICAgICAgICAgIGVsbS5jbGFzc0xpc3QucmVtb3ZlKG5hbWUpO1xuICAgICAgICB9XG4gICAgfVxuICAgIGZvciAobmFtZSBpbiBrbGFzcykge1xuICAgICAgICBjdXIgPSBrbGFzc1tuYW1lXTtcbiAgICAgICAgaWYgKGN1ciAhPT0gb2xkQ2xhc3NbbmFtZV0pIHtcbiAgICAgICAgICAgIGVsbS5jbGFzc0xpc3RbY3VyID8gJ2FkZCcgOiAncmVtb3ZlJ10obmFtZSk7XG4gICAgICAgIH1cbiAgICB9XG59XG5leHBvcnRzLmNsYXNzTW9kdWxlID0geyBjcmVhdGU6IHVwZGF0ZUNsYXNzLCB1cGRhdGU6IHVwZGF0ZUNsYXNzIH07XG5leHBvcnRzLmRlZmF1bHQgPSBleHBvcnRzLmNsYXNzTW9kdWxlO1xuLy8jIHNvdXJjZU1hcHBpbmdVUkw9Y2xhc3MuanMubWFwIl19
+2
View File
@@ -0,0 +1,2 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.snabbdom_class=e()}}(function(){return function e(n,o,r){function t(i,u){if(!o[i]){if(!n[i]){var s="function"==typeof require&&require;if(!u&&s)return s(i,!0);if(f)return f(i,!0);var d=new Error("Cannot find module '"+i+"'");throw d.code="MODULE_NOT_FOUND",d}var a=o[i]={exports:{}};n[i][0].call(a.exports,function(e){var o=n[i][1][e];return t(o?o:e)},a,a.exports,e,n,o,r)}return o[i].exports}for(var f="function"==typeof require&&require,i=0;i<r.length;i++)t(r[i]);return t}({1:[function(e,n,o){"use strict";function r(e,n){var o,r,t=n.elm,f=e.data["class"],i=n.data["class"];if((f||i)&&f!==i){f=f||{},i=i||{};for(r in f)i[r]||t.classList.remove(r);for(r in i)o=i[r],o!==f[r]&&t.classList[o?"add":"remove"](r)}}o.classModule={create:r,update:r},Object.defineProperty(o,"__esModule",{value:!0}),o["default"]=o.classModule},{}]},{},[1])(1)});
//# sourceMappingURL=snabbdom-class.min.js.map
+1
View File
File diff suppressed because one or more lines are too long
+42
View File
@@ -0,0 +1,42 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snabbdom_dataset = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CAPS_REGEX = /[A-Z]/g;
function updateDataset(oldVnode, vnode) {
var elm = vnode.elm, oldDataset = oldVnode.data.dataset, dataset = vnode.data.dataset, key;
if (!oldDataset && !dataset)
return;
if (oldDataset === dataset)
return;
oldDataset = oldDataset || {};
dataset = dataset || {};
var d = elm.dataset;
for (key in oldDataset) {
if (!dataset[key]) {
if (d) {
if (key in d) {
delete d[key];
}
}
else {
elm.removeAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase());
}
}
}
for (key in dataset) {
if (oldDataset[key] !== dataset[key]) {
if (d) {
d[key] = dataset[key];
}
else {
elm.setAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase(), dataset[key]);
}
}
}
}
exports.datasetModule = { create: updateDataset, update: updateDataset };
exports.default = exports.datasetModule;
},{}]},{},[1])(1)
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJtb2R1bGVzL2RhdGFzZXQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUNBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24gZSh0LG4scil7ZnVuY3Rpb24gcyhvLHUpe2lmKCFuW29dKXtpZighdFtvXSl7dmFyIGE9dHlwZW9mIHJlcXVpcmU9PVwiZnVuY3Rpb25cIiYmcmVxdWlyZTtpZighdSYmYSlyZXR1cm4gYShvLCEwKTtpZihpKXJldHVybiBpKG8sITApO3ZhciBmPW5ldyBFcnJvcihcIkNhbm5vdCBmaW5kIG1vZHVsZSAnXCIrbytcIidcIik7dGhyb3cgZi5jb2RlPVwiTU9EVUxFX05PVF9GT1VORFwiLGZ9dmFyIGw9bltvXT17ZXhwb3J0czp7fX07dFtvXVswXS5jYWxsKGwuZXhwb3J0cyxmdW5jdGlvbihlKXt2YXIgbj10W29dWzFdW2VdO3JldHVybiBzKG4/bjplKX0sbCxsLmV4cG9ydHMsZSx0LG4scil9cmV0dXJuIG5bb10uZXhwb3J0c312YXIgaT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2Zvcih2YXIgbz0wO288ci5sZW5ndGg7bysrKXMocltvXSk7cmV0dXJuIHN9KSIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KGV4cG9ydHMsIFwiX19lc01vZHVsZVwiLCB7IHZhbHVlOiB0cnVlIH0pO1xudmFyIENBUFNfUkVHRVggPSAvW0EtWl0vZztcbmZ1bmN0aW9uIHVwZGF0ZURhdGFzZXQob2xkVm5vZGUsIHZub2RlKSB7XG4gICAgdmFyIGVsbSA9IHZub2RlLmVsbSwgb2xkRGF0YXNldCA9IG9sZFZub2RlLmRhdGEuZGF0YXNldCwgZGF0YXNldCA9IHZub2RlLmRhdGEuZGF0YXNldCwga2V5O1xuICAgIGlmICghb2xkRGF0YXNldCAmJiAhZGF0YXNldClcbiAgICAgICAgcmV0dXJuO1xuICAgIGlmIChvbGREYXRhc2V0ID09PSBkYXRhc2V0KVxuICAgICAgICByZXR1cm47XG4gICAgb2xkRGF0YXNldCA9IG9sZERhdGFzZXQgfHwge307XG4gICAgZGF0YXNldCA9IGRhdGFzZXQgfHwge307XG4gICAgdmFyIGQgPSBlbG0uZGF0YXNldDtcbiAgICBmb3IgKGtleSBpbiBvbGREYXRhc2V0KSB7XG4gICAgICAgIGlmICghZGF0YXNldFtrZXldKSB7XG4gICAgICAgICAgICBpZiAoZCkge1xuICAgICAgICAgICAgICAgIGlmIChrZXkgaW4gZCkge1xuICAgICAgICAgICAgICAgICAgICBkZWxldGUgZFtrZXldO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgIGVsbS5yZW1vdmVBdHRyaWJ1dGUoJ2RhdGEtJyArIGtleS5yZXBsYWNlKENBUFNfUkVHRVgsICctJCYnKS50b0xvd2VyQ2FzZSgpKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbiAgICBmb3IgKGtleSBpbiBkYXRhc2V0KSB7XG4gICAgICAgIGlmIChvbGREYXRhc2V0W2tleV0gIT09IGRhdGFzZXRba2V5XSkge1xuICAgICAgICAgICAgaWYgKGQpIHtcbiAgICAgICAgICAgICAgICBkW2tleV0gPSBkYXRhc2V0W2tleV07XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICBlbG0uc2V0QXR0cmlidXRlKCdkYXRhLScgKyBrZXkucmVwbGFjZShDQVBTX1JFR0VYLCAnLSQmJykudG9Mb3dlckNhc2UoKSwgZGF0YXNldFtrZXldKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbn1cbmV4cG9ydHMuZGF0YXNldE1vZHVsZSA9IHsgY3JlYXRlOiB1cGRhdGVEYXRhc2V0LCB1cGRhdGU6IHVwZGF0ZURhdGFzZXQgfTtcbmV4cG9ydHMuZGVmYXVsdCA9IGV4cG9ydHMuZGF0YXNldE1vZHVsZTtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPWRhdGFzZXQuanMubWFwIl19
+99
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.snabbdom_eventlisteners=e()}}(function(){return function e(n,t,r){function o(f,u){if(!t[f]){if(!n[f]){var l="function"==typeof require&&require;if(!u&&l)return l(f,!0);if(i)return i(f,!0);var s=new Error("Cannot find module '"+f+"'");throw s.code="MODULE_NOT_FOUND",s}var d=t[f]={exports:{}};n[f][0].call(d.exports,function(e){var t=n[f][1][e];return o(t?t:e)},d,d.exports,e,n,t,r)}return t[f].exports}for(var i="function"==typeof require&&require,f=0;f<r.length;f++)o(r[f]);return o}({1:[function(e,n,t){"use strict";function r(e,n,t){if("function"==typeof e)e.call(n,t,n);else if("object"==typeof e)if("function"==typeof e[0])if(2===e.length)e[0].call(n,e[1],t,n);else{var o=e.slice(1);o.push(t),o.push(n),e[0].apply(n,o)}else for(var i=0;i<e.length;i++)r(e[i])}function o(e,n){var t=e.type,o=n.data.on;o&&o[t]&&r(o[t],n,e)}function i(){return function e(n){o(n,e.vnode)}}function f(e,n){var t,r=e.data.on,o=e.listener,f=e.elm,u=n&&n.data.on,l=n&&n.elm;if(r!==u){if(r&&o)if(u)for(t in r)u[t]||f.removeEventListener(t,o,!1);else for(t in r)f.removeEventListener(t,o,!1);if(u){var s=n.listener=e.listener||i();if(s.vnode=n,r)for(t in u)r[t]||l.addEventListener(t,s,!1);else for(t in u)l.addEventListener(t,s,!1)}}}t.eventListenersModule={create:f,update:f,destroy:f},Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=t.eventListenersModule},{}]},{},[1])(1)});
//# sourceMappingURL=snabbdom-eventlisteners.min.js.map
File diff suppressed because one or more lines are too long
+830
View File
File diff suppressed because one or more lines are too long
+2
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
+30
View File
@@ -0,0 +1,30 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snabbdom_props = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function updateProps(oldVnode, vnode) {
var key, cur, old, elm = vnode.elm, oldProps = oldVnode.data.props, props = vnode.data.props;
if (!oldProps && !props)
return;
if (oldProps === props)
return;
oldProps = oldProps || {};
props = props || {};
for (key in oldProps) {
if (!props[key]) {
delete elm[key];
}
}
for (key in props) {
cur = props[key];
old = oldProps[key];
if (old !== cur && (key !== 'value' || elm[key] !== cur)) {
elm[key] = cur;
}
}
}
exports.propsModule = { create: updateProps, update: updateProps };
exports.default = exports.propsModule;
},{}]},{},[1])(1)
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy8ucmVnaXN0cnkubnBtanMub3JnL2Jyb3dzZXItcGFjay82LjAuMi9ub2RlX21vZHVsZXMvYnJvd3Nlci1wYWNrL19wcmVsdWRlLmpzIiwibW9kdWxlcy9wcm9wcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQ0FBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbIihmdW5jdGlvbiBlKHQsbixyKXtmdW5jdGlvbiBzKG8sdSl7aWYoIW5bb10pe2lmKCF0W29dKXt2YXIgYT10eXBlb2YgcmVxdWlyZT09XCJmdW5jdGlvblwiJiZyZXF1aXJlO2lmKCF1JiZhKXJldHVybiBhKG8sITApO2lmKGkpcmV0dXJuIGkobywhMCk7dmFyIGY9bmV3IEVycm9yKFwiQ2Fubm90IGZpbmQgbW9kdWxlICdcIitvK1wiJ1wiKTt0aHJvdyBmLmNvZGU9XCJNT0RVTEVfTk9UX0ZPVU5EXCIsZn12YXIgbD1uW29dPXtleHBvcnRzOnt9fTt0W29dWzBdLmNhbGwobC5leHBvcnRzLGZ1bmN0aW9uKGUpe3ZhciBuPXRbb11bMV1bZV07cmV0dXJuIHMobj9uOmUpfSxsLGwuZXhwb3J0cyxlLHQsbixyKX1yZXR1cm4gbltvXS5leHBvcnRzfXZhciBpPXR5cGVvZiByZXF1aXJlPT1cImZ1bmN0aW9uXCImJnJlcXVpcmU7Zm9yKHZhciBvPTA7bzxyLmxlbmd0aDtvKyspcyhyW29dKTtyZXR1cm4gc30pIiwiXCJ1c2Ugc3RyaWN0XCI7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoZXhwb3J0cywgXCJfX2VzTW9kdWxlXCIsIHsgdmFsdWU6IHRydWUgfSk7XG5mdW5jdGlvbiB1cGRhdGVQcm9wcyhvbGRWbm9kZSwgdm5vZGUpIHtcbiAgICB2YXIga2V5LCBjdXIsIG9sZCwgZWxtID0gdm5vZGUuZWxtLCBvbGRQcm9wcyA9IG9sZFZub2RlLmRhdGEucHJvcHMsIHByb3BzID0gdm5vZGUuZGF0YS5wcm9wcztcbiAgICBpZiAoIW9sZFByb3BzICYmICFwcm9wcylcbiAgICAgICAgcmV0dXJuO1xuICAgIGlmIChvbGRQcm9wcyA9PT0gcHJvcHMpXG4gICAgICAgIHJldHVybjtcbiAgICBvbGRQcm9wcyA9IG9sZFByb3BzIHx8IHt9O1xuICAgIHByb3BzID0gcHJvcHMgfHwge307XG4gICAgZm9yIChrZXkgaW4gb2xkUHJvcHMpIHtcbiAgICAgICAgaWYgKCFwcm9wc1trZXldKSB7XG4gICAgICAgICAgICBkZWxldGUgZWxtW2tleV07XG4gICAgICAgIH1cbiAgICB9XG4gICAgZm9yIChrZXkgaW4gcHJvcHMpIHtcbiAgICAgICAgY3VyID0gcHJvcHNba2V5XTtcbiAgICAgICAgb2xkID0gb2xkUHJvcHNba2V5XTtcbiAgICAgICAgaWYgKG9sZCAhPT0gY3VyICYmIChrZXkgIT09ICd2YWx1ZScgfHwgZWxtW2tleV0gIT09IGN1cikpIHtcbiAgICAgICAgICAgIGVsbVtrZXldID0gY3VyO1xuICAgICAgICB9XG4gICAgfVxufVxuZXhwb3J0cy5wcm9wc01vZHVsZSA9IHsgY3JlYXRlOiB1cGRhdGVQcm9wcywgdXBkYXRlOiB1cGRhdGVQcm9wcyB9O1xuZXhwb3J0cy5kZWZhdWx0ID0gZXhwb3J0cy5wcm9wc01vZHVsZTtcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPXByb3BzLmpzLm1hcCJdfQ==
+2
View File
@@ -0,0 +1,2 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;o="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,o.snabbdom_props=e()}}(function(){return function e(o,r,n){function t(i,u){if(!r[i]){if(!o[i]){var d="function"==typeof require&&require;if(!u&&d)return d(i,!0);if(f)return f(i,!0);var p=new Error("Cannot find module '"+i+"'");throw p.code="MODULE_NOT_FOUND",p}var a=r[i]={exports:{}};o[i][0].call(a.exports,function(e){var r=o[i][1][e];return t(r?r:e)},a,a.exports,e,o,r,n)}return r[i].exports}for(var f="function"==typeof require&&require,i=0;i<n.length;i++)t(n[i]);return t}({1:[function(e,o,r){"use strict";function n(e,o){var r,n,t,f=o.elm,i=e.data.props,u=o.data.props;if((i||u)&&i!==u){i=i||{},u=u||{};for(r in i)u[r]||delete f[r];for(r in u)n=u[r],t=i[r],t===n||"value"===r&&f[r]===n||(f[r]=n)}}r.propsModule={create:n,update:n},Object.defineProperty(r,"__esModule",{value:!0}),r["default"]=r.propsModule},{}]},{},[1])(1)});
//# sourceMappingURL=snabbdom-props.min.js.map
+1
View File
File diff suppressed because one or more lines are too long
+90
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.snabbdom_style=e()}}(function(){return function e(t,n,r){function o(f,d){if(!n[f]){if(!t[f]){var u="function"==typeof require&&require;if(!d&&u)return u(f,!0);if(i)return i(f,!0);var l=new Error("Cannot find module '"+f+"'");throw l.code="MODULE_NOT_FOUND",l}var a=n[f]={exports:{}};t[f][0].call(a.exports,function(e){var n=t[f][1][e];return o(n?n:e)},a,a.exports,e,t,n,r)}return n[f].exports}for(var i="function"==typeof require&&require,f=0;f<r.length;f++)o(r[f]);return o}({1:[function(e,t,n){"use strict";function r(e,t,n){u(function(){e[t]=n})}function o(e,t){var n,o,i=t.elm,f=e.data.style,d=t.data.style;if((f||d)&&f!==d){f=f||{},d=d||{};var u="delayed"in f;for(o in f)d[o]||("-"===o[0]&&"-"===o[1]?i.style.removeProperty(o):i.style[o]="");for(o in d)if(n=d[o],"delayed"===o)for(o in d.delayed)n=d.delayed[o],u&&n===f.delayed[o]||r(i.style,o,n);else"remove"!==o&&n!==f[o]&&("-"===o[0]&&"-"===o[1]?i.style.setProperty(o,n):i.style[o]=n)}}function i(e){var t,n,r=e.elm,o=e.data.style;if(o&&(t=o.destroy))for(n in t)r.style[n]=t[n]}function f(e,t){var n=e.data.style;if(!n||!n.remove)return void t();var r,o,i=e.elm,f=0,d=n.remove,u=0,l=[];for(r in d)l.push(r),i.style[r]=d[r];o=getComputedStyle(i);for(var a=o["transition-property"].split(", ");f<a.length;++f)l.indexOf(a[f])!==-1&&u++;i.addEventListener("transitionend",function(e){e.target===i&&--u,0===u&&t()})}var d="undefined"!=typeof window&&window.requestAnimationFrame||setTimeout,u=function(e){d(function(){d(e)})};n.styleModule={create:o,update:o,destroy:i,remove:f},Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=n.styleModule},{}]},{},[1])(1)});
//# sourceMappingURL=snabbdom-style.min.js.map
+1
View File
File diff suppressed because one or more lines are too long
+506
View File
File diff suppressed because one or more lines are too long
+2
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
Vendored Executable
+126
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.tovnode=e()}}(function(){return function e(t,n,o){function r(u,d){if(!n[u]){if(!t[u]){var f="function"==typeof require&&require;if(!d&&f)return f(u,!0);if(i)return i(u,!0);var a=new Error("Cannot find module '"+u+"'");throw a.code="MODULE_NOT_FOUND",a}var l=n[u]={exports:{}};t[u][0].call(l.exports,function(e){var n=t[u][1][e];return r(n?n:e)},l,l.exports,e,t,n,o)}return n[u].exports}for(var i="function"==typeof require&&require,u=0;u<o.length;u++)r(o[u]);return r}({1:[function(e,t,n){"use strict";function o(e){return document.createElement(e)}function r(e,t){return document.createElementNS(e,t)}function i(e){return document.createTextNode(e)}function u(e){return document.createComment(e)}function d(e,t,n){e.insertBefore(t,n)}function f(e,t){e.removeChild(t)}function a(e,t){e.appendChild(t)}function l(e){return e.parentNode}function c(e){return e.nextSibling}function s(e){return e.tagName}function m(e,t){e.textContent=t}function v(e){return e.textContent}function p(e){return 1===e.nodeType}function x(e){return 3===e.nodeType}function h(e){return 8===e.nodeType}n.htmlDomApi={createElement:o,createElementNS:r,createTextNode:i,createComment:u,insertBefore:d,removeChild:f,appendChild:a,parentNode:l,nextSibling:c,tagName:s,setTextContent:m,getTextContent:v,isElement:p,isText:x,isComment:h},Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=n.htmlDomApi},{}],2:[function(e,t,n){"use strict";function o(e,t){var n,u=void 0!==t?t:i["default"];if(u.isElement(e)){var d,f=e.id?"#"+e.id:"",a=e.getAttribute("class"),l=a?"."+a.split(" ").join("."):"",c=u.tagName(e).toLowerCase()+f+l,s={},m=[],v=void 0,p=void 0,x=e.attributes,h=e.childNodes;for(v=0,p=x.length;v<p;v++)d=x[v].nodeName,"id"!==d&&"class"!==d&&(s[d]=x[v].nodeValue);for(v=0,p=h.length;v<p;v++)m.push(o(h[v]));return r["default"](c,{attrs:s},m,void 0,e)}return u.isText(e)?(n=u.getTextContent(e),r["default"](void 0,void 0,void 0,n,e)):u.isComment(e)?(n=u.getTextContent(e),r["default"]("!",void 0,void 0,n,void 0)):r["default"]("",{},[],void 0,void 0)}var r=e("./vnode"),i=e("./htmldomapi");n.toVNode=o,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=o},{"./htmldomapi":1,"./vnode":3}],3:[function(e,t,n){"use strict";function o(e,t,n,o,r){var i=void 0===t?void 0:t.key;return{sel:e,data:t,children:n,text:o,elm:r,key:i}}n.vnode=o,Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=o},{}]},{},[2])(2)});
//# sourceMappingURL=tovnode.min.js.map
+1
View File
File diff suppressed because one or more lines are too long
+19
View File
@@ -0,0 +1,19 @@
This carousel example uses `style transform` and `transition` to rotate a group of SVG triangles.
Also, the color of each triangle changes when you hover or click/tap it.
I built the build.js using npm and browserify.
In my local copy of the snabbdom project root I did these preparations:
```
npm install --save-dev babelify
npm install --save-dev babel-preset-es2015
echo '{ "presets": ["es2015"] }' > .babelrc
```
I then built like this:
```
browserify examples/carousel-svg/script.js -t babelify -o examples/carousel-svg/build.js
```
-- *jk*
+566
View File
@@ -0,0 +1,566 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var VNode = require('./vnode');
var is = require('./is');
function addNS(data, children) {
data.ns = 'http://www.w3.org/2000/svg';
if (children !== undefined) {
for (var i = 0; i < children.length; ++i) {
addNS(children[i].data, children[i].children);
}
}
}
module.exports = function h(sel, b, c) {
var data = {},
children,
text,
i;
if (arguments.length === 3) {
data = b;
if (is.array(c)) {
children = c;
} else if (is.primitive(c)) {
text = c;
}
} else if (arguments.length === 2) {
if (is.array(b)) {
children = b;
} else if (is.primitive(b)) {
text = b;
} else {
data = b;
}
}
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
}
}
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') {
addNS(data, children);
}
return VNode(sel, data, children, text, undefined);
};
},{"./is":2,"./vnode":7}],2:[function(require,module,exports){
'use strict';
module.exports = {
array: Array.isArray,
primitive: function primitive(s) {
return typeof s === 'string' || typeof s === 'number';
}
};
},{}],3:[function(require,module,exports){
"use strict";
var booleanAttrs = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "compact", "controls", "declare", "default", "defaultchecked", "defaultmuted", "defaultselected", "defer", "disabled", "draggable", "enabled", "formnovalidate", "hidden", "indeterminate", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "pauseonexit", "readonly", "required", "reversed", "scoped", "seamless", "selected", "sortable", "spellcheck", "translate", "truespeed", "typemustmatch", "visible"];
var booleanAttrsDict = {};
for (var i = 0, len = booleanAttrs.length; i < len; i++) {
booleanAttrsDict[booleanAttrs[i]] = true;
}
function updateAttrs(oldVnode, vnode) {
var key,
cur,
old,
elm = vnode.elm,
oldAttrs = oldVnode.data.attrs || {},
attrs = vnode.data.attrs || {};
// update modified attributes, add new attributes
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
// TODO: add support to namespaced attributes (setAttributeNS)
if (!cur && booleanAttrsDict[key]) elm.removeAttribute(key);else elm.setAttribute(key, cur);
}
}
//remove removed attributes
// use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value)
// the other option is to remove all attributes with value == undefined
for (key in oldAttrs) {
if (!(key in attrs)) {
elm.removeAttribute(key);
}
}
}
module.exports = { create: updateAttrs, update: updateAttrs };
},{}],4:[function(require,module,exports){
'use strict';
var is = require('../is');
function arrInvoker(arr) {
return function () {
// Special case when length is two, for performance
arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1));
};
}
function fnInvoker(o) {
return function (ev) {
o.fn(ev);
};
}
function updateEventListeners(oldVnode, vnode) {
var name,
cur,
old,
elm = vnode.elm,
oldOn = oldVnode.data.on || {},
on = vnode.data.on;
if (!on) return;
for (name in on) {
cur = on[name];
old = oldOn[name];
if (old === undefined) {
if (is.array(cur)) {
elm.addEventListener(name, arrInvoker(cur));
} else {
cur = { fn: cur };
on[name] = cur;
elm.addEventListener(name, fnInvoker(cur));
}
} else if (is.array(old)) {
// Deliberately modify old array since it's captured in closure created with `arrInvoker`
old.length = cur.length;
for (var i = 0; i < old.length; ++i) {
old[i] = cur[i];
}on[name] = old;
} else {
old.fn = cur;
on[name] = old;
}
}
}
module.exports = { create: updateEventListeners, update: updateEventListeners };
},{"../is":2}],5:[function(require,module,exports){
'use strict';
var raf = window && window.requestAnimationFrame || setTimeout;
var nextFrame = function nextFrame(fn) {
raf(function () {
raf(fn);
});
};
function setNextFrame(obj, prop, val) {
nextFrame(function () {
obj[prop] = val;
});
}
function updateStyle(oldVnode, vnode) {
var cur,
name,
elm = vnode.elm,
oldStyle = oldVnode.data.style || {},
style = vnode.data.style || {},
oldHasDel = 'delayed' in oldStyle;
for (name in oldStyle) {
if (!style[name]) {
elm.style[name] = '';
}
}
for (name in style) {
cur = style[name];
if (name === 'delayed') {
for (name in style.delayed) {
cur = style.delayed[name];
if (!oldHasDel || cur !== oldStyle.delayed[name]) {
setNextFrame(elm.style, name, cur);
}
}
} else if (name !== 'remove' && cur !== oldStyle[name]) {
elm.style[name] = cur;
}
}
}
function applyDestroyStyle(vnode) {
var style,
name,
elm = vnode.elm,
s = vnode.data.style;
if (!s || !(style = s.destroy)) return;
for (name in style) {
elm.style[name] = style[name];
}
}
function applyRemoveStyle(vnode, rm) {
var s = vnode.data.style;
if (!s || !s.remove) {
rm();
return;
}
var name,
elm = vnode.elm,
idx,
i = 0,
maxDur = 0,
compStyle,
style = s.remove,
amount = 0,
applied = [];
for (name in style) {
applied.push(name);
elm.style[name] = style[name];
}
compStyle = getComputedStyle(elm);
var props = compStyle['transition-property'].split(', ');
for (; i < props.length; ++i) {
if (applied.indexOf(props[i]) !== -1) amount++;
}
elm.addEventListener('transitionend', function (ev) {
if (ev.target === elm) --amount;
if (amount === 0) rm();
});
}
module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle };
},{}],6:[function(require,module,exports){
// jshint newcap: false
/* global require, module, document, Element */
'use strict';
var VNode = require('./vnode');
var is = require('./is');
function isUndef(s) {
return s === undefined;
}
function isDef(s) {
return s !== undefined;
}
function emptyNodeAt(elm) {
return VNode(elm.tagName, {}, [], undefined, elm);
}
var emptyNode = VNode('', {}, [], undefined, undefined);
function sameVnode(vnode1, vnode2) {
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
}
function createKeyToOldIdx(children, beginIdx, endIdx) {
var i,
map = {},
key;
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) map[key] = i;
}
return map;
}
function createRmCb(childElm, listeners) {
return function () {
if (--listeners === 0) childElm.parentElement.removeChild(childElm);
};
}
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
function init(modules) {
var i,
j,
cbs = {};
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
function createElm(vnode, insertedVnodeQueue) {
var i,
data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode);
if (isDef(i = data.vnode)) vnode = i;
}
var elm,
children = vnode.children,
sel = vnode.sel;
if (isDef(sel)) {
// Parse selector
var hashIdx = sel.indexOf('#');
var dotIdx = sel.indexOf('.', hashIdx);
var hash = hashIdx > 0 ? hashIdx : sel.length;
var dot = dotIdx > 0 ? dotIdx : sel.length;
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? document.createElementNS(i, tag) : document.createElement(tag);
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
elm.appendChild(createElm(children[i], insertedVnodeQueue));
}
} else if (is.primitive(vnode.text)) {
elm.appendChild(document.createTextNode(vnode.text));
}
for (i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode);
}i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode);
if (i.insert) insertedVnodeQueue.push(vnode);
}
} else {
elm = vnode.elm = document.createTextNode(vnode.text);
}
return vnode.elm;
}
function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
parentElm.insertBefore(createElm(vnodes[startIdx], insertedVnodeQueue), before);
}
}
function invokeDestroyHook(vnode) {
var i = vnode.data,
j;
if (isDef(i)) {
if (isDef(i = i.hook) && isDef(i = i.destroy)) i(vnode);
for (i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](vnode);
}if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
}
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var i,
listeners,
rm,
ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.sel)) {
invokeDestroyHook(ch);
listeners = cbs.remove.length + 1;
rm = createRmCb(ch.elm, listeners);
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](ch, rm);
}if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) {
i(ch, rm);
} else {
rm();
}
} else {
// Text node
parentElm.removeChild(ch.elm);
}
}
}
}
function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) {
var oldStartIdx = 0,
newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, before;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) {
// Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) {
// Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
idxInOld = oldKeyToIdx[newStartVnode.key];
if (isUndef(idxInOld)) {
// New element
parentElm.insertBefore(createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode(oldVnode, vnode, insertedVnodeQueue) {
var i, hook;
if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode);
}
if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i;
if (isDef(i = vnode.data) && isDef(i = i.vnode)) vnode = i;
var elm = vnode.elm = oldVnode.elm,
oldCh = oldVnode.children,
ch = vnode.children;
if (oldVnode === vnode) return;
if (isDef(vnode.data)) {
for (i = 0; i < cbs.update.length; ++i) {
cbs.update[i](oldVnode, vnode);
}i = vnode.data.hook;
if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode);
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue);
} else if (isDef(ch)) {
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
}
} else if (oldVnode.text !== vnode.text) {
elm.textContent = vnode.text;
}
if (isDef(hook) && isDef(i = hook.postpatch)) {
i(oldVnode, vnode);
}
}
return function (oldVnode, vnode) {
var i;
var insertedVnodeQueue = [];
for (i = 0; i < cbs.pre.length; ++i) {
cbs.pre[i]();
}if (oldVnode instanceof Element) {
if (oldVnode.parentElement !== null) {
createElm(vnode, insertedVnodeQueue);
oldVnode.parentElement.replaceChild(vnode.elm, oldVnode);
} else {
oldVnode = emptyNodeAt(oldVnode);
patchVnode(oldVnode, vnode, insertedVnodeQueue);
}
} else {
patchVnode(oldVnode, vnode, insertedVnodeQueue);
}
for (i = 0; i < insertedVnodeQueue.length; ++i) {
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
}
for (i = 0; i < cbs.post.length; ++i) {
cbs.post[i]();
}return vnode;
};
}
module.exports = { init: init };
},{"./is":2,"./vnode":7}],7:[function(require,module,exports){
"use strict";
module.exports = function (sel, data, children, text, elm) {
var key = data === undefined ? undefined : data.key;
return { sel: sel, data: data, children: children,
text: text, elm: elm, key: key };
};
},{}],8:[function(require,module,exports){
'use strict';
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([require('../../modules/attributes'), require('../../modules/style'), require('../../modules/eventlisteners')]);
var h = require('../../h.js');
var vnode;
var data = {
degRotation: 0
};
function gRotation() {
//console.log("gRotation: %s", data.degRotation);
return "rotate(" + data.degRotation + "deg)";
}
function triangleClick(id) {
console.log("triangleClick: %s", id);
render();
}
function handleRotate(degs) {
data.degRotation += degs;
console.log("handleRotate: %s, %s", degs, data.degRotation);
render();
}
function handleReset(degs) {
data.degRotation = degs;
console.log("handleReset: %s", degs);
render();
}
function render() {
vnode = patch(vnode, view(data));
}
var hTriangle = function hTriangle(id, degRotation) {
return h("polygon#" + id, {
attrs: {
points: "-50,-88 0,-175 50,-88",
transform: "rotate(" + degRotation + ")",
"stroke-width": 3
},
on: { click: [triangleClick, id] }
});
};
var view = function view(data) {
return h("div.view", [h("h1", "Snabbdom SVG Carousel"), h("svg", { attrs: { width: 380, height: 380, viewBox: [-190, -190, 380, 380] } }, [h("g#carousel", { style: { "-webkit-transform": gRotation(), transform: gRotation() } }, [hTriangle("yellow", 0), hTriangle("green", 60), hTriangle("magenta", 120), hTriangle("red", 180), hTriangle("cyan", 240), hTriangle("blue", 300)])]), h("button", { on: { click: [handleRotate, 60] } }, "Rotate Clockwise"), h("button", { on: { click: [handleRotate, -60] } }, "Rotate Anticlockwise"), h("button", { on: { click: [handleReset, 0] } }, "Reset")]);
};
window.addEventListener("DOMContentLoaded", function () {
var container = document.getElementById("container");
vnode = patch(container, view(data));
render();
});
},{"../../h.js":1,"../../modules/attributes":3,"../../modules/eventlisteners":4,"../../modules/style":5,"../../snabbdom.js":6}]},{},[8]);
+74
View File
@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta charset="utf-8">
<title>Carousel</title>
<script type="text/javascript" src="build.js"></script>
<style type="text/css">
div.view {
margin: 10px;
}
h1 {
font-size: 24px;
color: #505000;
}
svg {
display: block;
margin-bottom: 10px;
border: 1px solid gray;
}
g#carousel {
-webkit-transition: -webkit-transform 1s ease;
transition: transform 1s ease;
}
polygon {
stroke: #808000;
transition: fill 0.5s linear;
}
polygon#yellow {
fill: rgba(255,255,0,0.4);
}
polygon#yellow:hover, polygon#yellow:active {
fill: yellow;
}
polygon#green {
fill: rgba(0,128,0,0.4);
}
polygon#green:hover, polygon#green:active {
fill: green;
}
polygon#magenta {
fill: rgba(255,0,255,0.4);
}
polygon#magenta:hover, polygon#magenta:active {
fill: magenta;
}
polygon#red {
fill: rgba(255,0,0,0.4);
}
polygon#red:hover, polygon#red:active {
fill: red;
}
polygon#cyan {
fill: rgba(0,255,255,0.4);
}
polygon#cyan:hover, polygon#cyan:active {
fill: cyan;
}
polygon#blue {
fill: rgba(0,0,255,0.4);
}
polygon#blue:hover, polygon#blue:active {
fill: blue;
}
button {
font-size: 15px;
margin: 0 0.7em 0.7em 0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
+74
View File
@@ -0,0 +1,74 @@
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([
require('../../modules/attributes').default,
require('../../modules/style').default,
require('../../modules/eventlisteners').default
]);
var h = require('../../h.js').default;
var vnode;
var data = {
degRotation: 0
};
function gRotation() {
//console.log("gRotation: %s", data.degRotation);
return "rotate(" + data.degRotation + "deg)";
}
function triangleClick(id) {
console.log("triangleClick: %s", id);
render();
}
function handleRotate(degs) {
data.degRotation += degs;
console.log("handleRotate: %s, %s", degs, data.degRotation);
render();
}
function handleReset(degs) {
data.degRotation = degs;
console.log("handleReset: %s", degs);
render();
}
function render() {
vnode = patch(vnode, view(data));
}
const hTriangle = (id, degRotation) =>
h("polygon#" + id, {
attrs: {
points: "-50,-88 0,-175 50,-88",
transform: "rotate(" + degRotation + ")",
"stroke-width": 3
},
on: {click: [triangleClick, id]}
});
const view = (data) =>
h("div.view", [
h("h1", "Snabbdom SVG Carousel"),
h("svg", {attrs: {width: 380, height: 380, viewBox: [-190, -190, 380, 380]}}, [
h("g#carousel",
{style: {"-webkit-transform": gRotation(), transform: gRotation()}}, [
hTriangle("yellow", 0),
hTriangle("green", 60),
hTriangle("magenta", 120),
hTriangle("red", 180),
hTriangle("cyan", 240),
hTriangle("blue", 300)
])
]),
h("button", {on: {click: [handleRotate, 60]}}, "Rotate Clockwise"),
h("button", {on: {click: [handleRotate, -60]}}, "Rotate Anticlockwise"),
h("button", {on: {click: [handleReset, 0]}}, "Reset")
]);
window.addEventListener("DOMContentLoaded", () => {
var container = document.getElementById("container");
vnode = patch(container, view(data));
render();
});
+708
View File
@@ -0,0 +1,708 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* jshint esnext: true */
'use strict';
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([require('../../modules/class'), require('../../modules/hero'), require('../../modules/style'), require('../../modules/eventlisteners')]);
var h = require('../../h.js');
var vnode;
var data = {
selected: undefined,
movies: [{ rank: 1, title: 'This is an', desc: 'Lorem ipsum dolor sit amet, sed pede integer vitae bibendum, accumsan sit, vulputate aenean tempora ipsum. Lorem sed id et metus, eros posuere suspendisse nec nunc justo, fusce augue placerat nibh purus suspendisse. Aliquam aliquam, ut eget. Mollis a eget sed nibh tincidunt nec, mi integer, proin magna lacus iaculis tortor. Aliquam vel arcu arcu, vivamus a urna fames felis vel wisi, cursus tortor nec erat dignissim cras sem, mauris ac venenatis tellus elit.' }, { rank: 2, title: 'example of', desc: 'Consequuntur ipsum nulla, consequat curabitur in magnis risus. Taciti mattis bibendum tellus nibh, at dui neque eget, odio pede ut, sapien pede, ipsum ut. Sagittis dui, sodales sem, praesent ipsum conubia eget lorem lobortis wisi.' }, { rank: 3, title: 'Snabbdom', desc: 'Quam lorem aliquam fusce wisi, urna purus ipsum pharetra sed, at cras sodales enim vestibulum odio cras, luctus integer phasellus.' }, { rank: 4, title: 'doing hero transitions', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.' }, { rank: 5, title: 'using the', desc: 'Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.' }, { rank: 6, title: 'module for hero transitions', desc: 'Sapien laoreet, ligula elit tortor nulla pellentesque, maecenas enim turpis, quae duis venenatis vivamus ultricies, nunc imperdiet sollicitudin ipsum malesuada. Ut sem. Wisi fusce nullam nibh enim. Nisl hymenaeos id sed sed in. Proin leo et, pulvinar nunc pede laoreet.' }, { rank: 7, title: 'click on ar element in', desc: 'Accumsan quia, id nascetur dui et congue erat, id excepteur, primis ratione nec. At nulla et. Suspendisse lobortis, lobortis in tortor fringilla, duis adipiscing vestibulum voluptates sociosqu auctor.' }, { rank: 8, title: 'the list', desc: 'Ante tellus egestas vel hymenaeos, ut viverra nibh ut, ipsum nibh donec donec dolor. Eros ridiculus vel egestas convallis ipsum, commodo ut venenatis nullam porta iaculis, suspendisse ante proin leo, felis risus etiam.' }, { rank: 9, title: 'to witness', desc: 'Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst.' }, { rank: 10, title: 'the effect', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris' }]
};
function select(m) {
data.selected = m;
render();
}
function render() {
vnode = patch(vnode, view(data));
}
var fadeInOutStyle = {
opacity: '0', delayed: { opacity: '1' }, remove: { opacity: '0' }
};
var detailView = function detailView(movie) {
return h('div.page', { style: fadeInOutStyle }, [h('div.header', [h('div.header-content.detail', {
style: { opacity: '1', remove: { opacity: '0' } }
}, [h('div.rank', [h('span.header-rank.hero', { hero: { id: 'rank' + movie.rank } }, movie.rank), h('div.rank-circle', {
style: { transform: 'scale(0)',
delayed: { transform: 'scale(1)' },
destroy: { transform: 'scale(0)' } }
})]), h('div.hero.header-title', { hero: { id: movie.title } }, movie.title), h('div.spacer'), h('div.close', {
on: { click: [select, undefined] },
style: { transform: 'scale(0)',
delayed: { transform: 'scale(1)' },
destroy: { transform: 'scale(0)' } }
}, 'x')])]), h('div.page-content', [h('div.desc', {
style: { opacity: '0', transform: 'translateX(3em)',
delayed: { opacity: '1', transform: 'translate(0)' },
remove: { opacity: '0', position: 'absolute', top: '0', left: '0',
transform: 'translateX(3em)' }
}
}, [h('h2', 'Description:'), h('span', movie.desc)])])]);
};
var overviewView = function overviewView(movies) {
return h('div.page', { style: fadeInOutStyle }, [h('div.header', [h('div.header-content.overview', {
style: fadeInOutStyle
}, [h('div.header-title', {
style: { transform: 'translateY(-2em)',
delayed: { transform: 'translate(0)' },
destroy: { transform: 'translateY(-2em)' } }
}, 'Top 10 movies'), h('div.spacer')])]), h('div.page-content', [h('div.list', {
style: { opacity: '0', delayed: { opacity: '1' },
remove: { opacity: '0', position: 'absolute', top: '0', left: '0' } }
}, movies.map(function (movie) {
return h('div.row', {
on: { click: [select, movie] }
}, [h('div.hero.rank', [h('span.hero', { hero: { id: 'rank' + movie.rank } }, movie.rank)]), h('div.hero', { hero: { id: movie.title } }, movie.title)]);
}))])]);
};
var view = function view(data) {
return h('div.page-container', [data.selected ? detailView(data.selected) : overviewView(data.movies)]);
};
window.addEventListener('DOMContentLoaded', function () {
var container = document.getElementById('container');
vnode = patch(container, view(data));
render();
});
},{"../../h.js":2,"../../modules/class":4,"../../modules/eventlisteners":5,"../../modules/hero":6,"../../modules/style":7,"../../snabbdom.js":8}],2:[function(require,module,exports){
'use strict';
var VNode = require('./vnode');
var is = require('./is');
function addNS(data, children) {
data.ns = 'http://www.w3.org/2000/svg';
if (children !== undefined) {
for (var i = 0; i < children.length; ++i) {
addNS(children[i].data, children[i].children);
}
}
}
module.exports = function h(sel, b, c) {
var data = {},
children,
text,
i;
if (arguments.length === 3) {
data = b;
if (is.array(c)) {
children = c;
} else if (is.primitive(c)) {
text = c;
}
} else if (arguments.length === 2) {
if (is.array(b)) {
children = b;
} else if (is.primitive(b)) {
text = b;
} else {
data = b;
}
}
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
}
}
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') {
addNS(data, children);
}
return VNode(sel, data, children, text, undefined);
};
},{"./is":3,"./vnode":9}],3:[function(require,module,exports){
'use strict';
module.exports = {
array: Array.isArray,
primitive: function primitive(s) {
return typeof s === 'string' || typeof s === 'number';
}
};
},{}],4:[function(require,module,exports){
'use strict';
function updateClass(oldVnode, vnode) {
var cur,
name,
elm = vnode.elm,
oldClass = oldVnode.data['class'] || {},
klass = vnode.data['class'] || {};
for (name in klass) {
cur = klass[name];
if (cur !== oldClass[name]) {
elm.classList[cur ? 'add' : 'remove'](name);
}
}
}
module.exports = { create: updateClass, update: updateClass };
},{}],5:[function(require,module,exports){
'use strict';
var is = require('../is');
function arrInvoker(arr) {
return function () {
// Special case when length is two, for performance
arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1));
};
}
function fnInvoker(o) {
return function (ev) {
o.fn(ev);
};
}
function updateEventListeners(oldVnode, vnode) {
var name,
cur,
old,
elm = vnode.elm,
oldOn = oldVnode.data.on || {},
on = vnode.data.on;
if (!on) return;
for (name in on) {
cur = on[name];
old = oldOn[name];
if (old === undefined) {
if (is.array(cur)) {
elm.addEventListener(name, arrInvoker(cur));
} else {
cur = { fn: cur };
on[name] = cur;
elm.addEventListener(name, fnInvoker(cur));
}
} else if (is.array(old)) {
// Deliberately modify old array since it's captured in closure created with `arrInvoker`
old.length = cur.length;
for (var i = 0; i < old.length; ++i) old[i] = cur[i];
on[name] = old;
} else {
old.fn = cur;
on[name] = old;
}
}
}
module.exports = { create: updateEventListeners, update: updateEventListeners };
},{"../is":3}],6:[function(require,module,exports){
'use strict';
var raf = window && window.requestAnimationFrame || setTimeout;
var nextFrame = function nextFrame(fn) {
raf(function () {
raf(fn);
});
};
function setNextFrame(obj, prop, val) {
nextFrame(function () {
obj[prop] = val;
});
}
function getTextNodeRect(textNode) {
var rect;
if (document.createRange) {
var range = document.createRange();
range.selectNodeContents(textNode);
if (range.getBoundingClientRect) {
rect = range.getBoundingClientRect();
}
}
return rect;
}
function calcTransformOrigin(isTextNode, textRect, boundingRect) {
if (isTextNode) {
if (textRect) {
//calculate pixels to center of text from left edge of bounding box
var relativeCenterX = textRect.left + textRect.width / 2 - boundingRect.left;
var relativeCenterY = textRect.top + textRect.height / 2 - boundingRect.top;
return relativeCenterX + 'px ' + relativeCenterY + 'px';
}
}
return '0 0'; //top left
}
function getTextDx(oldTextRect, newTextRect) {
if (oldTextRect && newTextRect) {
return oldTextRect.left + oldTextRect.width / 2 - (newTextRect.left + newTextRect.width / 2);
}
return 0;
}
function getTextDy(oldTextRect, newTextRect) {
if (oldTextRect && newTextRect) {
return oldTextRect.top + oldTextRect.height / 2 - (newTextRect.top + newTextRect.height / 2);
}
return 0;
}
function isTextElement(elm) {
return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3;
}
var removed, created;
function pre(oldVnode, vnode) {
removed = {};
created = [];
}
function create(oldVnode, vnode) {
var hero = vnode.data.hero;
if (hero && hero.id) {
created.push(hero.id);
created.push(vnode);
}
}
function destroy(vnode) {
var hero = vnode.data.hero;
if (hero && hero.id) {
var elm = vnode.elm;
vnode.isTextNode = isTextElement(elm); //is this a text node?
vnode.boundingRect = elm.getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode
vnode.textRect = vnode.isTextNode ? getTextNodeRect(elm.childNodes[0]) : null; //save bounding rect of inner text node
var computedStyle = window.getComputedStyle(elm, null); //get current styles (includes inherited properties)
vnode.savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values
removed[hero.id] = vnode;
}
}
function post() {
var i, id, newElm, oldVnode, oldElm, hRatio, wRatio, oldRect, newRect, dx, dy, origTransform, origTransition, newStyle, oldStyle, newComputedStyle, isTextNode, newTextRect, oldTextRect;
for (i = 0; i < created.length; i += 2) {
id = created[i];
newElm = created[i + 1].elm;
oldVnode = removed[id];
if (oldVnode) {
isTextNode = oldVnode.isTextNode && isTextElement(newElm); //Are old & new both text?
newStyle = newElm.style;
newComputedStyle = window.getComputedStyle(newElm, null); //get full computed style for new element
oldElm = oldVnode.elm;
oldStyle = oldElm.style;
//Overall element bounding boxes
newRect = newElm.getBoundingClientRect();
oldRect = oldVnode.boundingRect; //previously saved bounding rect
//Text node bounding boxes & distances
if (isTextNode) {
newTextRect = getTextNodeRect(newElm.childNodes[0]);
oldTextRect = oldVnode.textRect;
dx = getTextDx(oldTextRect, newTextRect);
dy = getTextDy(oldTextRect, newTextRect);
} else {
//Calculate distances between old & new positions
dx = oldRect.left - newRect.left;
dy = oldRect.top - newRect.top;
}
hRatio = newRect.height / Math.max(oldRect.height, 1);
wRatio = isTextNode ? hRatio : newRect.width / Math.max(oldRect.width, 1); //text scales based on hRatio
// Animate new element
origTransform = newStyle.transform;
origTransition = newStyle.transition;
if (newComputedStyle.display === 'inline') //inline elements cannot be transformed
newStyle.display = 'inline-block'; //this does not appear to have any negative side effects
newStyle.transition = origTransition + 'transform 0s';
newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect);
newStyle.opacity = '0';
newStyle.transform = origTransform + 'translate(' + dx + 'px, ' + dy + 'px) ' + 'scale(' + 1 / wRatio + ', ' + 1 / hRatio + ')';
setNextFrame(newStyle, 'transition', origTransition);
setNextFrame(newStyle, 'transform', origTransform);
setNextFrame(newStyle, 'opacity', '1');
// Animate old element
for (var key in oldVnode.savedStyle) {
//re-apply saved inherited properties
if (parseInt(key) != key) {
var ms = key.substring(0, 2) === 'ms';
var moz = key.substring(0, 3) === 'moz';
var webkit = key.substring(0, 6) === 'webkit';
if (!ms && !moz && !webkit) //ignore prefixed style properties
oldStyle[key] = oldVnode.savedStyle[key];
}
}
oldStyle.position = 'absolute';
oldStyle.top = oldRect.top + 'px'; //start at existing position
oldStyle.left = oldRect.left + 'px';
oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents
oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents
oldStyle.margin = 0; //Margin on hero element leads to incorrect positioning
oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect);
oldStyle.transform = '';
oldStyle.opacity = '1';
document.body.appendChild(oldElm);
setNextFrame(oldStyle, 'transform', 'translate(' + -dx + 'px, ' + -dy + 'px) scale(' + wRatio + ', ' + hRatio + ')'); //scale must be on far right for translate to be correct
setNextFrame(oldStyle, 'opacity', '0');
oldElm.addEventListener('transitionend', function (ev) {
if (ev.propertyName === 'transform') document.body.removeChild(ev.target);
});
}
}
removed = created = undefined;
}
module.exports = { pre: pre, create: create, destroy: destroy, post: post };
},{}],7:[function(require,module,exports){
'use strict';
var raf = requestAnimationFrame || setTimeout;
var nextFrame = function nextFrame(fn) {
raf(function () {
raf(fn);
});
};
function setNextFrame(obj, prop, val) {
nextFrame(function () {
obj[prop] = val;
});
}
function updateStyle(oldVnode, vnode) {
var cur,
name,
elm = vnode.elm,
oldStyle = oldVnode.data.style || {},
style = vnode.data.style || {},
oldHasDel = ('delayed' in oldStyle);
for (name in style) {
cur = style[name];
if (name === 'delayed') {
for (name in style.delayed) {
cur = style.delayed[name];
if (!oldHasDel || cur !== oldStyle.delayed[name]) {
setNextFrame(elm.style, name, cur);
}
}
} else if (name !== 'remove' && cur !== oldStyle[name]) {
elm.style[name] = cur;
}
}
}
function applyDestroyStyle(vnode) {
var style,
name,
elm = vnode.elm,
s = vnode.data.style;
if (!s || !(style = s.destroy)) return;
for (name in style) {
elm.style[name] = style[name];
}
}
function applyRemoveStyle(vnode, rm) {
var s = vnode.data.style;
if (!s || !s.remove) {
rm();
return;
}
var name,
elm = vnode.elm,
idx,
i = 0,
maxDur = 0,
compStyle,
style = s.remove,
amount = 0,
applied = [];
for (name in style) {
applied.push(name);
elm.style[name] = style[name];
}
compStyle = getComputedStyle(elm);
var props = compStyle['transition-property'].split(', ');
for (; i < props.length; ++i) {
if (applied.indexOf(props[i]) !== -1) amount++;
}
elm.addEventListener('transitionend', function (ev) {
if (ev.target === elm) --amount;
if (amount === 0) rm();
});
}
module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle };
},{}],8:[function(require,module,exports){
// jshint newcap: false
/* global require, module, document, Element */
'use strict';
var VNode = require('./vnode');
var is = require('./is');
function isUndef(s) {
return s === undefined;
}
function isDef(s) {
return s !== undefined;
}
function emptyNodeAt(elm) {
return VNode(elm.tagName, {}, [], undefined, elm);
}
var emptyNode = VNode('', {}, [], undefined, undefined);
function sameVnode(vnode1, vnode2) {
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
}
function createKeyToOldIdx(children, beginIdx, endIdx) {
var i,
map = {},
key;
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) map[key] = i;
}
return map;
}
function createRmCb(childElm, listeners) {
return function () {
if (--listeners === 0) childElm.parentElement.removeChild(childElm);
};
}
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
function init(modules) {
var i,
j,
cbs = {};
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
function createElm(vnode, insertedVnodeQueue) {
var i,
data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode);
if (isDef(i = data.vnode)) vnode = i;
}
var elm,
children = vnode.children,
sel = vnode.sel;
if (isDef(sel)) {
// Parse selector
var hashIdx = sel.indexOf('#');
var dotIdx = sel.indexOf('.', hashIdx);
var hash = hashIdx > 0 ? hashIdx : sel.length;
var dot = dotIdx > 0 ? dotIdx : sel.length;
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? document.createElementNS(i, tag) : document.createElement(tag);
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
elm.appendChild(createElm(children[i], insertedVnodeQueue));
}
} else if (is.primitive(vnode.text)) {
elm.appendChild(document.createTextNode(vnode.text));
}
for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode);
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode);
if (i.insert) insertedVnodeQueue.push(vnode);
}
} else {
elm = vnode.elm = document.createTextNode(vnode.text);
}
return vnode.elm;
}
function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
parentElm.insertBefore(createElm(vnodes[startIdx], insertedVnodeQueue), before);
}
}
function invokeDestroyHook(vnode) {
var i = vnode.data,
j;
if (isDef(i)) {
if (isDef(i = i.hook) && isDef(i = i.destroy)) i(vnode);
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
}
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var i,
listeners,
rm,
ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.sel)) {
invokeDestroyHook(ch);
listeners = cbs.remove.length + 1;
rm = createRmCb(ch.elm, listeners);
for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm);
if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) {
i(ch, rm);
} else {
rm();
}
} else {
// Text node
parentElm.removeChild(ch.elm);
}
}
}
}
function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) {
var oldStartIdx = 0,
newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, before;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) {
// Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) {
// Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
idxInOld = oldKeyToIdx[newStartVnode.key];
if (isUndef(idxInOld)) {
// New element
parentElm.insertBefore(createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode(oldVnode, vnode, insertedVnodeQueue) {
var i, hook;
if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode);
}
if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i;
if (isDef(i = vnode.data) && isDef(i = i.vnode)) vnode = i;
var elm = vnode.elm = oldVnode.elm,
oldCh = oldVnode.children,
ch = vnode.children;
if (oldVnode === vnode) return;
if (isDef(vnode.data)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
i = vnode.data.hook;
if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode);
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue);
} else if (isDef(ch)) {
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
}
} else if (oldVnode.text !== vnode.text) {
elm.textContent = vnode.text;
}
if (isDef(hook) && isDef(i = hook.postpatch)) {
i(oldVnode, vnode);
}
}
return function (oldVnode, vnode) {
var i;
var insertedVnodeQueue = [];
for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i]();
if (oldVnode instanceof Element) {
if (oldVnode.parentElement !== null) {
createElm(vnode, insertedVnodeQueue);
oldVnode.parentElement.replaceChild(vnode.elm, oldVnode);
} else {
oldVnode = emptyNodeAt(oldVnode);
patchVnode(oldVnode, vnode, insertedVnodeQueue);
}
} else {
patchVnode(oldVnode, vnode, insertedVnodeQueue);
}
for (i = 0; i < insertedVnodeQueue.length; ++i) {
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
}
for (i = 0; i < cbs.post.length; ++i) cbs.post[i]();
return vnode;
};
}
module.exports = { init: init };
},{"./is":3,"./vnode":9}],9:[function(require,module,exports){
"use strict";
module.exports = function (sel, data, children, text, elm) {
var key = data === undefined ? undefined : data.key;
return { sel: sel, data: data, children: children,
text: text, elm: elm, key: key };
};
},{}]},{},[1]);
+166
View File
@@ -0,0 +1,166 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>Hero animation</title>
<script type="text/javascript" src="build.js"></script>
<style>
{
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
html, body {
height: 100%;
margin: 0;
}
body {
background: #fff;
font-family: sans-serif;
}
.page-container {
width: 100%;
position: relative;
background: #fff;
}
@media (min-width: 28em),
@media (min-height: 38em) {
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #aaaaaa;
position: relative;
}
.page-container {
box-shadow: 0 0 1em rgba(0, 0, 0, .5);
width: 28em;
min-height: 38em;
height: 38em;
}
}
.page {
background: #fff;
transition: opacity 0.4s ease-in-out,
transform 0.4s ease-in-out;
width: 100%;
height: 100%;
}
h2 {
font-size: 1.1em;
margin: .2em 0;
}
.header {
height: 3.5em;
background: #1293ea;
overflow: hidden;
}
.header-content {
width: 100%;
box-sizing: border-box;
padding: .4em .8em;
color: #fff;
display: flex;
align-items: center;
position: absolute;
transition: opacity 0.4s ease-in-out,
transform 0.4s ease-in-out;
}
.header h1 {
font-weight: normal;
margin: 0;
font-size: 1.5em;
line-height: 1.8em;
}
.header-title {
color: #fff;
font-size: 1.5em;
line-height: 1.8em;
transition: transform 0.4s ease-in-out;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.header .rank {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 2.7em;
height: 2.7em;
margin-right: .5em;
position: relative;
}
.header .rank-circle {
position: absolute;
background: #fff;
width: 2.7em;
height: 2.7em;
border-radius: 1.35em;
margin-right: .5em;
transition: transform 0.4s ease-in-out;
top: 0;
left: 0;
}
.header-rank {
z-index: 2;
color: #1293ea;
font-size: 1.5em;
}
.header .close {
line-height: 1.8em;
cursor: pointer;
text-align: center;
width: 1.8em;
height: 1.8em;
border-radius: .9em;
background: rgba(0, 0, 0, .5);
transition: transform 0.4s ease-in-out;
}
.hero {
transition: transform 0.4s ease-in-out,
opacity 0.4s ease-in-out;
}
.page-content {
position: relative;
overflow: hidden;
width: 100%;
height: calc(100% - 3.5em);
}
.list {
position: absolute;
width: 100%;
transition: transform 0.4s ease-in-out,
opacity 0.4s ease-in-out;
}
.desc {
position: absolute;
transition: transform 0.4s ease-in-out,
opacity 0.4s ease-in-out;
padding: 1em;
}
.spacer {
flex: 1;
}
.row {
cursor: pointer;
box-sizing: border-box;
padding: 1em;
}
.row:not(:first-child) {
border-top: 1px solid #eeeeee;
}
.row div {
display: inline-block;
}
.row > div:nth-child(1) {
text-align: center;
margin-right: 1em;
width: 1em;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
+120
View File
@@ -0,0 +1,120 @@
/* jshint esnext: true */
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([
require('../../modules/class').default,
require('../../modules/hero').default,
require('../../modules/style').default,
require('../../modules/eventlisteners').default,
]);
var h = require('../../h.js').default;
var vnode;
var data = {
selected: undefined,
movies: [
{rank: 1, title: 'This is an', desc: 'Lorem ipsum dolor sit amet, sed pede integer vitae bibendum, accumsan sit, vulputate aenean tempora ipsum. Lorem sed id et metus, eros posuere suspendisse nec nunc justo, fusce augue placerat nibh purus suspendisse. Aliquam aliquam, ut eget. Mollis a eget sed nibh tincidunt nec, mi integer, proin magna lacus iaculis tortor. Aliquam vel arcu arcu, vivamus a urna fames felis vel wisi, cursus tortor nec erat dignissim cras sem, mauris ac venenatis tellus elit.'},
{rank: 2, title: 'example of', desc: 'Consequuntur ipsum nulla, consequat curabitur in magnis risus. Taciti mattis bibendum tellus nibh, at dui neque eget, odio pede ut, sapien pede, ipsum ut. Sagittis dui, sodales sem, praesent ipsum conubia eget lorem lobortis wisi.'},
{rank: 3, title: 'Snabbdom', desc: 'Quam lorem aliquam fusce wisi, urna purus ipsum pharetra sed, at cras sodales enim vestibulum odio cras, luctus integer phasellus.'},
{rank: 4, title: 'doing hero transitions', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.'},
{rank: 5, title: 'using the', desc: 'Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris. Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst. Sem nec tristique vel vehicula fringilla, nibh eu et posuere mi rhoncus.'},
{rank: 6, title: 'module for hero transitions', desc: 'Sapien laoreet, ligula elit tortor nulla pellentesque, maecenas enim turpis, quae duis venenatis vivamus ultricies, nunc imperdiet sollicitudin ipsum malesuada. Ut sem. Wisi fusce nullam nibh enim. Nisl hymenaeos id sed sed in. Proin leo et, pulvinar nunc pede laoreet.'},
{rank: 7, title: 'click on ar element in', desc: 'Accumsan quia, id nascetur dui et congue erat, id excepteur, primis ratione nec. At nulla et. Suspendisse lobortis, lobortis in tortor fringilla, duis adipiscing vestibulum voluptates sociosqu auctor.'},
{rank: 8, title: 'the list', desc: 'Ante tellus egestas vel hymenaeos, ut viverra nibh ut, ipsum nibh donec donec dolor. Eros ridiculus vel egestas convallis ipsum, commodo ut venenatis nullam porta iaculis, suspendisse ante proin leo, felis risus etiam.'},
{rank: 9, title: 'to witness', desc: 'Metus amet ad, elit porttitor a aliquet commodo lacus, integer neque imperdiet augue laoreet, nonummy turpis lacus sed pulvinar condimentum platea. Wisi eleifend quis, tristique dictum, ac dictumst.'},
{rank: 10, title: 'the effect', desc: 'Et orci hac ultrices id in. Diam ultrices luctus egestas, sem aliquam auctor molestie odio laoreet. Pede nam cubilia, diam vestibulum ornare natoque, aenean etiam fusce id, eget dictum blandit et mauris mauris'},
]
};
function select(m) {
data.selected = m;
render();
}
function render() {
vnode = patch(vnode, view(data));
}
const fadeInOutStyle = {
opacity: '0', delayed: {opacity: '1'}, remove: {opacity: '0'}
};
const detailView = (movie) =>
h('div.page', {style: fadeInOutStyle}, [
h('div.header', [
h('div.header-content.detail', {
style: {opacity: '1', remove: {opacity: '0'}},
}, [
h('div.rank', [
h('span.header-rank.hero', {hero: {id: 'rank'+movie.rank}}, movie.rank),
h('div.rank-circle', {
style: {transform: 'scale(0)',
delayed: {transform: 'scale(1)'},
destroy: {transform: 'scale(0)'}},
}),
]),
h('div.hero.header-title', {hero: {id: movie.title}}, movie.title),
h('div.spacer'),
h('div.close', {
on: {click: [select, undefined]},
style: {transform: 'scale(0)',
delayed: {transform: 'scale(1)'},
destroy: {transform: 'scale(0)'}},
}, 'x'),
]),
]),
h('div.page-content', [
h('div.desc', {
style: {opacity: '0', transform: 'translateX(3em)',
delayed: {opacity: '1', transform: 'translate(0)'},
remove: {opacity: '0', position: 'absolute', top: '0', left: '0',
transform: 'translateX(3em)'}
}
}, [
h('h2', 'Description:'),
h('span', movie.desc),
]),
]),
]);
const overviewView = (movies) =>
h('div.page', {style: fadeInOutStyle}, [
h('div.header', [
h('div.header-content.overview', {
style: fadeInOutStyle,
}, [
h('div.header-title', {
style: {transform: 'translateY(-2em)',
delayed: {transform: 'translate(0)'},
destroy: {transform: 'translateY(-2em)'}}
}, 'Top 10 movies'),
h('div.spacer'),
]),
]),
h('div.page-content', [
h('div.list', {
style: {opacity: '0', delayed: {opacity: '1'},
remove: {opacity: '0', position: 'absolute', top: '0', left: '0'}}
}, movies.map((movie) =>
h('div.row', {
on: {click: [select, movie]},
}, [
h('div.hero.rank', [
h('span.hero', {hero: {id: 'rank'+movie.rank}}, movie.rank)
]),
h('div.hero', {hero: {id: movie.title}}, movie.title)
])
)),
]),
]);
const view = (data) =>
h('div.page-container', [
data.selected ? detailView(data.selected) : overviewView(data.movies),
]);
window.addEventListener('DOMContentLoaded', () => {
var container = document.getElementById('container');
vnode = patch(container, view(data));
render();
});
+523
View File
@@ -0,0 +1,523 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([require('../../modules/class'), require('../../modules/props'), require('../../modules/style'), require('../../modules/eventlisteners')]);
var h = require('../../h.js');
var vnode;
var nextKey = 11;
var margin = 8;
var sortBy = 'rank';
var totalHeight = 0;
var originalData = [{ rank: 1, title: 'The Shawshank Redemption', desc: 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', elmHeight: 0 }, { rank: 2, title: 'The Godfather', desc: 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', elmHeight: 0 }, { rank: 3, title: 'The Godfather: Part II', desc: 'The early life and career of Vito Corleone in 1920s New York is portrayed while his son, Michael, expands and tightens his grip on his crime syndicate stretching from Lake Tahoe, Nevada to pre-revolution 1958 Cuba.', elmHeight: 0 }, { rank: 4, title: 'The Dark Knight', desc: 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.', elmHeight: 0 }, { rank: 5, title: 'Pulp Fiction', desc: 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', elmHeight: 0 }, { rank: 6, title: 'Schindler\'s List', desc: 'In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.', elmHeight: 0 }, { rank: 7, title: '12 Angry Men', desc: 'A dissenting juror in a murder trial slowly manages to convince the others that the case is not as obviously clear as it seemed in court.', elmHeight: 0 }, { rank: 8, title: 'The Good, the Bad and the Ugly', desc: 'A bounty hunting scam joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.', elmHeight: 0 }, { rank: 9, title: 'The Lord of the Rings: The Return of the King', desc: 'Gandalf and Aragorn lead the World of Men against Sauron\'s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', elmHeight: 0 }, { rank: 10, title: 'Fight Club', desc: 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more...', elmHeight: 0 }];
var data = [originalData[0], originalData[1], originalData[2], originalData[3], originalData[4], originalData[5], originalData[6], originalData[7], originalData[8], originalData[9]];
function changeSort(prop) {
sortBy = prop;
data.sort(function (a, b) {
if (a[prop] > b[prop]) {
return 1;
}
if (a[prop] < b[prop]) {
return -1;
}
return 0;
});
render();
}
function add() {
var n = originalData[Math.floor(Math.random() * 10)];
data = [{ rank: nextKey++, title: n.title, desc: n.desc, elmHeight: 0 }].concat(data);
render();
render();
}
function remove(movie) {
data = data.filter(function (m) {
return m !== movie;
});
render();
}
function movieView(movie) {
return h('div.row', {
key: movie.rank,
style: { opacity: '0', transform: 'translate(-200px)',
delayed: { transform: 'translateY(' + movie.offset + 'px)', opacity: '1' },
remove: { opacity: '0', transform: 'translateY(' + movie.offset + 'px) translateX(200px)' } },
hook: { insert: function insert(vnode) {
movie.elmHeight = vnode.elm.offsetHeight;
} } }, [h('div', { style: { fontWeight: 'bold' } }, movie.rank), h('div', movie.title), h('div', movie.desc), h('div.btn.rm-btn', { on: { click: [remove, movie] } }, 'x')]);
}
function render() {
data = data.reduce(function (acc, m) {
var last = acc[acc.length - 1];
m.offset = last ? last.offset + last.elmHeight + margin : margin;
return acc.concat(m);
}, []);
totalHeight = data[data.length - 1].offset + data[data.length - 1].elmHeight;
vnode = patch(vnode, view(data));
}
function view(data) {
return h('div', [h('h1', 'Top 10 movies'), h('div', [h('a.btn.add', { on: { click: add } }, 'Add'), 'Sort by: ', h('span.btn-group', [h('a.btn.rank', { 'class': { active: sortBy === 'rank' }, on: { click: [changeSort, 'rank'] } }, 'Rank'), h('a.btn.title', { 'class': { active: sortBy === 'title' }, on: { click: [changeSort, 'title'] } }, 'Title'), h('a.btn.desc', { 'class': { active: sortBy === 'desc' }, on: { click: [changeSort, 'desc'] } }, 'Description')])]), h('div.list', { style: { height: totalHeight + 'px' } }, data.map(movieView))]);
}
window.addEventListener('DOMContentLoaded', function () {
var container = document.getElementById('container');
vnode = patch(container, view(data));
render();
});
},{"../../h.js":2,"../../modules/class":4,"../../modules/eventlisteners":5,"../../modules/props":6,"../../modules/style":7,"../../snabbdom.js":8}],2:[function(require,module,exports){
'use strict';
var VNode = require('./vnode');
var is = require('./is');
module.exports = function h(sel, b, c) {
var data = {},
children,
text,
i;
if (arguments.length === 3) {
data = b;
if (is.array(c)) {
children = c;
} else if (is.primitive(c)) {
text = c;
}
} else if (arguments.length === 2) {
if (is.array(b)) {
children = b;
} else if (is.primitive(b)) {
text = b;
} else {
data = b;
}
}
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
}
}
return VNode(sel, data, children, text, undefined);
};
},{"./is":3,"./vnode":9}],3:[function(require,module,exports){
'use strict';
module.exports = {
array: Array.isArray,
primitive: function primitive(s) {
return typeof s === 'string' || typeof s === 'number';
} };
},{}],4:[function(require,module,exports){
'use strict';
function updateClass(oldVnode, vnode) {
var cur,
name,
elm = vnode.elm,
oldClass = oldVnode.data['class'] || {},
klass = vnode.data['class'] || {};
for (name in klass) {
cur = klass[name];
if (cur !== oldClass[name]) {
elm.classList[cur ? 'add' : 'remove'](name);
}
}
}
module.exports = { create: updateClass, update: updateClass };
},{}],5:[function(require,module,exports){
'use strict';
var is = require('../is');
function arrInvoker(arr) {
return function () {
arr[0](arr[1]);
};
}
function updateEventListeners(oldVnode, vnode) {
var name,
cur,
old,
elm = vnode.elm,
oldOn = oldVnode.data.on || {},
on = vnode.data.on;
if (!on) return;
for (name in on) {
cur = on[name];
old = oldOn[name];
if (old === undefined) {
elm.addEventListener(name, is.array(cur) ? arrInvoker(cur) : cur);
} else if (is.array(old)) {
old[0] = cur[0]; // Deliberately modify old array since it's
old[1] = cur[1]; // captured in closure created with `arrInvoker`
}
}
}
module.exports = { create: updateEventListeners, update: updateEventListeners };
},{"../is":3}],6:[function(require,module,exports){
"use strict";
function updateProps(oldVnode, vnode) {
var key,
cur,
old,
elm = vnode.elm,
oldProps = oldVnode.data.props || {},
props = vnode.data.props || {};
for (key in props) {
cur = props[key];
old = oldProps[key];
if (old !== cur) {
elm[key] = cur;
}
}
}
module.exports = { create: updateProps, update: updateProps };
},{}],7:[function(require,module,exports){
'use strict';
var raf = requestAnimationFrame || setTimeout;
var nextFrame = function nextFrame(fn) {
raf(function () {
raf(fn);
});
};
function setNextFrame(obj, prop, val) {
nextFrame(function () {
obj[prop] = val;
});
}
function updateStyle(oldVnode, vnode) {
var cur,
name,
elm = vnode.elm,
oldStyle = oldVnode.data.style || {},
style = vnode.data.style || {},
oldHasDel = ('delayed' in oldStyle);
for (name in style) {
cur = style[name];
if (name === 'delayed') {
for (name in style.delayed) {
cur = style.delayed[name];
if (!oldHasDel || cur !== oldStyle.delayed[name]) {
setNextFrame(elm.style, name, cur);
}
}
} else if (name !== 'remove' && cur !== oldStyle[name]) {
elm.style[name] = cur;
}
}
}
function applyDestroyStyle(vnode) {
var style,
name,
elm = vnode.elm,
s = vnode.data.style;
if (!s || !(style = s.destroy)) return;
for (name in style) {
elm.style[name] = style[name];
}
}
function applyRemoveStyle(vnode, rm) {
var s = vnode.data.style;
if (!s || !s.remove) {
rm();
return;
}
var name,
elm = vnode.elm,
idx,
i = 0,
maxDur = 0,
compStyle,
style = s.remove,
amount = 0;
var applied = [];
for (name in style) {
applied.push(name);
elm.style[name] = style[name];
}
compStyle = getComputedStyle(elm);
var props = compStyle['transition-property'].split(', ');
for (; i < props.length; ++i) {
if (applied.indexOf(props[i]) !== -1) amount++;
}
elm.addEventListener('transitionend', function (ev) {
if (ev.target === elm) --amount;
if (amount === 0) rm();
});
}
module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle };
},{}],8:[function(require,module,exports){
// jshint newcap: false
'use strict';
var VNode = require('./vnode');
var is = require('./is');
function isUndef(s) {
return s === undefined;
}
function emptyNodeAt(elm) {
return VNode(elm.tagName, {}, [], undefined, elm);
}
var emptyNode = VNode('', {}, [], undefined, undefined);
var insertedVnodeQueue;
function sameVnode(vnode1, vnode2) {
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
}
function createKeyToOldIdx(children, beginIdx, endIdx) {
var i,
map = {},
key;
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (!isUndef(key)) map[key] = i;
}
return map;
}
function createRmCb(parentElm, childElm, listeners) {
return function () {
if (--listeners === 0) parentElm.removeChild(childElm);
};
}
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
function init(modules) {
var i,
j,
cbs = {};
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
function createElm(vnode) {
var i;
if (!isUndef(i = vnode.data) && !isUndef(i = i.hook) && !isUndef(i = i.init)) {
i(vnode);
}
if (!isUndef(i = vnode.data) && !isUndef(i = i.vnode)) vnode = i;
var elm,
children = vnode.children,
sel = vnode.sel;
if (!isUndef(sel)) {
// Parse selector
var hashIdx = sel.indexOf('#');
var dotIdx = sel.indexOf('.', hashIdx);
var hash = hashIdx > 0 ? hashIdx : sel.length;
var dot = dotIdx > 0 ? dotIdx : sel.length;
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
elm = vnode.elm = document.createElement(tag);
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
elm.appendChild(createElm(children[i]));
}
} else if (is.primitive(vnode.text)) {
elm.appendChild(document.createTextNode(vnode.text));
}
for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode);
i = vnode.data.hook; // Reuse variable
if (!isUndef(i)) {
if (i.create) i.create(vnode);
if (i.insert) insertedVnodeQueue.push(vnode);
}
} else {
elm = vnode.elm = document.createTextNode(vnode.text);
}
return elm;
}
function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
if (isUndef(before)) {
for (; startIdx <= endIdx; ++startIdx) {
parentElm.appendChild(createElm(vnodes[startIdx]));
}
} else {
var elm = before.elm;
for (; startIdx <= endIdx; ++startIdx) {
parentElm.insertBefore(createElm(vnodes[startIdx]), elm);
}
}
}
function invokeDestroyHook(vnode) {
var i = vnode.data.hook,
j;
if (!isUndef(i) && !isUndef(j = i.destroy)) j(vnode);
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
if (!isUndef(vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var i,
listeners,
rm,
ch = vnodes[startIdx];
if (!isUndef(ch)) {
listeners = cbs.remove.length + 1;
rm = createRmCb(parentElm, ch.elm, listeners);
for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm);
invokeDestroyHook(ch);
if (ch.data.hook && ch.data.hook.remove) {
ch.data.hook.remove(ch, rm);
} else {
rm();
}
}
}
}
function updateChildren(parentElm, oldCh, newCh) {
var oldStartIdx = 0,
newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) {
// Vnode moved right
patchVnode(oldStartVnode, newEndVnode);
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) {
// Vnode moved left
patchVnode(oldEndVnode, newStartVnode);
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
idxInOld = oldKeyToIdx[newStartVnode.key];
if (isUndef(idxInOld)) {
// New element
parentElm.insertBefore(createElm(newStartVnode), oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
patchVnode(elmToMove, newStartVnode);
oldCh[idxInOld] = undefined;
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
if (oldStartIdx > oldEndIdx) addVnodes(parentElm, oldStartVnode, newCh, newStartIdx, newEndIdx);else if (newStartIdx > newEndIdx) removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
function patchVnode(oldVnode, vnode) {
var i;
if (!isUndef(i = vnode.data) && !isUndef(i = i.hook) && !isUndef(i = i.patch)) {
i = i(oldVnode, vnode);
}
if (!isUndef(i = oldVnode.data) && !isUndef(i = i.vnode)) oldVnode = i;
if (!isUndef(i = vnode.data) && !isUndef(i = i.vnode)) vnode = i;
var elm = vnode.elm = oldVnode.elm,
oldCh = oldVnode.children,
ch = vnode.children;
if (oldVnode === vnode) return;
if (!isUndef(vnode.data)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
i = vnode.data.hook;
if (!isUndef(i) && !isUndef(i = i.update)) i(vnode);
}
if (isUndef(vnode.text)) {
if (!isUndef(oldCh) && !isUndef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch);
} else if (!isUndef(ch)) {
addVnodes(elm, undefined, ch, 0, ch.length - 1);
} else if (!isUndef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
}
} else if (oldVnode.text !== vnode.text) {
elm.childNodes[0].nodeValue = vnode.text;
}
return vnode;
}
return function (oldVnode, vnode) {
var i;
insertedVnodeQueue = [];
if (oldVnode instanceof Element) {
oldVnode = emptyNodeAt(oldVnode);
}
for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i]();
patchVnode(oldVnode, vnode);
for (i = 0; i < insertedVnodeQueue.length; ++i) {
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
}
insertedVnodeQueue = undefined;
for (i = 0; i < cbs.post.length; ++i) cbs.post[i]();
return vnode;
};
}
module.exports = { init: init };
},{"./is":3,"./vnode":9}],9:[function(require,module,exports){
"use strict";
module.exports = function (sel, data, children, text, elm) {
var key = data === undefined ? undefined : data.key;
return { sel: sel, data: data, children: children,
text: text, elm: elm, key: key };
};
},{}]},{},[1]);
+84
View File
@@ -0,0 +1,84 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reorder animation</title>
<script type="text/javascript" src="build.js"></script>
<style>
body {
background: #fafafa;
font-family: sans-serif;
}
h1 {
font-weight: normal;
}
.btn {
display: inline-block;
cursor: pointer;
background: #fff;
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
padding: .5em .8em;
transition: box-shadow .05s ease-in-out;
-webkit-transition: box-shadow .05s ease-in-out;
}
.btn:hover {
box-shadow: 0 0 2px rgba(0, 0, 0, .2);
}
.btn:active, .active, .active:hover {
box-shadow: 0 0 1px rgba(0, 0, 0, .2),
inset 0 0 4px rgba(0, 0, 0, .1);
}
.add {
float: right;
}
#container {
max-width: 42em;
margin: 0 auto 2em auto;
}
.list {
position: relative;
}
.row {
overflow: hidden;
position: absolute;
box-sizing: border-box;
width: 100%;
left: 0px;
margin: .5em 0;
padding: 1em;
background: #fff;
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
-webkit-transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
}
.row div {
display: inline-block;
vertical-align: middle;
}
.row > div:nth-child(1) {
width: 5%;
}
.row > div:nth-child(2) {
width: 30%;
}
.row > div:nth-child(3) {
width: 65%;
}
.rm-btn {
cursor: pointer;
position: absolute;
top: 0;
right: 0;
color: #C25151;
width: 1.4em;
height: 1.4em;
text-align: center;
line-height: 1.4em;
padding: 0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
+112
View File
@@ -0,0 +1,112 @@
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([
require('../../modules/class').default,
require('../../modules/props').default,
require('../../modules/style').default,
require('../../modules/eventlisteners').default,
]);
var h = require('../../h.js').default;
var vnode;
var nextKey = 11;
var margin = 8;
var sortBy = 'rank';
var totalHeight = 0;
var originalData = [
{rank: 1, title: 'The Shawshank Redemption', desc: 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', elmHeight: 0},
{rank: 2, title: 'The Godfather', desc: 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', elmHeight: 0},
{rank: 3, title: 'The Godfather: Part II', desc: 'The early life and career of Vito Corleone in 1920s New York is portrayed while his son, Michael, expands and tightens his grip on his crime syndicate stretching from Lake Tahoe, Nevada to pre-revolution 1958 Cuba.', elmHeight: 0},
{rank: 4, title: 'The Dark Knight', desc: 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.', elmHeight: 0},
{rank: 5, title: 'Pulp Fiction', desc: 'The lives of two mob hit men, a boxer, a gangster\'s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', elmHeight: 0},
{rank: 6, title: 'Schindler\'s List', desc: 'In Poland during World War II, Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.', elmHeight: 0},
{rank: 7, title: '12 Angry Men', desc: 'A dissenting juror in a murder trial slowly manages to convince the others that the case is not as obviously clear as it seemed in court.', elmHeight: 0},
{rank: 8, title: 'The Good, the Bad and the Ugly', desc: 'A bounty hunting scam joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.', elmHeight: 0},
{rank: 9, title: 'The Lord of the Rings: The Return of the King', desc: 'Gandalf and Aragorn lead the World of Men against Sauron\'s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', elmHeight: 0},
{rank: 10, title: 'Fight Club', desc: 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more...', elmHeight: 0},
];
var data = [
originalData[0],
originalData[1],
originalData[2],
originalData[3],
originalData[4],
originalData[5],
originalData[6],
originalData[7],
originalData[8],
originalData[9],
];
function changeSort(prop) {
sortBy = prop;
data.sort((a, b) => {
if (a[prop] > b[prop]) {
return 1;
}
if (a[prop] < b[prop]) {
return -1;
}
return 0;
});
render();
}
function add() {
var n = originalData[Math.floor(Math.random() * 10)];
data = [{rank: nextKey++, title: n.title, desc: n.desc, elmHeight: 0}].concat(data);
render();
render();
}
function remove(movie) {
data = data.filter((m) => { return m !== movie; });
render();
}
function movieView(movie) {
return h('div.row', {
key: movie.rank,
style: {opacity: '0', transform: 'translate(-200px)',
delayed: {transform: `translateY(${movie.offset}px)`, opacity: '1'},
remove: {opacity: '0', transform: `translateY(${movie.offset}px) translateX(200px)`}},
hook: {insert: (vnode) => { movie.elmHeight = vnode.elm.offsetHeight; }},
}, [
h('div', {style: {fontWeight: 'bold'}}, movie.rank),
h('div', movie.title),
h('div', movie.desc),
h('div.btn.rm-btn', {on: {click: [remove, movie]}}, 'x'),
]);
}
function render() {
data = data.reduce((acc, m) => {
var last = acc[acc.length - 1];
m.offset = last ? last.offset + last.elmHeight + margin : margin;
return acc.concat(m);
}, []);
totalHeight = data[data.length - 1].offset + data[data.length - 1].elmHeight;
vnode = patch(vnode, view(data));
}
function view(data) {
return h('div', [
h('h1', 'Top 10 movies'),
h('div', [
h('a.btn.add', {on: {click: add}}, 'Add'),
'Sort by: ',
h('span.btn-group', [
h('a.btn.rank', {class: {active: sortBy === 'rank'}, on: {click: [changeSort, 'rank']}}, 'Rank'),
h('a.btn.title', {class: {active: sortBy === 'title'}, on: {click: [changeSort, 'title']}}, 'Title'),
h('a.btn.desc', {class: {active: sortBy === 'desc'}, on: {click: [changeSort, 'desc']}}, 'Description'),
]),
]),
h('div.list', {style: {height: totalHeight+'px'}}, data.map(movieView)),
]);
}
window.addEventListener('DOMContentLoaded', () => {
var container = document.getElementById('container');
vnode = patch(container, view(data));
render();
});
+376
View File
@@ -0,0 +1,376 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([require('../../modules/attributes')]);
var h = require('../../h.js');
var vnode;
window.addEventListener('DOMContentLoaded', function () {
var container = document.getElementById('container');
var vnode = h('div', [h('svg', { attrs: { width: 100, height: 100 } }, [h('circle', { attrs: { cx: 50, cy: 50, r: 40, stroke: 'green', 'stroke-width': 4, fill: 'yellow' } })])]);
vnode = patch(container, vnode);
});
},{"../../h.js":2,"../../modules/attributes":4,"../../snabbdom.js":5}],2:[function(require,module,exports){
'use strict';
var VNode = require('./vnode');
var is = require('./is');
function addNS(data, children) {
data.ns = 'http://www.w3.org/2000/svg';
if (children !== undefined) {
for (var i = 0; i < children.length; ++i) {
addNS(children[i].data, children[i].children);
}
}
}
module.exports = function h(sel, b, c) {
var data = {},
children,
text,
i;
if (arguments.length === 3) {
data = b;
if (is.array(c)) {
children = c;
} else if (is.primitive(c)) {
text = c;
}
} else if (arguments.length === 2) {
if (is.array(b)) {
children = b;
} else if (is.primitive(b)) {
text = b;
} else {
data = b;
}
}
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]);
}
}
if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') {
addNS(data, children);
}
return VNode(sel, data, children, text, undefined);
};
},{"./is":3,"./vnode":6}],3:[function(require,module,exports){
'use strict';
module.exports = {
array: Array.isArray,
primitive: function primitive(s) {
return typeof s === 'string' || typeof s === 'number';
} };
},{}],4:[function(require,module,exports){
"use strict";
var booleanAttrs = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "compact", "controls", "declare", "default", "defaultchecked", "defaultmuted", "defaultselected", "defer", "disabled", "draggable", "enabled", "formnovalidate", "hidden", "indeterminate", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "pauseonexit", "readonly", "required", "reversed", "scoped", "seamless", "selected", "sortable", "spellcheck", "translate", "truespeed", "typemustmatch", "visible"];
var booleanAttrsDict = {};
for (var i = 0, len = booleanAttrs.length; i < len; i++) {
booleanAttrsDict[booleanAttrs[i]] = true;
}
function updateAttrs(oldVnode, vnode) {
var key,
cur,
old,
elm = vnode.elm,
oldAttrs = oldVnode.data.attrs || {},
attrs = vnode.data.attrs || {};
// update modified attributes, add new attributes
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
// TODO: add support to namespaced attributes (setAttributeNS)
if (!cur && booleanAttrsDict[key]) elm.removeAttribute(key);else elm.setAttribute(key, cur);
}
}
//remove removed attributes
// use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value)
// the other option is to remove all attributes with value == undefined
for (key in oldAttrs) {
if (!(key in attrs)) {
elm.removeAttribute(key);
}
}
}
module.exports = { create: updateAttrs, update: updateAttrs };
},{}],5:[function(require,module,exports){
// jshint newcap: false
/* global require, module, document, Element */
'use strict';
var VNode = require('./vnode');
var is = require('./is');
function isUndef(s) {
return s === undefined;
}
function isDef(s) {
return s !== undefined;
}
function emptyNodeAt(elm) {
return VNode(elm.tagName, {}, [], undefined, elm);
}
var emptyNode = VNode('', {}, [], undefined, undefined);
function sameVnode(vnode1, vnode2) {
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
}
function createKeyToOldIdx(children, beginIdx, endIdx) {
var i,
map = {},
key;
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) map[key] = i;
}
return map;
}
function createRmCb(childElm, listeners) {
return function () {
if (--listeners === 0) childElm.parentElement.removeChild(childElm);
};
}
var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
function init(modules) {
var i,
j,
cbs = {};
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
function createElm(vnode, insertedVnodeQueue) {
var i,
data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode);
if (isDef(i = data.vnode)) vnode = i;
}
var elm,
children = vnode.children,
sel = vnode.sel;
if (isDef(sel)) {
// Parse selector
var hashIdx = sel.indexOf('#');
var dotIdx = sel.indexOf('.', hashIdx);
var hash = hashIdx > 0 ? hashIdx : sel.length;
var dot = dotIdx > 0 ? dotIdx : sel.length;
var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? document.createElementNS(i, tag) : document.createElement(tag);
if (hash < dot) elm.id = sel.slice(hash + 1, dot);
if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' ');
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
elm.appendChild(createElm(children[i], insertedVnodeQueue));
}
} else if (is.primitive(vnode.text)) {
elm.appendChild(document.createTextNode(vnode.text));
}
for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode);
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode);
if (i.insert) insertedVnodeQueue.push(vnode);
}
} else {
elm = vnode.elm = document.createTextNode(vnode.text);
}
return vnode.elm;
}
function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
parentElm.insertBefore(createElm(vnodes[startIdx], insertedVnodeQueue), before);
}
}
function invokeDestroyHook(vnode) {
var i = vnode.data,
j;
if (isDef(i)) {
if (isDef(i = i.hook) && isDef(i = i.destroy)) i(vnode);
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
}
function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var i,
listeners,
rm,
ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.sel)) {
invokeDestroyHook(ch);
listeners = cbs.remove.length + 1;
rm = createRmCb(ch.elm, listeners);
for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm);
if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) {
i(ch, rm);
} else {
rm();
}
} else {
// Text node
parentElm.removeChild(ch.elm);
}
}
}
}
function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) {
var oldStartIdx = 0,
newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, before;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) {
// Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
parentElm.insertBefore(oldStartVnode.elm, oldEndVnode.elm.nextSibling);
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) {
// Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
parentElm.insertBefore(oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
idxInOld = oldKeyToIdx[newStartVnode.key];
if (isUndef(idxInOld)) {
// New element
parentElm.insertBefore(createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
parentElm.insertBefore(elmToMove.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode(oldVnode, vnode, insertedVnodeQueue) {
var i, hook;
if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode);
}
if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i;
if (isDef(i = vnode.data) && isDef(i = i.vnode)) vnode = i;
var elm = vnode.elm = oldVnode.elm,
oldCh = oldVnode.children,
ch = vnode.children;
if (oldVnode === vnode) return;
if (isDef(vnode.data)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
i = vnode.data.hook;
if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode);
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue);
} else if (isDef(ch)) {
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
}
} else if (oldVnode.text !== vnode.text) {
elm.textContent = vnode.text;
}
if (isDef(hook) && isDef(i = hook.postpatch)) {
i(oldVnode, vnode);
}
}
return function (oldVnode, vnode) {
var i;
var insertedVnodeQueue = [];
for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i]();
if (oldVnode instanceof Element) {
if (oldVnode.parentElement !== null) {
createElm(vnode, insertedVnodeQueue);
oldVnode.parentElement.replaceChild(vnode.elm, oldVnode);
} else {
oldVnode = emptyNodeAt(oldVnode);
patchVnode(oldVnode, vnode, insertedVnodeQueue);
}
} else {
patchVnode(oldVnode, vnode, insertedVnodeQueue);
}
for (i = 0; i < insertedVnodeQueue.length; ++i) {
insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]);
}
for (i = 0; i < cbs.post.length; ++i) cbs.post[i]();
return vnode;
};
}
module.exports = { init: init };
},{"./is":3,"./vnode":6}],6:[function(require,module,exports){
"use strict";
module.exports = function (sel, data, children, text, elm) {
var key = data === undefined ? undefined : data.key;
return { sel: sel, data: data, children: children,
text: text, elm: elm, key: key };
};
},{}]},{},[1]);
+84
View File
@@ -0,0 +1,84 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SVG</title>
<script type="text/javascript" src="build.js"></script>
<style>
body {
background: #fafafa;
font-family: sans-serif;
}
h1 {
font-weight: normal;
}
.btn {
display: inline-block;
cursor: pointer;
background: #fff;
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
padding: .5em .8em;
transition: box-shadow .05s ease-in-out;
-webkit-transition: box-shadow .05s ease-in-out;
}
.btn:hover {
box-shadow: 0 0 2px rgba(0, 0, 0, .2);
}
.btn:active, .active, .active:hover {
box-shadow: 0 0 1px rgba(0, 0, 0, .2),
inset 0 0 4px rgba(0, 0, 0, .1);
}
.add {
float: right;
}
#container {
max-width: 42em;
margin: 0 auto 2em auto;
}
.list {
position: relative;
}
.row {
overflow: hidden;
position: absolute;
box-sizing: border-box;
width: 100%;
left: 0px;
margin: .5em 0;
padding: 1em;
background: #fff;
box-shadow: 0 0 1px rgba(0, 0, 0, .2);
transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
-webkit-transition: transform .5s ease-in-out, opacity .5s ease-out, left .5s ease-in-out;
}
.row div {
display: inline-block;
vertical-align: middle;
}
.row > div:nth-child(1) {
width: 5%;
}
.row > div:nth-child(2) {
width: 30%;
}
.row > div:nth-child(3) {
width: 65%;
}
.rm-btn {
cursor: pointer;
position: absolute;
top: 0;
right: 0;
color: #C25151;
width: 1.4em;
height: 1.4em;
text-align: center;
line-height: 1.4em;
padding: 0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
+17
View File
@@ -0,0 +1,17 @@
var snabbdom = require('../../snabbdom.js');
var patch = snabbdom.init([
require('../../modules/attributes').default,
]);
var h = require('../../h.js').default;
var vnode;
window.addEventListener('DOMContentLoaded', () => {
var container = document.getElementById('container');
var vnode = h('div', [
h('svg', {attrs: {width: 100, height: 100}}, [
h('circle', {attrs: {cx: 50, cy: 50, r: 40, stroke: 'green', 'stroke-width': 4, fill: 'yellow'}})
])
]);
vnode = patch(container, vnode);
});
+82
View File
@@ -0,0 +1,82 @@
var gulp = require('gulp')
var clean = require('gulp-clean')
var uglify = require('gulp-uglify')
var rename = require('gulp-rename')
var sourcemaps = require('gulp-sourcemaps')
var browserify = require('browserify')
var fs = require('fs')
function standalone(name, entry, exportName) {
return browserify(entry, { debug: true, standalone: exportName || name })
.bundle()
.pipe(fs.createWriteStream('./dist/'+ name.replace(/_/g, '-') +'.js'))
}
gulp.task('bundle:snabbdom', function() {
return standalone('snabbdom_patch', './snabbdom.bundle.js', 'snabbdom')
})
gulp.task('bundle:snabbdom:init', function() {
return standalone('snabbdom', './snabbdom.js')
})
gulp.task('bundle:snabbdom:h', function() {
return standalone('h', './h.js')
})
gulp.task('bundle:snabbdom:tovnode', function() {
return standalone('tovnode', './tovnode.js')
})
gulp.task('bundle:module:class', function() {
return standalone('snabbdom_class', './modules/class.js')
})
gulp.task('bundle:module:dataset', function() {
return standalone('snabbdom_dataset', './modules/dataset.js')
})
gulp.task('bundle:module:props', function() {
return standalone('snabbdom_props', './modules/props.js')
})
gulp.task('bundle:module:attributes', function() {
return standalone('snabbdom_attributes', './modules/attributes.js')
})
gulp.task('bundle:module:style', function() {
return standalone('snabbdom_style', './modules/style.js')
})
gulp.task('bundle:module:eventlisteners', function() {
return standalone('snabbdom_eventlisteners', './modules/eventlisteners.js')
})
gulp.task('bundle', [
'bundle:snabbdom',
'bundle:snabbdom:init',
'bundle:snabbdom:h',
'bundle:snabbdom:tovnode',
'bundle:module:attributes',
'bundle:module:class',
'bundle:module:dataset',
'bundle:module:props',
'bundle:module:style',
'bundle:module:eventlisteners'
])
gulp.task('compress', ['bundle'], function() {
return gulp.src(['dist/*.js', '!dist/*.min.js'])
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'))
})
gulp.task('clean', function() {
return gulp.src('dist/*.*', {read: false})
.pipe(clean())
})
gulp.task('default', ['bundle'])
+66
View File
@@ -0,0 +1,66 @@
const ci = !!process.env.CI;
const watch = !!process.env.WATCH;
const live = !!process.env.LIVE;
const identifier = process.env.BROWSERSTACK_LOCAL_IDENTIFIER;
const ip = process.env.IP_ADDR;
const browserstack = require('./browserstack-karma.js');
const browsers = ci
? Object.keys(browserstack)
: live
? undefined
: watch
? ['Chrome']
: ['Chrome', 'Firefox'];
module.exports = function(config) {
config.set({
basePath: '.',
frameworks: ['mocha', 'karma-typescript'],
// list of files / patterns to load in the browser
files: [{pattern: 'src/**/*.ts'}, {pattern: 'test/**/*'}],
plugins: [
'karma-mocha',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-browserstack-launcher',
'karma-typescript',
],
hostname: ci ? ip : 'localhost',
preprocessors: {
'src/**/*.ts': ['karma-typescript'],
'test/**/*.js': ['karma-typescript'],
},
browserStack: {
name: 'Snabbdom',
startTunnel: false,
retryLimit: 3,
tunnelIdentifier: identifier,
},
browserNoActivityTimeout: 1000000,
customLaunchers: browserstack,
karmaTypescriptConfig: {
coverageOptions: {
exclude: /test\//,
},
compilerOptions: {
allowJs: true,
declaration: false
},
tsconfig: './tsconfig.json',
include: {
mode: 'merge',
values: ['test/**/*'],
},
},
reporters: ['dots', 'karma-typescript', 'BrowserStack'],
port: 9876,
colors: true,
autoWatch: true,
browsers: browsers,
singleRun: !watch && !live,
concurrency: ci ? 1 : Infinity,
});
}
+60
View File
@@ -0,0 +1,60 @@
{
"name": "snabbdom",
"version": "0.7.3",
"description": "A virtual DOM library with focus on simplicity, modularity, powerful features and performance.",
"main": "snabbdom.js",
"module": "es/snabbdom.js",
"typings": "snabbdom.d.ts",
"directories": {
"example": "examples",
"test": "test"
},
"devDependencies": {
"benchmark": "^2.1.4",
"browserify": "^14.4.0",
"fake-raf": "1.0.1",
"gulp": "^3.9.1",
"gulp-clean": "^0.3.2",
"gulp-rename": "^1.2.2",
"gulp-sourcemaps": "^2.6.0",
"gulp-uglify": "^3.0.0",
"karma": "^3.0.0",
"karma-browserstack-launcher": "^1.3.0",
"karma-chrome-launcher": "^2.2.0",
"karma-firefox-launcher": "^1.1.0",
"karma-mocha": "^1.3.0",
"karma-typescript": "^3.0.13",
"knuth-shuffle": "^1.0.1",
"mocha": "^5.2.0",
"typescript": "^3.0.3",
"xyz": "2.1.0"
},
"scripts": {
"pretest": "npm run compile",
"test": "testem",
"compile": "npm run compile-es && npm run compile-commonjs",
"compile-es": "tsc --outDir es --module es6 --moduleResolution node",
"compile-commonjs": "tsc --outDir ./",
"prepublish": "npm run compile",
"release-major": "xyz --repo git@github.com:paldepind/snabbdom.git --increment major",
"release-minor": "xyz --repo git@github.com:paldepind/snabbdom.git --increment minor",
"release-patch": "xyz --repo git@github.com:paldepind/snabbdom.git --increment patch"
},
"repository": {
"type": "git",
"url": "git+https://github.com/paldepind/snabbdom.git"
},
"keywords": [
"virtual",
"dom",
"light",
"kiss",
"performance"
],
"author": "Simon Friis Vindum",
"license": "MIT",
"bugs": {
"url": "https://github.com/paldepind/snabbdom/issues"
},
"homepage": "https://github.com/paldepind/snabbdom#readme"
}
+58
View File
@@ -0,0 +1,58 @@
var Benchmark = require('benchmark');
var a = require('../snabbdom.js');
var b = require('../oldsnabbdom.js');
global.a = a;
global.b = b;
var suite = new Benchmark.Suite();
a.spanNum = function spanNum(n) {
return a.h('span', {key: n}, n.toString());
};
b.spanNum = function spanNum(n) {
return b.h('span', {key: n}, n.toString());
};
var elms = global.elms = 10;
var arr = global.arr = [];
for (var n = 0; n < elms; ++n) { arr[n] = n; }
document.addEventListener('DOMContentLoaded', function() {
var elm = global.elm = document.getElementById('container');
// add tests
suite.add('a/ insert first', {
setup: function() {
var vnode1 = a.h('div', arr.map(a.spanNum));
var vnode2 = a.h('div', ['new'].concat(arr).map(a.spanNum));
},
fn: function() {
var emptyNode = a.emptyNodeAt(elm);
a.patch(emptyNode, vnode1);
a.patch(vnode1, vnode2);
a.patch(vnode2, a.emptyNode);
},
})
.add('b/ insert first', {
setup: function() {
var vnode1 = b.h('div', arr.map(b.spanNum));
var vnode2 = b.h('div', ['new'].concat(arr).map(b.spanNum));
},
fn: function() {
var emptyNode = b.emptyNodeAt(elm);
b.patch(emptyNode, vnode1);
b.patch(vnode1, vnode2);
b.patch(vnode2, b.emptyNode);
},
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run({async: true});
});
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Snabbdom benchmarks</title>
<script type="text/javascript" src="build.js"></script>
</head>
<body>
<p>See console</p>
<div id="container"></div>
</body>
</html>
+50
View File
@@ -0,0 +1,50 @@
import {vnode, VNode, VNodeData} from './vnode';
export type VNodes = Array<VNode>;
export type VNodeChildElement = VNode | string | number | undefined | null;
export type ArrayOrElement<T> = T | T[];
export type VNodeChildren = ArrayOrElement<VNodeChildElement>
import * as is from './is';
function addNS(data: any, children: VNodes | undefined, sel: string | undefined): void {
data.ns = 'http://www.w3.org/2000/svg';
if (sel !== 'foreignObject' && children !== undefined) {
for (let i = 0; i < children.length; ++i) {
let childData = children[i].data;
if (childData !== undefined) {
addNS(childData, (children[i] as VNode).children as VNodes, children[i].sel);
}
}
}
}
export function h(sel: string): VNode;
export function h(sel: string, data: VNodeData): VNode;
export function h(sel: string, children: VNodeChildren): VNode;
export function h(sel: string, data: VNodeData, children: VNodeChildren): VNode;
export function h(sel: any, b?: any, c?: any): VNode {
var data: VNodeData = {}, children: any, text: any, i: number;
if (c !== undefined) {
data = b;
if (is.array(c)) { children = c; }
else if (is.primitive(c)) { text = c; }
else if (c && c.sel) { children = [c]; }
} else if (b !== undefined) {
if (is.array(b)) { children = b; }
else if (is.primitive(b)) { text = b; }
else if (b && b.sel) { children = [b]; }
else { data = b; }
}
if (children !== undefined) {
for (i = 0; i < children.length; ++i) {
if (is.primitive(children[i])) children[i] = vnode(undefined, undefined, undefined, children[i], undefined);
}
}
if (
sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g' &&
(sel.length === 3 || sel[3] === '.' || sel[3] === '#')
) {
addNS(data, children, sel);
}
return vnode(sel, data, children, text, undefined);
};
export default h;
+64
View File
@@ -0,0 +1,64 @@
import {VNode, VNodeData} from '../vnode';
export interface AttachData {
[key: string]: any
[i: number]: any
placeholder?: any
real?: Node
}
interface VNodeDataWithAttach extends VNodeData {
attachData: AttachData
}
interface VNodeWithAttachData extends VNode {
data: VNodeDataWithAttach
}
function pre(vnode: VNodeWithAttachData, newVnode: VNodeWithAttachData): void {
const attachData = vnode.data.attachData;
// Copy created placeholder and real element from old vnode
newVnode.data.attachData.placeholder = attachData.placeholder;
newVnode.data.attachData.real = attachData.real;
// Mount real element in vnode so the patch process operates on it
vnode.elm = vnode.data.attachData.real;
}
function post(_: any, vnode: VNodeWithAttachData): void {
// Mount dummy placeholder in vnode so potential reorders use it
vnode.elm = vnode.data.attachData.placeholder;
}
function destroy(vnode: VNodeWithAttachData): void {
// Remove placeholder
if (vnode.elm !== undefined) {
(vnode.elm.parentNode as HTMLElement).removeChild(vnode.elm);
}
// Remove real element from where it was inserted
vnode.elm = vnode.data.attachData.real;
}
function create(_: any, vnode: VNodeWithAttachData): void {
const real = vnode.elm, attachData = vnode.data.attachData;
const placeholder = document.createElement('span');
// Replace actual element with dummy placeholder
// Snabbdom will then insert placeholder instead
vnode.elm = placeholder;
attachData.target.appendChild(real);
attachData.real = real;
attachData.placeholder = placeholder;
}
export function attachTo(target: Element, vnode: VNode): VNode {
if (vnode.data === undefined) vnode.data = {};
if (vnode.data.hook === undefined) vnode.data.hook = {};
const data = vnode.data;
const hook = vnode.data.hook;
data.attachData = {target: target, placeholder: undefined, real: undefined};
hook.create = create;
hook.prepatch = pre;
hook.postpatch = post;
hook.destroy = destroy;
return vnode;
};
export default attachTo;
+25
View File
@@ -0,0 +1,25 @@
import {VNode} from './vnode';
export type PreHook = () => any;
export type InitHook = (vNode: VNode) => any;
export type CreateHook = (emptyVNode: VNode, vNode: VNode) => any;
export type InsertHook = (vNode: VNode) => any;
export type PrePatchHook = (oldVNode: VNode, vNode: VNode) => any;
export type UpdateHook = (oldVNode: VNode, vNode: VNode) => any;
export type PostPatchHook = (oldVNode: VNode, vNode: VNode) => any;
export type DestroyHook = (vNode: VNode) => any;
export type RemoveHook = (vNode: VNode, removeCallback: () => void) => any;
export type PostHook = () => any;
export interface Hooks {
pre?: PreHook;
init?: InitHook;
create?: CreateHook;
insert?: InsertHook;
prepatch?: PrePatchHook;
update?: UpdateHook;
postpatch?: PostPatchHook;
destroy?: DestroyHook;
remove?: RemoveHook;
post?: PostHook;
}
+97
View File
@@ -0,0 +1,97 @@
export interface DOMAPI {
createElement: (tagName: any) => HTMLElement;
createElementNS: (namespaceURI: string, qualifiedName: string) => Element;
createTextNode: (text: string) => Text;
createComment: (text: string) => Comment;
insertBefore: (parentNode: Node, newNode: Node, referenceNode: Node | null) => void;
removeChild: (node: Node, child: Node) => void;
appendChild: (node: Node, child: Node) => void;
parentNode: (node: Node) => Node;
nextSibling: (node: Node) => Node;
tagName: (elm: Element) => string;
setTextContent: (node: Node, text: string | null) => void;
getTextContent: (node: Node) => string | null;
isElement: (node: Node) => node is Element;
isText: (node: Node) => node is Text;
isComment: (node: Node) => node is Comment;
}
function createElement(tagName: any): HTMLElement {
return document.createElement(tagName);
}
function createElementNS(namespaceURI: string, qualifiedName: string): Element {
return document.createElementNS(namespaceURI, qualifiedName);
}
function createTextNode(text: string): Text {
return document.createTextNode(text);
}
function createComment(text: string): Comment {
return document.createComment(text);
}
function insertBefore(parentNode: Node, newNode: Node, referenceNode: Node | null): void {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild(node: Node, child: Node): void {
node.removeChild(child);
}
function appendChild(node: Node, child: Node): void {
node.appendChild(child);
}
function parentNode(node: Node): Node | null {
return node.parentNode;
}
function nextSibling(node: Node): Node | null {
return node.nextSibling;
}
function tagName(elm: Element): string {
return elm.tagName;
}
function setTextContent(node: Node, text: string | null): void {
node.textContent = text;
}
function getTextContent(node: Node): string | null {
return node.textContent;
}
function isElement(node: Node): node is Element {
return node.nodeType === 1;
}
function isText(node: Node): node is Text {
return node.nodeType === 3;
}
function isComment(node: Node): node is Comment {
return node.nodeType === 8;
}
export const htmlDomApi = {
createElement,
createElementNS,
createTextNode,
createComment,
insertBefore,
removeChild,
appendChild,
parentNode,
nextSibling,
tagName,
setTextContent,
getTextContent,
isElement,
isText,
isComment,
} as DOMAPI;
export default htmlDomApi;
+4
View File
@@ -0,0 +1,4 @@
export const array = Array.isArray;
export function primitive(s: any): s is (string | number) {
return typeof s === 'string' || typeof s === 'number';
}
+64
View File
@@ -0,0 +1,64 @@
import {VNode, VNodeData} from '../vnode';
import {Module} from './module';
// because those in TypeScript are too restrictive: https://github.com/Microsoft/TSJS-lib-generator/pull/237
declare global {
interface Element {
setAttribute(name: string, value: string | number | boolean): void;
setAttributeNS(namespaceURI: string, qualifiedName: string, value: string | number | boolean): void;
}
}
export type Attrs = Record<string, string | number | boolean>
const xlinkNS = 'http://www.w3.org/1999/xlink';
const xmlNS = 'http://www.w3.org/XML/1998/namespace';
const colonChar = 58;
const xChar = 120;
function updateAttrs(oldVnode: VNode, vnode: VNode): void {
var key: string, elm: Element = vnode.elm as Element,
oldAttrs = (oldVnode.data as VNodeData).attrs,
attrs = (vnode.data as VNodeData).attrs;
if (!oldAttrs && !attrs) return;
if (oldAttrs === attrs) return;
oldAttrs = oldAttrs || {};
attrs = attrs || {};
// update modified attributes, add new attributes
for (key in attrs) {
const cur = attrs[key];
const old = oldAttrs[key];
if (old !== cur) {
if (cur === true) {
elm.setAttribute(key, "");
} else if (cur === false) {
elm.removeAttribute(key);
} else {
if (key.charCodeAt(0) !== xChar) {
elm.setAttribute(key, cur);
} else if (key.charCodeAt(3) === colonChar) {
// Assume xml namespace
elm.setAttributeNS(xmlNS, key, cur);
} else if (key.charCodeAt(5) === colonChar) {
// Assume xlink namespace
elm.setAttributeNS(xlinkNS, key, cur);
} else {
elm.setAttribute(key, cur);
}
}
}
}
// remove removed attributes
// use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value)
// the other option is to remove all attributes with value == undefined
for (key in oldAttrs) {
if (!(key in attrs)) {
elm.removeAttribute(key);
}
}
}
export const attributesModule = {create: updateAttrs, update: updateAttrs} as Module;
export default attributesModule;
+30
View File
@@ -0,0 +1,30 @@
import {VNode, VNodeData} from '../vnode';
import {Module} from './module';
export type Classes = Record<string, boolean>
function updateClass(oldVnode: VNode, vnode: VNode): void {
var cur: any, name: string, elm: Element = vnode.elm as Element,
oldClass = (oldVnode.data as VNodeData).class,
klass = (vnode.data as VNodeData).class;
if (!oldClass && !klass) return;
if (oldClass === klass) return;
oldClass = oldClass || {};
klass = klass || {};
for (name in oldClass) {
if (!klass[name]) {
elm.classList.remove(name);
}
}
for (name in klass) {
cur = klass[name];
if (cur !== oldClass[name]) {
(elm.classList as any)[cur ? 'add' : 'remove'](name);
}
}
}
export const classModule = {create: updateClass, update: updateClass} as Module;
export default classModule;
+43
View File
@@ -0,0 +1,43 @@
import {VNode, VNodeData} from '../vnode';
import {Module} from './module';
export type Dataset = Record<string, string>;
const CAPS_REGEX = /[A-Z]/g;
function updateDataset(oldVnode: VNode, vnode: VNode): void {
let elm: HTMLElement = vnode.elm as HTMLElement,
oldDataset = (oldVnode.data as VNodeData).dataset,
dataset = (vnode.data as VNodeData).dataset,
key: string;
if (!oldDataset && !dataset) return;
if (oldDataset === dataset) return;
oldDataset = oldDataset || {};
dataset = dataset || {};
const d = elm.dataset;
for (key in oldDataset) {
if (!dataset[key]) {
if (d) {
if (key in d) {
delete d[key];
}
} else {
elm.removeAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase());
}
}
}
for (key in dataset) {
if (oldDataset[key] !== dataset[key]) {
if (d) {
d[key] = dataset[key];
} else {
elm.setAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase(), dataset[key]);
}
}
}
}
export const datasetModule = {create: updateDataset, update: updateDataset} as Module;
export default datasetModule;
+111
View File
@@ -0,0 +1,111 @@
import {VNode, VNodeData} from '../vnode';
import {Module} from './module';
export type On = {
[N in keyof HTMLElementEventMap]?: (ev: HTMLElementEventMap[N]) => void
} & {
[event: string]: EventListener
};
function invokeHandler(handler: any, vnode?: VNode, event?: Event): void {
if (typeof handler === "function") {
// call function handler
handler.call(vnode, event, vnode);
} else if (typeof handler === "object") {
// call handler with arguments
if (typeof handler[0] === "function") {
// special case for single argument for performance
if (handler.length === 2) {
handler[0].call(vnode, handler[1], event, vnode);
} else {
var args = handler.slice(1);
args.push(event);
args.push(vnode);
handler[0].apply(vnode, args);
}
} else {
// call multiple handlers
for (var i = 0; i < handler.length; i++) {
invokeHandler(handler[i], vnode, event);
}
}
}
}
function handleEvent(event: Event, vnode: VNode) {
var name = event.type,
on = (vnode.data as VNodeData).on;
// call event handler(s) if exists
if (on && on[name]) {
invokeHandler(on[name], vnode, event);
}
}
function createListener() {
return function handler(event: Event) {
handleEvent(event, (handler as any).vnode);
}
}
function updateEventListeners(oldVnode: VNode, vnode?: VNode): void {
var oldOn = (oldVnode.data as VNodeData).on,
oldListener = (oldVnode as any).listener,
oldElm: Element = oldVnode.elm as Element,
on = vnode && (vnode.data as VNodeData).on,
elm: Element = (vnode && vnode.elm) as Element,
name: string;
// optimization for reused immutable handlers
if (oldOn === on) {
return;
}
// remove existing listeners which no longer used
if (oldOn && oldListener) {
// if element changed or deleted we remove all existing listeners unconditionally
if (!on) {
for (name in oldOn) {
// remove listener if element was changed or existing listeners removed
oldElm.removeEventListener(name, oldListener, false);
}
} else {
for (name in oldOn) {
// remove listener if existing listener removed
if (!on[name]) {
oldElm.removeEventListener(name, oldListener, false);
}
}
}
}
// add new listeners which has not already attached
if (on) {
// reuse existing listener or create new
var listener = (vnode as any).listener = (oldVnode as any).listener || createListener();
// update vnode for listener
listener.vnode = vnode;
// if element changed or added we add all needed listeners unconditionally
if (!oldOn) {
for (name in on) {
// add listener if element was changed or new listeners added
elm.addEventListener(name, listener, false);
}
} else {
for (name in on) {
// add listener if new listener added
if (!oldOn[name]) {
elm.addEventListener(name, listener, false);
}
}
}
}
}
export const eventListenersModule = {
create: updateEventListeners,
update: updateEventListeners,
destroy: updateEventListeners
} as Module;
export default eventListenersModule;
+165
View File
@@ -0,0 +1,165 @@
import {VNode, VNodeData} from '../vnode';
import {Module} from './module';
export type Hero = { id: string }
var raf = (typeof window !== 'undefined' && window.requestAnimationFrame) || setTimeout;
var nextFrame = function(fn: any) { raf(function() { raf(fn); }); };
function setNextFrame(obj: any, prop: string, val: any): void {
nextFrame(function() { obj[prop] = val; });
}
function getTextNodeRect(textNode: Text): ClientRect | undefined {
var rect: ClientRect | undefined;
if (document.createRange) {
var range = document.createRange();
range.selectNodeContents(textNode);
if (range.getBoundingClientRect) {
rect = range.getBoundingClientRect();
}
}
return rect;
}
function calcTransformOrigin(isTextNode: boolean,
textRect: ClientRect | undefined,
boundingRect: ClientRect): string {
if (isTextNode) {
if (textRect) {
//calculate pixels to center of text from left edge of bounding box
var relativeCenterX = textRect.left + textRect.width/2 - boundingRect.left;
var relativeCenterY = textRect.top + textRect.height/2 - boundingRect.top;
return relativeCenterX + 'px ' + relativeCenterY + 'px';
}
}
return '0 0'; //top left
}
function getTextDx(oldTextRect: ClientRect | undefined,
newTextRect: ClientRect | undefined): number {
if (oldTextRect && newTextRect) {
return ((oldTextRect.left + oldTextRect.width/2) - (newTextRect.left + newTextRect.width/2));
}
return 0;
}
function getTextDy(oldTextRect: ClientRect | undefined,
newTextRect: ClientRect | undefined): number {
if (oldTextRect && newTextRect) {
return ((oldTextRect.top + oldTextRect.height/2) - (newTextRect.top + newTextRect.height/2));
}
return 0;
}
function isTextElement(elm: Element | Text): elm is Text {
return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3;
}
var removed: any, created: any;
function pre() {
removed = {};
created = [];
}
function create(oldVnode: VNode, vnode: VNode): void {
var hero = (vnode.data as VNodeData).hero;
if (hero && hero.id) {
created.push(hero.id);
created.push(vnode);
}
}
function destroy(vnode: VNode): void {
var hero = (vnode.data as VNodeData).hero;
if (hero && hero.id) {
var elm = vnode.elm;
(vnode as any).isTextNode = isTextElement(elm as Element | Text); //is this a text node?
(vnode as any).boundingRect = (elm as Element).getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode
(vnode as any).textRect = (vnode as any).isTextNode ? getTextNodeRect((elm as Element).childNodes[0] as Text) : null; //save bounding rect of inner text node
var computedStyle = window.getComputedStyle(elm as Element, void 0); //get current styles (includes inherited properties)
(vnode as any).savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values
removed[hero.id] = vnode;
}
}
function post() {
var i: number, id: any, newElm: Element, oldVnode: VNode, oldElm: Element,
hRatio: number, wRatio: number,
oldRect: ClientRect, newRect: ClientRect, dx: number, dy: number,
origTransform: string | null, origTransition: string | null,
newStyle: CSSStyleDeclaration, oldStyle: CSSStyleDeclaration,
newComputedStyle: CSSStyleDeclaration, isTextNode: boolean,
newTextRect: ClientRect | undefined, oldTextRect: ClientRect | undefined;
for (i = 0; i < created.length; i += 2) {
id = created[i];
newElm = created[i+1].elm;
oldVnode = removed[id];
if (oldVnode) {
isTextNode = (oldVnode as any).isTextNode && isTextElement(newElm); //Are old & new both text?
newStyle = (newElm as HTMLElement).style;
newComputedStyle = window.getComputedStyle(newElm, void 0); //get full computed style for new element
oldElm = oldVnode.elm as Element;
oldStyle = (oldElm as HTMLElement).style;
//Overall element bounding boxes
newRect = newElm.getBoundingClientRect();
oldRect = (oldVnode as any).boundingRect; //previously saved bounding rect
//Text node bounding boxes & distances
if (isTextNode) {
newTextRect = getTextNodeRect(newElm.childNodes[0] as Text);
oldTextRect = (oldVnode as any).textRect;
dx = getTextDx(oldTextRect, newTextRect);
dy = getTextDy(oldTextRect, newTextRect);
} else {
//Calculate distances between old & new positions
dx = oldRect.left - newRect.left;
dy = oldRect.top - newRect.top;
}
hRatio = newRect.height / (Math.max(oldRect.height, 1));
wRatio = isTextNode ? hRatio : newRect.width / (Math.max(oldRect.width, 1)); //text scales based on hRatio
// Animate new element
origTransform = newStyle.transform;
origTransition = newStyle.transition;
if (newComputedStyle.display === 'inline') //inline elements cannot be transformed
newStyle.display = 'inline-block'; //this does not appear to have any negative side effects
newStyle.transition = origTransition + 'transform 0s';
newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect);
newStyle.opacity = '0';
newStyle.transform = origTransform + 'translate('+dx+'px, '+dy+'px) ' +
'scale('+1/wRatio+', '+1/hRatio+')';
setNextFrame(newStyle, 'transition', origTransition);
setNextFrame(newStyle, 'transform', origTransform);
setNextFrame(newStyle, 'opacity', '1');
// Animate old element
for (var key in (oldVnode as any).savedStyle) { //re-apply saved inherited properties
if (parseInt(key) != key as any as number) {
var ms = key.substring(0,2) === 'ms';
var moz = key.substring(0,3) === 'moz';
var webkit = key.substring(0,6) === 'webkit';
if (!ms && !moz && !webkit) //ignore prefixed style properties
(oldStyle as any)[key] = (oldVnode as any).savedStyle[key];
}
}
oldStyle.position = 'absolute';
oldStyle.top = oldRect.top + 'px'; //start at existing position
oldStyle.left = oldRect.left + 'px';
oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents
oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents
oldStyle.margin = '0'; //Margin on hero element leads to incorrect positioning
oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect);
oldStyle.transform = '';
oldStyle.opacity = '1';
document.body.appendChild(oldElm);
setNextFrame(oldStyle, 'transform', 'translate('+ -dx +'px, '+ -dy +'px) scale('+wRatio+', '+hRatio+')'); //scale must be on far right for translate to be correct
setNextFrame(oldStyle, 'opacity', '0');
oldElm.addEventListener('transitionend', function (ev: TransitionEvent) {
if (ev.propertyName === 'transform')
document.body.removeChild(ev.target as Node);
});
}
}
removed = created = undefined;
}
export const heroModule = {pre, create, destroy, post} as Module;
export default heroModule;
+10
View File
@@ -0,0 +1,10 @@
import {PreHook, CreateHook, UpdateHook, DestroyHook, RemoveHook, PostHook} from '../hooks';
export interface Module {
pre: PreHook;
create: CreateHook;
update: UpdateHook;
destroy: DestroyHook;
remove: RemoveHook;
post: PostHook;
}
+31
View File
@@ -0,0 +1,31 @@
import {VNode, VNodeData} from '../vnode';
import {Module} from './module';
export type Props = Record<string, any>;
function updateProps(oldVnode: VNode, vnode: VNode): void {
var key: string, cur: any, old: any, elm = vnode.elm,
oldProps = (oldVnode.data as VNodeData).props,
props = (vnode.data as VNodeData).props;
if (!oldProps && !props) return;
if (oldProps === props) return;
oldProps = oldProps || {};
props = props || {};
for (key in oldProps) {
if (!props[key]) {
delete (elm as any)[key];
}
}
for (key in props) {
cur = props[key];
old = oldProps[key];
if (old !== cur && (key !== 'value' || (elm as any)[key] !== cur)) {
(elm as any)[key] = cur;
}
}
}
export const propsModule = {create: updateProps, update: updateProps} as Module;
export default propsModule;
+103
View File
@@ -0,0 +1,103 @@
import {VNode, VNodeData} from '../vnode';
import {Module} from './module';
export type VNodeStyle = Record<string, string> & {
delayed?: Record<string, string>
remove?: Record<string, string>
}
// Bindig `requestAnimationFrame` like this fixes a bug in IE/Edge. See #360 and #409.
var raf = (typeof window !== 'undefined' && (window.requestAnimationFrame).bind(window)) || setTimeout;
var nextFrame = function(fn: any) { raf(function() { raf(fn); }); };
var reflowForced = false;
function setNextFrame(obj: any, prop: string, val: any): void {
nextFrame(function() { obj[prop] = val; });
}
function updateStyle(oldVnode: VNode, vnode: VNode): void {
var cur: any, name: string, elm = vnode.elm,
oldStyle = (oldVnode.data as VNodeData).style,
style = (vnode.data as VNodeData).style;
if (!oldStyle && !style) return;
if (oldStyle === style) return;
oldStyle = oldStyle || {} as VNodeStyle;
style = style || {} as VNodeStyle;
var oldHasDel = 'delayed' in oldStyle;
for (name in oldStyle) {
if (!style[name]) {
if (name[0] === '-' && name[1] === '-') {
(elm as any).style.removeProperty(name);
} else {
(elm as any).style[name] = '';
}
}
}
for (name in style) {
cur = style[name];
if (name === 'delayed' && style.delayed) {
for (let name2 in style.delayed) {
cur = style.delayed[name2];
if (!oldHasDel || cur !== (oldStyle.delayed as any)[name2]) {
setNextFrame((elm as any).style, name2, cur);
}
}
} else if (name !== 'remove' && cur !== oldStyle[name]) {
if (name[0] === '-' && name[1] === '-') {
(elm as any).style.setProperty(name, cur);
} else {
(elm as any).style[name] = cur;
}
}
}
}
function applyDestroyStyle(vnode: VNode): void {
var style: any, name: string, elm = vnode.elm, s = (vnode.data as VNodeData).style;
if (!s || !(style = s.destroy)) return;
for (name in style) {
(elm as any).style[name] = style[name];
}
}
function applyRemoveStyle(vnode: VNode, rm: () => void): void {
var s = (vnode.data as VNodeData).style;
if (!s || !s.remove) {
rm();
return;
}
if(!reflowForced) {
getComputedStyle(document.body).transform;
reflowForced = true;
}
var name: string, elm = vnode.elm, i = 0, compStyle: CSSStyleDeclaration,
style = s.remove, amount = 0, applied: Array<string> = [];
for (name in style) {
applied.push(name);
(elm as any).style[name] = style[name];
}
compStyle = getComputedStyle(elm as Element);
var props = (compStyle as any)['transition-property'].split(', ');
for (; i < props.length; ++i) {
if(applied.indexOf(props[i]) !== -1) amount++;
}
(elm as Element).addEventListener('transitionend', function (ev: TransitionEvent) {
if (ev.target === elm) --amount;
if (amount === 0) rm();
});
}
function forceReflow() {
reflowForced = false;
}
export const styleModule = {
pre: forceReflow,
create: updateStyle,
update: updateStyle,
destroy: applyDestroyStyle,
remove: applyRemoveStyle
} as Module;
export default styleModule;
+16
View File
@@ -0,0 +1,16 @@
import {init} from './snabbdom';
import {attributesModule} from './modules/attributes'; // for setting attributes on DOM elements
import {classModule} from './modules/class'; // makes it easy to toggle classes
import {propsModule} from './modules/props'; // for setting properties on DOM elements
import {styleModule} from './modules/style'; // handles styling on elements with support for animations
import {eventListenersModule} from './modules/eventlisteners'; // attaches event listeners
import {h} from './h'; // helper function for creating vnodes
var patch = init([ // Init patch function with choosen modules
attributesModule,
classModule,
propsModule,
styleModule,
eventListenersModule
]) as (oldVNode: any, vnode: any) => any;
export const snabbdomBundle = { patch, h: h as any };
export default snabbdomBundle;
+318
View File
@@ -0,0 +1,318 @@
/* global module, document, Node */
import {Module} from './modules/module';
import {Hooks} from './hooks';
import vnode, {VNode, VNodeData, Key} from './vnode';
import * as is from './is';
import htmlDomApi, {DOMAPI} from './htmldomapi';
function isUndef(s: any): boolean { return s === undefined; }
function isDef(s: any): boolean { return s !== undefined; }
type VNodeQueue = Array<VNode>;
const emptyNode = vnode('', {}, [], undefined, undefined);
function sameVnode(vnode1: VNode, vnode2: VNode): boolean {
return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel;
}
function isVnode(vnode: any): vnode is VNode {
return vnode.sel !== undefined;
}
type KeyToIndexMap = {[key: string]: number};
type ArraysOf<T> = {
[K in keyof T]: (T[K])[];
}
type ModuleHooks = ArraysOf<Module>;
function createKeyToOldIdx(children: Array<VNode>, beginIdx: number, endIdx: number): KeyToIndexMap {
let i: number, map: KeyToIndexMap = {}, key: Key | undefined, ch;
for (i = beginIdx; i <= endIdx; ++i) {
ch = children[i];
if (ch != null) {
key = ch.key;
if (key !== undefined) map[key] = i;
}
}
return map;
}
const hooks: (keyof Module)[] = ['create', 'update', 'remove', 'destroy', 'pre', 'post'];
export {h} from './h';
export {thunk} from './thunk';
export function init(modules: Array<Partial<Module>>, domApi?: DOMAPI) {
let i: number, j: number, cbs = ({} as ModuleHooks);
const api: DOMAPI = domApi !== undefined ? domApi : htmlDomApi;
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
const hook = modules[j][hooks[i]];
if (hook !== undefined) {
(cbs[hooks[i]] as Array<any>).push(hook);
}
}
}
function emptyNodeAt(elm: Element) {
const id = elm.id ? '#' + elm.id : '';
const c = elm.className ? '.' + elm.className.split(' ').join('.') : '';
return vnode(api.tagName(elm).toLowerCase() + id + c, {}, [], undefined, elm);
}
function createRmCb(childElm: Node, listeners: number) {
return function rmCb() {
if (--listeners === 0) {
const parent = api.parentNode(childElm);
api.removeChild(parent, childElm);
}
};
}
function createElm(vnode: VNode, insertedVnodeQueue: VNodeQueue): Node {
let i: any, data = vnode.data;
if (data !== undefined) {
if (isDef(i = data.hook) && isDef(i = i.init)) {
i(vnode);
data = vnode.data;
}
}
let children = vnode.children, sel = vnode.sel;
if (sel === '!') {
if (isUndef(vnode.text)) {
vnode.text = '';
}
vnode.elm = api.createComment(vnode.text as string);
} else if (sel !== undefined) {
// Parse selector
const hashIdx = sel.indexOf('#');
const dotIdx = sel.indexOf('.', hashIdx);
const hash = hashIdx > 0 ? hashIdx : sel.length;
const dot = dotIdx > 0 ? dotIdx : sel.length;
const tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel;
const elm = vnode.elm = isDef(data) && isDef(i = (data as VNodeData).ns) ? api.createElementNS(i, tag)
: api.createElement(tag);
if (hash < dot) elm.setAttribute('id', sel.slice(hash + 1, dot));
if (dotIdx > 0) elm.setAttribute('class', sel.slice(dot + 1).replace(/\./g, ' '));
for (i = 0; i < cbs.create.length; ++i) cbs.create[i](emptyNode, vnode);
if (is.array(children)) {
for (i = 0; i < children.length; ++i) {
const ch = children[i];
if (ch != null) {
api.appendChild(elm, createElm(ch as VNode, insertedVnodeQueue));
}
}
} else if (is.primitive(vnode.text)) {
api.appendChild(elm, api.createTextNode(vnode.text));
}
i = (vnode.data as VNodeData).hook; // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode);
if (i.insert) insertedVnodeQueue.push(vnode);
}
} else {
vnode.elm = api.createTextNode(vnode.text as string);
}
return vnode.elm;
}
function addVnodes(parentElm: Node,
before: Node | null,
vnodes: Array<VNode>,
startIdx: number,
endIdx: number,
insertedVnodeQueue: VNodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx];
if (ch != null) {
api.insertBefore(parentElm, createElm(ch, insertedVnodeQueue), before);
}
}
}
function invokeDestroyHook(vnode: VNode) {
let i: any, j: number, data = vnode.data;
if (data !== undefined) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode);
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
if (vnode.children !== undefined) {
for (j = 0; j < vnode.children.length; ++j) {
i = vnode.children[j];
if (i != null && typeof i !== "string") {
invokeDestroyHook(i);
}
}
}
}
}
function removeVnodes(parentElm: Node,
vnodes: Array<VNode>,
startIdx: number,
endIdx: number): void {
for (; startIdx <= endIdx; ++startIdx) {
let i: any, listeners: number, rm: () => void, ch = vnodes[startIdx];
if (ch != null) {
if (isDef(ch.sel)) {
invokeDestroyHook(ch);
listeners = cbs.remove.length + 1;
rm = createRmCb(ch.elm as Node, listeners);
for (i = 0; i < cbs.remove.length; ++i) cbs.remove[i](ch, rm);
if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) {
i(ch, rm);
} else {
rm();
}
} else { // Text node
api.removeChild(parentElm, ch.elm as Node);
}
}
}
}
function updateChildren(parentElm: Node,
oldCh: Array<VNode>,
newCh: Array<VNode>,
insertedVnodeQueue: VNodeQueue) {
let oldStartIdx = 0, newStartIdx = 0;
let oldEndIdx = oldCh.length - 1;
let oldStartVnode = oldCh[0];
let oldEndVnode = oldCh[oldEndIdx];
let newEndIdx = newCh.length - 1;
let newStartVnode = newCh[0];
let newEndVnode = newCh[newEndIdx];
let oldKeyToIdx: any;
let idxInOld: number;
let elmToMove: VNode;
let before: any;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (oldStartVnode == null) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode might have been moved left
} else if (oldEndVnode == null) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (newStartVnode == null) {
newStartVnode = newCh[++newStartIdx];
} else if (newEndVnode == null) {
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
api.insertBefore(parentElm, oldStartVnode.elm as Node, api.nextSibling(oldEndVnode.elm as Node));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
api.insertBefore(parentElm, oldEndVnode.elm as Node, oldStartVnode.elm as Node);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (oldKeyToIdx === undefined) {
oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
}
idxInOld = oldKeyToIdx[newStartVnode.key as string];
if (isUndef(idxInOld)) { // New element
api.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm as Node);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
if (elmToMove.sel !== newStartVnode.sel) {
api.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm as Node);
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined as any;
api.insertBefore(parentElm, (elmToMove.elm as Node), oldStartVnode.elm as Node);
}
newStartVnode = newCh[++newStartIdx];
}
}
}
if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
if (oldStartIdx > oldEndIdx) {
before = newCh[newEndIdx+1] == null ? null : newCh[newEndIdx+1].elm;
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
}
function patchVnode(oldVnode: VNode, vnode: VNode, insertedVnodeQueue: VNodeQueue) {
let i: any, hook: any;
if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode);
}
const elm = vnode.elm = (oldVnode.elm as Node);
let oldCh = oldVnode.children;
let ch = vnode.children;
if (oldVnode === vnode) return;
if (vnode.data !== undefined) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
i = vnode.data.hook;
if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode);
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh as Array<VNode>, ch as Array<VNode>, insertedVnodeQueue);
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) api.setTextContent(elm, '');
addVnodes(elm, null, ch as Array<VNode>, 0, (ch as Array<VNode>).length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh as Array<VNode>, 0, (oldCh as Array<VNode>).length - 1);
} else if (isDef(oldVnode.text)) {
api.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
if (isDef(oldCh)) {
removeVnodes(elm, oldCh as Array<VNode>, 0, (oldCh as Array<VNode>).length - 1);
}
api.setTextContent(elm, vnode.text as string);
}
if (isDef(hook) && isDef(i = hook.postpatch)) {
i(oldVnode, vnode);
}
}
return function patch(oldVnode: VNode | Element, vnode: VNode): VNode {
let i: number, elm: Node, parent: Node;
const insertedVnodeQueue: VNodeQueue = [];
for (i = 0; i < cbs.pre.length; ++i) cbs.pre[i]();
if (!isVnode(oldVnode)) {
oldVnode = emptyNodeAt(oldVnode);
}
if (sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue);
} else {
elm = oldVnode.elm as Node;
parent = api.parentNode(elm);
createElm(vnode, insertedVnodeQueue);
if (parent !== null) {
api.insertBefore(parent, vnode.elm as Node, api.nextSibling(elm));
removeVnodes(parent, [oldVnode], 0, 0);
}
}
for (i = 0; i < insertedVnodeQueue.length; ++i) {
(((insertedVnodeQueue[i].data as VNodeData).hook as Hooks).insert as any)(insertedVnodeQueue[i]);
}
for (i = 0; i < cbs.post.length; ++i) cbs.post[i]();
return vnode;
};
}
+64
View File
@@ -0,0 +1,64 @@
import {VNode, VNodeData} from './vnode';
import {h} from './h';
export interface ThunkData extends VNodeData {
fn: () => VNode;
args: Array<any>;
}
export interface Thunk extends VNode {
data: ThunkData;
}
export interface ThunkFn {
(sel: string, fn: Function, args: Array<any>): Thunk;
(sel: string, key: any, fn: Function, args: Array<any>): Thunk;
}
function copyToThunk(vnode: VNode, thunk: VNode): void {
thunk.elm = vnode.elm;
(vnode.data as VNodeData).fn = (thunk.data as VNodeData).fn;
(vnode.data as VNodeData).args = (thunk.data as VNodeData).args;
thunk.data = vnode.data;
thunk.children = vnode.children;
thunk.text = vnode.text;
thunk.elm = vnode.elm;
}
function init(thunk: VNode): void {
const cur = thunk.data as VNodeData;
const vnode = (cur.fn as any).apply(undefined, cur.args);
copyToThunk(vnode, thunk);
}
function prepatch(oldVnode: VNode, thunk: VNode): void {
let i: number, old = oldVnode.data as VNodeData, cur = thunk.data as VNodeData;
const oldArgs = old.args, args = cur.args;
if (old.fn !== cur.fn || (oldArgs as any).length !== (args as any).length) {
copyToThunk((cur.fn as any).apply(undefined, args), thunk);
return;
}
for (i = 0; i < (args as any).length; ++i) {
if ((oldArgs as any)[i] !== (args as any)[i]) {
copyToThunk((cur.fn as any).apply(undefined, args), thunk);
return;
}
}
copyToThunk(oldVnode, thunk);
}
export const thunk = function thunk(sel: string, key?: any, fn?: any, args?: any): VNode {
if (args === undefined) {
args = fn;
fn = key;
key = undefined;
}
return h(sel, {
key: key,
hook: {init: init, prepatch: prepatch},
fn: fn,
args: args
});
} as ThunkFn;
export default thunk;
+39
View File
@@ -0,0 +1,39 @@
import vnode, {VNode} from './vnode';
import htmlDomApi, {DOMAPI} from './htmldomapi';
export function toVNode(node: Node, domApi?: DOMAPI): VNode {
const api: DOMAPI = domApi !== undefined ? domApi : htmlDomApi;
let text: string;
if (api.isElement(node)) {
const id = node.id ? '#' + node.id : '';
const cn = node.getAttribute('class');
const c = cn ? '.' + cn.split(' ').join('.') : '';
const sel = api.tagName(node).toLowerCase() + id + c;
const attrs: any = {};
const children: Array<VNode> = [];
let name: string;
let i: number, n: number;
const elmAttrs = node.attributes;
const elmChildren = node.childNodes;
for (i = 0, n = elmAttrs.length; i < n; i++) {
name = elmAttrs[i].nodeName;
if (name !== 'id' && name !== 'class') {
attrs[name] = elmAttrs[i].nodeValue;
}
}
for (i = 0, n = elmChildren.length; i < n; i++) {
children.push(toVNode(elmChildren[i], domApi));
}
return vnode(sel, {attrs}, children, undefined, node);
} else if (api.isText(node)) {
text = api.getTextContent(node) as string;
return vnode(undefined, undefined, undefined, text, node);
} else if (api.isComment(node)) {
text = api.getTextContent(node) as string;
return vnode('!', {}, [], text, node as any);
} else {
return vnode('', {}, [], undefined, node as any);
}
}
export default toVNode;
+49
View File
@@ -0,0 +1,49 @@
import {Hooks} from './hooks';
import {AttachData} from './helpers/attachto'
import {VNodeStyle} from './modules/style'
import {On} from './modules/eventlisteners'
import {Attrs} from './modules/attributes'
import {Classes} from './modules/class'
import {Props} from './modules/props'
import {Dataset} from './modules/dataset'
import {Hero} from './modules/hero'
export type Key = string | number;
export interface VNode {
sel: string | undefined;
data: VNodeData | undefined;
children: Array<VNode | string> | undefined;
elm: Node | undefined;
text: string | undefined;
key: Key | undefined;
}
export interface VNodeData {
props?: Props;
attrs?: Attrs;
class?: Classes;
style?: VNodeStyle;
dataset?: Dataset;
on?: On;
hero?: Hero;
attachData?: AttachData;
hook?: Hooks;
key?: Key;
ns?: string; // for SVGs
fn?: () => VNode; // for thunks
args?: Array<any>; // for thunks
[key: string]: any; // for any other 3rd party module
}
export function vnode(sel: string | undefined,
data: any | undefined,
children: Array<VNode | string> | undefined,
text: string | undefined,
elm: Element | Text | undefined): VNode {
let key = data === undefined ? undefined : data.key;
return {sel: sel, data: data, children: children,
text: text, elm: elm, key: key};
}
export default vnode;
+98
View File
@@ -0,0 +1,98 @@
var assert = require('assert');
var snabbdom = require('../snabbdom');
var patch = snabbdom.init([]);
var attachTo = require('../helpers/attachto').default;
var h = require('../h').default;
describe('attachTo', function() {
var elm, vnode0;
beforeEach(function() {
elm = document.createElement('div');
vnode0 = elm;
});
it('adds element to target', function() {
var vnode1 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
attachTo(elm, h('div#attached', 'Test')),
]),
]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.children.length, 2);
});
it('updates element at target', function() {
var vnode1 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
attachTo(elm, h('div#attached', 'First text')),
]),
]);
var vnode2 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
attachTo(elm, h('div#attached', 'New text')),
]),
]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.children[0].innerHTML, 'First text');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.children[0].innerHTML, 'New text');
});
it('element can be inserted before modal', function() {
var vnode1 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
attachTo(elm, h('div#attached', 'Text')),
]),
]);
var vnode2 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
h('div', 'A new element'),
attachTo(elm, h('div#attached', 'Text')),
]),
]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.children[0].innerHTML, 'Text');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.children[0].innerHTML, 'Text');
});
it('removes element at target', function() {
var vnode1 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
attachTo(elm, h('div#attached', 'First text')),
]),
]);
var vnode2 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
]),
]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.children[0].innerHTML, 'First text');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.children.length, 1);
});
it('remove hook receives real element', function() {
function rm(vnode, cb) {
assert.equal(vnode.elm.tagName, 'DIV');
assert.equal(vnode.elm.innerHTML, 'First text');
cb();
}
var vnode1 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
attachTo(elm, h('div#attached', {hook: {remove: rm}}, 'First text')),
]),
]);
var vnode2 = h('div', [
h('div#wrapper', [
h('div', 'Some element'),
]),
]);
elm = patch(vnode0, vnode1).elm;
elm = patch(vnode1, vnode2).elm;
});
});
+97
View File
@@ -0,0 +1,97 @@
var assert = require('assert');
var snabbdom = require('../snabbdom');
var patch = snabbdom.init([
require('../modules/attributes').default,
]);
var h = require('../h').default;
describe('attributes', function() {
var elm, vnode0;
beforeEach(function() {
elm = document.createElement('div');
vnode0 = elm;
});
it('have their provided values', function() {
var vnode1 = h('div', {attrs: {href: '/foo', minlength: 1, selected: true, disabled: false}});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.getAttribute('href'), '/foo');
assert.strictEqual(elm.getAttribute('minlength'), '1');
assert.strictEqual(elm.hasAttribute('selected'), true);
assert.strictEqual(elm.getAttribute('selected'), '');
assert.strictEqual(elm.hasAttribute('disabled'), false);
});
it('can be memoized', function() {
var cachedAttrs = {href: '/foo', minlength: 1, selected: true};
var vnode1 = h('div', {attrs: cachedAttrs});
var vnode2 = h('div', {attrs: cachedAttrs});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.getAttribute('href'), '/foo');
assert.strictEqual(elm.getAttribute('minlength'), '1');
assert.strictEqual(elm.getAttribute('selected'), '');
elm = patch(vnode1, vnode2).elm;
assert.strictEqual(elm.getAttribute('href'), '/foo');
assert.strictEqual(elm.getAttribute('minlength'), '1');
assert.strictEqual(elm.getAttribute('selected'), '');
});
it('are not omitted when falsy values are provided', function() {
var vnode1 = h('div', {attrs: {href: null, minlength: 0, value: '', title:'undefined'}});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.getAttribute('href'), 'null');
assert.strictEqual(elm.getAttribute('minlength'), '0');
assert.strictEqual(elm.getAttribute('value'), '');
assert.strictEqual(elm.getAttribute('title'), 'undefined');
});
it('are set correctly when namespaced', function() {
var vnode1 = h('div', {attrs: {'xlink:href': '#foo'}});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.getAttributeNS('http://www.w3.org/1999/xlink', 'href'), '#foo');
});
it('should not touch class nor id fields', function() {
elm = document.createElement('div');
elm.id = 'myId';
elm.className = 'myClass';
vnode0 = elm;
var vnode1 = h('div#myId.myClass', {attrs: {}}, ['Hello']);
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.tagName, 'DIV');
assert.strictEqual(elm.id, 'myId');
assert.strictEqual(elm.className, 'myClass');
assert.strictEqual(elm.textContent, 'Hello');
});
describe('boolean attribute', function() {
it('is present and empty string if the value is truthy', function() {
var vnode1 = h('div', {attrs: {required: true, readonly: 1, noresize: 'truthy'}});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.hasAttribute('required'), true);
assert.strictEqual(elm.getAttribute('required'), '');
assert.strictEqual(elm.hasAttribute('readonly'), true);
assert.strictEqual(elm.getAttribute('readonly'), '1');
assert.strictEqual(elm.hasAttribute('noresize'), true);
assert.strictEqual(elm.getAttribute('noresize'), 'truthy');
});
it('is omitted if the value is false', function() {
var vnode1 = h('div', {attrs: {required: false}});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.hasAttribute('required'), false);
assert.strictEqual(elm.getAttribute('required'), null);
});
it('is not omitted if the value is falsy but casted to string', function() {
var vnode1 = h('div', {attrs: {readonly: 0, noresize: null}});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.getAttribute('readonly'), '0');
assert.strictEqual(elm.getAttribute('noresize'), 'null');
});
});
describe('Object.prototype property', function() {
it('is not considered as a boolean attribute and shouldn\'t be omitted', function() {
var vnode1 = h('div', {attrs: {constructor: true}});
elm = patch(vnode0, vnode1).elm;
assert.strictEqual(elm.hasAttribute('constructor'), true);
assert.strictEqual(elm.getAttribute('constructor'), '');
var vnode2 = h('div', {attrs: {constructor: false}});
elm = patch(vnode0, vnode2).elm;
assert.strictEqual(elm.hasAttribute('constructor'), false);
});
});
});
+1114
View File
File diff suppressed because it is too large Load Diff
+56
View File
@@ -0,0 +1,56 @@
var assert = require('assert');
var fakeRaf = require('fake-raf');
var snabbdom = require('../snabbdom');
fakeRaf.use();
var patch = snabbdom.init([
require('../modules/dataset').default,
]);
var h = require('../h').default;
describe('dataset', function() {
var elm, vnode0;
beforeEach(function() {
elm = document.createElement('div');
vnode0 = elm;
});
it('is set on initial element creation', function() {
elm = patch(vnode0, h('div', {dataset: {foo: 'foo'}})).elm;
assert.equal(elm.dataset.foo, 'foo');
});
it('updates dataset', function() {
var vnode1 = h('i', {dataset: {foo: 'foo', bar: 'bar'}});
var vnode2 = h('i', {dataset: {baz: 'baz'}});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.dataset.foo, 'foo');
assert.equal(elm.dataset.bar, 'bar');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.dataset.baz, 'baz');
assert.equal(elm.dataset.foo, undefined);
});
it('can be memoized', function() {
var cachedDataset = {foo: 'foo', bar: 'bar'};
var vnode1 = h('i', {dataset: cachedDataset});
var vnode2 = h('i', {dataset: cachedDataset});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.dataset.foo, 'foo');
assert.equal(elm.dataset.bar, 'bar');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.dataset.foo, 'foo');
assert.equal(elm.dataset.bar, 'bar');
});
it('handles string conversions', function() {
var vnode1 = h('i', {dataset: {empty: '', dash: '-', dashed:'foo-bar', camel: 'fooBar', integer:0, float:0.1}});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.dataset.empty, '');
assert.equal(elm.dataset.dash, '-');
assert.equal(elm.dataset.dashed, 'foo-bar');
assert.equal(elm.dataset.camel, 'fooBar');
assert.equal(elm.dataset.integer, '0');
assert.equal(elm.dataset.float, '0.1');
});
});
fakeRaf.restore();
+178
View File
@@ -0,0 +1,178 @@
var assert = require('assert');
var snabbdom = require('../snabbdom');
var patch = snabbdom.init([
require('../modules/eventlisteners.js').default,
]);
var h = require('../h').default;
describe('event listeners', function() {
var elm, vnode0;
beforeEach(function() {
elm = document.createElement('div');
vnode0 = elm;
});
it('attaches click event handler to element', function() {
var result = [];
function clicked(ev) { result.push(ev); }
var vnode = h('div', {on: {click: clicked}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode).elm;
elm.click();
assert.equal(1, result.length);
});
it('does not attach new listener', function() {
var result = [];
//function clicked(ev) { result.push(ev); }
var vnode1 = h('div', {on: {click: function(ev) { result.push(1); }}}, [
h('a', 'Click my parent'),
]);
var vnode2 = h('div', {on: {click: function(ev) { result.push(2); }}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
elm = patch(vnode1, vnode2).elm;
elm.click();
assert.deepEqual(result, [1, 2]);
});
it('does calls handler for function in array', function() {
var result = [];
function clicked(ev) { result.push(ev); }
var vnode = h('div', {on: {click: [clicked, 1]}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode).elm;
elm.click();
assert.deepEqual(result, [1]);
});
it('handles changed value in array', function() {
var result = [];
function clicked(ev) { result.push(ev); }
var vnode1 = h('div', {on: {click: [clicked, 1]}}, [
h('a', 'Click my parent'),
]);
var vnode2 = h('div', {on: {click: [clicked, 2]}}, [
h('a', 'Click my parent'),
]);
var vnode3 = h('div', {on: {click: [clicked, 3]}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
elm = patch(vnode1, vnode2).elm;
elm.click();
elm = patch(vnode2, vnode3).elm;
elm.click();
assert.deepEqual(result, [1, 2, 3]);
});
it('handles changed several values in array', function() {
var result = [];
function clicked() { result.push([].slice.call(arguments, 0, arguments.length-2)); }
var vnode1 = h('div', {on: {click: [clicked, 1, 2, 3]}}, [
h('a', 'Click my parent'),
]);
var vnode2 = h('div', {on: {click: [clicked, 1, 2]}}, [
h('a', 'Click my parent'),
]);
var vnode3 = h('div', {on: {click: [clicked, 2, 3]}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
elm = patch(vnode1, vnode2).elm;
elm.click();
elm = patch(vnode2, vnode3).elm;
elm.click();
assert.deepEqual(result, [[1, 2, 3], [1, 2], [2, 3]]);
});
it('detach attached click event handler to element', function() {
var result = [];
function clicked(ev) { result.push(ev); }
var vnode1 = h('div', {on: {click: clicked}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
assert.equal(1, result.length);
var vnode2 = h('div', {on: {}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode1, vnode2).elm;
elm.click();
assert.equal(1, result.length);
});
it('multiple event handlers for same event on same element', function() {
var called = 0;
function clicked(ev, vnode) {
++called;
// Check that the first argument is an event
assert.equal(true, 'target' in ev);
// Check that the second argument was a vnode
assert.equal(vnode.sel, 'div');
}
var vnode1 = h('div', {on: {click: [[clicked], [clicked], [clicked]]}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
assert.equal(3, called);
var vnode2 = h('div', {on: {click: [[clicked], [clicked]]}}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode1, vnode2).elm;
elm.click();
assert.equal(5, called);
});
it('access to virtual node in event handler', function() {
var result = [];
function clicked(ev, vnode) { result.push(this); result.push(vnode); }
var vnode1 = h('div', {on: {click: clicked }}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
assert.equal(2, result.length);
assert.equal(vnode1, result[0]);
assert.equal(vnode1, result[1]);
}),
it('access to virtual node in event handler with argument', function() {
var result = [];
function clicked(arg, ev, vnode) { result.push(this); result.push(vnode); }
var vnode1 = h('div', {on: {click: [clicked, 1] }}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
assert.equal(2, result.length);
assert.equal(vnode1, result[0]);
assert.equal(vnode1, result[1]);
}),
it('access to virtual node in event handler with arguments', function() {
var result = [];
function clicked(arg1, arg2, ev, vnode) { result.push(this); result.push(vnode); }
var vnode1 = h('div', {on: {click: [clicked, 1, "2"] }}, [
h('a', 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
assert.equal(2, result.length);
assert.equal(vnode1, result[0]);
assert.equal(vnode1, result[1]);
});
it('shared handlers in parent and child nodes', function() {
var result = [];
var sharedHandlers = {
click: function(ev) { result.push(ev); }
};
var vnode1 = h('div', {on: sharedHandlers}, [
h('a', {on: sharedHandlers}, 'Click my parent'),
]);
elm = patch(vnode0, vnode1).elm;
elm.click();
assert.equal(1, result.length);
elm.firstChild.click();
assert.equal(3, result.length);
});
});
+53
View File
@@ -0,0 +1,53 @@
var assert = require('assert');
var snabbdom = require('../snabbdom');
var h = require('../h').default;
var patch = snabbdom.init([
require('../modules/attributes').default
]);
describe('svg', function () {
var elm, vnode0;
beforeEach(function() {
elm = document.createElement('svg');
vnode0 = elm;
});
it('removes child svg elements', function(){
var a = h('svg', {}, [
h('g'),
h('g')
]);
var b = h('svg', {}, [
h('g')
]);
var result = patch(patch(vnode0, a), b).elm;
assert.equal(result.childNodes.length, 1);
});
it('adds correctly xlink namespaced attribute', function(){
var xlinkNS = 'http://www.w3.org/1999/xlink';
var testUrl = '/test';
var a = h('svg', {}, [
h('use', {
attrs: { 'xlink:href': testUrl }
}, [])
]);
var result = patch(vnode0, a).elm;
assert.equal(result.childNodes.length, 1);
assert.equal(result.childNodes[0].getAttribute('xlink:href'), testUrl);
assert.equal(result.childNodes[0].getAttributeNS(xlinkNS,'href'), testUrl);
});
it('adds correctly xml namespaced attribute', function(){
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var testAttrValue = 'und';
var a = h('svg', { attrs: { 'xml:lang': testAttrValue } }, []);
var result = patch(vnode0, a).elm;
assert.equal(result.getAttributeNS(xmlNS, 'lang'), testAttrValue);
assert.equal(result.getAttribute('xml:lang'), testAttrValue);
});
})
+151
View File
@@ -0,0 +1,151 @@
var assert = require('assert');
var fakeRaf = require('fake-raf');
var snabbdom = require('../snabbdom');
fakeRaf.use();
var patch = snabbdom.init([
require('../modules/style').default,
]);
var h = require('../h').default;
var toVNode = require('../tovnode').default;
describe('style', function() {
var elm, vnode0;
beforeEach(function() {
elm = document.createElement('div');
vnode0 = elm;
});
it('is being styled', function() {
elm = patch(vnode0, h('div', {style: {fontSize: '12px'}})).elm;
assert.equal(elm.style.fontSize, '12px');
});
it('can be memoized', function() {
var cachedStyles = {fontSize: '14px', display: 'inline'};
var vnode1 = h('i', {style: cachedStyles});
var vnode2 = h('i', {style: cachedStyles});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.style.fontSize, '14px');
assert.equal(elm.style.display, 'inline');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.style.fontSize, '14px');
assert.equal(elm.style.display, 'inline');
});
it('updates styles', function() {
var vnode1 = h('i', {style: {fontSize: '14px', display: 'inline'}});
var vnode2 = h('i', {style: {fontSize: '12px', display: 'block'}});
var vnode3 = h('i', {style: {fontSize: '10px', display: 'block'}});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.style.fontSize, '14px');
assert.equal(elm.style.display, 'inline');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.style.fontSize, '12px');
assert.equal(elm.style.display, 'block');
elm = patch(vnode2, vnode3).elm;
assert.equal(elm.style.fontSize, '10px');
assert.equal(elm.style.display, 'block');
});
it('explicialy removes styles', function() {
var vnode1 = h('i', {style: {fontSize: '14px'}});
var vnode2 = h('i', {style: {fontSize: ''}});
var vnode3 = h('i', {style: {fontSize: '10px'}});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.style.fontSize, '14px');
patch(vnode1, vnode2);
assert.equal(elm.style.fontSize, '');
patch(vnode2, vnode3);
assert.equal(elm.style.fontSize, '10px');
});
it('implicially removes styles from element', function() {
var vnode1 = h('div', [h('i', {style: {fontSize: '14px'}})]);
var vnode2 = h('div', [h('i')]);
var vnode3 = h('div', [h('i', {style: {fontSize: '10px'}})]);
patch(vnode0, vnode1);
assert.equal(elm.firstChild.style.fontSize, '14px');
patch(vnode1, vnode2);
assert.equal(elm.firstChild.style.fontSize, '');
patch(vnode2, vnode3);
assert.equal(elm.firstChild.style.fontSize, '10px');
});
it('updates css variables', function() {
var vnode1 = h('div', {style: {'--myVar': 1}});
var vnode2 = h('div', {style: {'--myVar': 2}});
var vnode3 = h('div', {style: {'--myVar': 3}});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.style.getPropertyValue('--myVar'), 1);
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.style.getPropertyValue('--myVar'), 2);
elm = patch(vnode2, vnode3).elm;
assert.equal(elm.style.getPropertyValue('--myVar'), 3);
});
it('explicialy removes css variables', function() {
var vnode1 = h('i', {style: {'--myVar': 1}});
var vnode2 = h('i', {style: {'--myVar': ''}});
var vnode3 = h('i', {style: {'--myVar': 2}});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.style.getPropertyValue('--myVar'), 1);
patch(vnode1, vnode2);
assert.equal(elm.style.getPropertyValue('--myVar'), '');
patch(vnode2, vnode3);
assert.equal(elm.style.getPropertyValue('--myVar'), 2);
});
it('implicially removes css variables from element', function() {
var vnode1 = h('div', [h('i', {style: {'--myVar': 1}})]);
var vnode2 = h('div', [h('i')]);
var vnode3 = h('div', [h('i', {style: {'--myVar': 2}})]);
patch(vnode0, vnode1);
assert.equal(elm.firstChild.style.getPropertyValue('--myVar'), 1);
patch(vnode1, vnode2);
assert.equal(elm.firstChild.style.getPropertyValue('--myVar'), '');
patch(vnode2, vnode3);
assert.equal(elm.firstChild.style.getPropertyValue('--myVar'), 2);
});
it('updates delayed styles in next frame', function() {
var patch = snabbdom.init([
require('../modules/style').default,
]);
var vnode1 = h('i', {style: {fontSize: '14px', delayed: {fontSize: '16px'}}});
var vnode2 = h('i', {style: {fontSize: '18px', delayed: {fontSize: '20px'}}});
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.style.fontSize, '14px');
fakeRaf.step();
fakeRaf.step();
assert.equal(elm.style.fontSize, '16px');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.style.fontSize, '18px');
fakeRaf.step();
fakeRaf.step();
assert.equal(elm.style.fontSize, '20px');
});
it('applies tranform as transition on remove', function(done) {
var btn = h('button', { style: {
transition: 'transform 0.5s',
remove: { transform: 'translateY(100%)' }
}}, ['A button']);
var vnode1 = h('div.parent', {}, [btn]);
var vnode2 = h('div.parent', {}, [null]);
document.body.appendChild(vnode0);
patch(vnode0, vnode1);
patch(vnode1, vnode2);
assert.strictEqual(document.querySelectorAll('button').length, 1);
setTimeout(function () {
assert.strictEqual(document.querySelectorAll('button').length, 0);
done();
}, 700);
});
describe('using toVNode()', function () {
it('handles (ignoring) comment nodes', function() {
var comment = document.createComment('yolo');
var prevElm = document.createElement('div');
prevElm.appendChild(comment);
var nextVNode = h('div', [h('span', 'Hi')]);
elm = patch(toVNode(prevElm), nextVNode).elm;
assert.strictEqual(elm, prevElm);
assert.equal(elm.tagName, 'DIV');
assert.strictEqual(elm.childNodes.length, 1);
assert.strictEqual(elm.childNodes[0].tagName, 'SPAN');
assert.strictEqual(elm.childNodes[0].textContent, 'Hi');
});
});
});
fakeRaf.restore();
+232
View File
@@ -0,0 +1,232 @@
var assert = require('assert');
var snabbdom = require('../snabbdom');
var patch = snabbdom.init([
]);
var h = require('../h').default;
var thunk = require('../thunk').default;
describe('thunk', function() {
var elm, vnode0;
beforeEach(function() {
elm = vnode0 = document.createElement('div');
});
it('returns vnode with data and render function', function() {
function numberInSpan(n) {
return h('span', 'Number is ' + n);
}
var vnode = thunk('span', 'num', numberInSpan, [22]);
assert.deepEqual(vnode.sel, 'span');
assert.deepEqual(vnode.data.key, 'num');
assert.deepEqual(vnode.data.args, [22]);
});
it('calls render function once on data change', function() {
var called = 0;
function numberInSpan(n) {
called++;
return h('span', {key: 'num'}, 'Number is ' + n);
}
var vnode1 = h('div', [
thunk('span', 'num', numberInSpan, [1])
]);
var vnode2 = h('div', [
thunk('span', 'num', numberInSpan, [2])
]);
patch(vnode0, vnode1);
assert.equal(called, 1);
patch(vnode1, vnode2);
assert.equal(called, 2);
});
it('does not call render function on data unchanged', function() {
var called = 0;
function numberInSpan(n) {
called++;
return h('span', {key: 'num'}, 'Number is ' + n);
}
var vnode1 = h('div', [
thunk('span', 'num', numberInSpan, [1])
]);
var vnode2 = h('div', [
thunk('span', 'num', numberInSpan, [1])
]);
patch(vnode0, vnode1);
assert.equal(called, 1);
patch(vnode1, vnode2);
assert.equal(called, 1);
});
it('calls render function once on data-length change', function() {
var called = 0;
function numberInSpan(n) {
called++;
return h('span', {key: 'num'}, 'Number is ' + n);
}
var vnode1 = h('div', [
thunk('span', 'num', numberInSpan, [1])
]);
var vnode2 = h('div', [
thunk('span', 'num', numberInSpan, [1, 2])
]);
patch(vnode0, vnode1);
assert.equal(called, 1);
patch(vnode1, vnode2);
assert.equal(called, 2);
});
it('calls render function once on function change', function() {
var called = 0;
function numberInSpan(n) {
called++;
return h('span', {key: 'num'}, 'Number is ' + n);
}
function numberInSpan2(n) {
called++;
return h('span', {key: 'num'}, 'Number really is ' + n);
}
var vnode1 = h('div', [
thunk('span', 'num', numberInSpan, [1])
]);
var vnode2 = h('div', [
thunk('span', 'num', numberInSpan2, [1])
]);
patch(vnode0, vnode1);
assert.equal(called, 1);
patch(vnode1, vnode2);
assert.equal(called, 2);
});
it('renders correctly', function() {
var called = 0;
function numberInSpan(n) {
called++;
return h('span', {key: 'num'}, 'Number is ' + n);
}
var vnode1 = h('div', [
thunk('span', 'num', numberInSpan, [1])
]);
var vnode2 = h('div', [
thunk('span', 'num', numberInSpan, [1])
]);
var vnode3 = h('div', [
thunk('span', 'num', numberInSpan, [2])
]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.firstChild.tagName.toLowerCase(), 'span');
assert.equal(elm.firstChild.innerHTML, 'Number is 1');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.firstChild.tagName.toLowerCase(), 'span');
assert.equal(elm.firstChild.innerHTML, 'Number is 1');
elm = patch(vnode2, vnode3).elm;
assert.equal(elm.firstChild.tagName.toLowerCase(), 'span');
assert.equal(elm.firstChild.innerHTML, 'Number is 2');
assert.equal(called, 2);
});
it('supports leaving out the `key` argument', function() {
function vnodeFn(s) {
return h('span.number', 'Hello ' + s);
}
var vnode1 = thunk('span.number', vnodeFn, ['World!']);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.innerText, 'Hello World!');
});
it('renders correctly when root', function() {
var called = 0;
function numberInSpan(n) {
called++;
return h('span', {key: 'num'}, 'Number is ' + n);
}
var vnode1 = thunk('span', 'num', numberInSpan, [1]);
var vnode2 = thunk('span', 'num', numberInSpan, [1]);
var vnode3 = thunk('span', 'num', numberInSpan, [2]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.tagName.toLowerCase(), 'span');
assert.equal(elm.innerHTML, 'Number is 1');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.tagName.toLowerCase(), 'span');
assert.equal(elm.innerHTML, 'Number is 1');
elm = patch(vnode2, vnode3).elm;
assert.equal(elm.tagName.toLowerCase(), 'span');
assert.equal(elm.innerHTML, 'Number is 2');
assert.equal(called, 2);
});
it('can be replaced and removed', function() {
function numberInSpan(n) {
return h('span', {key: 'num'}, 'Number is ' + n);
}
function oddEven(n) {
var prefix = (n % 2) === 0 ? 'Even' : 'Odd';
return h('div', {key: oddEven}, prefix + ': ' + n);
}
var vnode1 = h('div', [thunk('span', 'num', numberInSpan, [1])]);
var vnode2 = h('div', [thunk('div', 'oddEven', oddEven, [4])]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.firstChild.tagName.toLowerCase(), 'span');
assert.equal(elm.firstChild.innerHTML, 'Number is 1');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.firstChild.tagName.toLowerCase(), 'div');
assert.equal(elm.firstChild.innerHTML, 'Even: 4');
});
it('can be replaced and removed when root', function() {
function numberInSpan(n) {
return h('span', {key: 'num'}, 'Number is ' + n);
}
function oddEven(n) {
var prefix = (n % 2) === 0 ? 'Even' : 'Odd';
return h('div', {key: oddEven}, prefix + ': ' + n);
}
var vnode1 = thunk('span', 'num', numberInSpan, [1]);
var vnode2 = thunk('div', 'oddEven', oddEven, [4]);
elm = patch(vnode0, vnode1).elm;
assert.equal(elm.tagName.toLowerCase(), 'span');
assert.equal(elm.innerHTML, 'Number is 1');
elm = patch(vnode1, vnode2).elm;
assert.equal(elm.tagName.toLowerCase(), 'div');
assert.equal(elm.innerHTML, 'Even: 4');
});
it('invokes destroy hook on thunks', function() {
var called = 0;
function destroyHook() {
called++;
}
function numberInSpan(n) {
return h('span', {key: 'num', hook: {destroy: destroyHook}}, 'Number is ' + n);
}
var vnode1 = h('div', [
h('div', 'Foo'),
thunk('span', 'num', numberInSpan, [1]),
h('div', 'Foo')
]);
var vnode2 = h('div', [
h('div', 'Foo'),
h('div', 'Foo')
]);
patch(vnode0, vnode1);
patch(vnode1, vnode2);
assert.equal(called, 1);
});
it('invokes remove hook on thunks', function() {
var called = 0;
function hook() {
called++;
}
function numberInSpan(n) {
return h('span', {key: 'num', hook: {remove: hook}}, 'Number is ' + n);
}
var vnode1 = h('div', [
h('div', 'Foo'),
thunk('span', 'num', numberInSpan, [1]),
h('div', 'Foo')
]);
var vnode2 = h('div', [
h('div', 'Foo'),
h('div', 'Foo')
]);
patch(vnode0, vnode1);
patch(vnode1, vnode2);
assert.equal(called, 1);
});
});
+13
View File
@@ -0,0 +1,13 @@
{
"framework": "mocha",
"src_files": [
"snabbdom.js",
"test/*.js"
],
"serve_files": [
"browserified.js"
],
"before_tests": "browserify -d test/index.js -o browserified.js",
"on_exit": "rm browserified.js",
"launch_in_dev": [ "firefox", "chromium" ]
}
+36
View File
@@ -0,0 +1,36 @@
{
"compilerOptions": {
"target": "ES5",
"noImplicitAny": true,
"sourceMap": true,
"strictNullChecks": true,
"declaration": true,
"removeComments": false,
"noUnusedLocals": true,
"lib": [
"dom",
"es5",
"es2015.core"
]
},
"files": [
"src/helpers/attachto.ts",
"src/modules/attributes.ts",
"src/modules/class.ts",
"src/modules/dataset.ts",
"src/modules/eventlisteners.ts",
"src/modules/hero.ts",
"src/modules/props.ts",
"src/modules/module.ts",
"src/modules/style.ts",
"src/h.ts",
"src/htmldomapi.ts",
"src/hooks.ts",
"src/is.ts",
"src/snabbdom.bundle.ts",
"src/snabbdom.ts",
"src/thunk.ts",
"src/tovnode.ts",
"src/vnode.ts"
]
}
+114
View File
@@ -0,0 +1,114 @@
export function escape(str: string | number | undefined): string {
if (str === undefined) {
return "";
}
if (typeof str === "number") {
return String(str);
}
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&#x27;")
.replace(/`/g, "&#x60;");
}
/**
* Remove trailing and leading spaces
*/
export function htmlTrim(s: string): string {
let result = s.replace(/(^\s+|\s+$)/g, "");
if (s[0] === " ") {
result = " " + result;
}
if (result !== " " && s[s.length - 1] === " ") {
result = result + " ";
}
return result;
}
/**
* Create a function that will generate unique id numbers
*/
export function idGenerator(): () => number {
let nextID = 1;
return () => nextID++;
}
export type HashFn = (args: any[]) => string;
export function memoize<R, T extends (...args: any[]) => R>(
f: T,
hash?: HashFn
): T {
if (!hash) {
hash = args => args.map(a => String(a)).join(",");
}
let cache: { [key: string]: R } = {};
function memoizedFunction(...args: any[]) {
let hashValue = hash!(args);
if (!(hashValue in cache)) {
cache[hashValue] = f(...args);
}
return cache[hashValue];
}
return memoizedFunction as T;
}
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
*
* Inspired by https://davidwalsh.name/javascript-debounce-function
*/
export function debounce(
func: Function,
wait: number,
immediate?: boolean
): Function {
let timeout;
return function(this: any) {
const context = this;
const args = arguments;
function later() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
}
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
interface Tree<T> {
children: T[];
}
/**
* Find a node in a tree.
*
* This will traverse the tree (depth first) and return the first child that
* matches the predicate, if any
*/
export function findInTree<T extends Tree<T>>(
tree: T,
predicate: (t: T) => boolean
): T | null {
if (predicate(tree)) {
return tree;
}
for (let child of tree.children) {
let match = findInTree(child, predicate);
if (match) {
return match;
}
}
return null;
}