Coder Social home page Coder Social logo

snabbdom / snabbdom Goto Github PK

View Code? Open in Web Editor NEW
11.3K 11.3K 1.1K 4.94 MB

A virtual DOM library with focus on simplicity, modularity, powerful features and performance.

License: MIT License

JavaScript 2.14% HTML 0.19% TypeScript 97.49% Shell 0.18%
hacktoberfest snabbdom virtual-dom-library

snabbdom's Introduction

Snabbdom

A virtual DOM library with a focus on simplicity, modularity, powerful features and performance.


License: MIT Build Status npm version npm downloads Join the chat at https://gitter.im/snabbdom/snabbdom

Donate to our collective

Thanks to Browserstack for providing access to their great cross-browser testing tools.


English | 简体中文 | Hindi

Introduction

Virtual DOM is awesome. It allows us to express our application's view as a function of its state. But existing solutions were way too bloated, too slow, lacked features, had an API biased towards OOP , and/or lacked features I needed.

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.
    • Patch function with a function signature equivalent to a reduce/scan function. Allows for easier integration with a FRP library.
  • Features in modules
  • Third party features

Example

import {
  init,
  classModule,
  propsModule,
  styleModule,
  eventListenersModule,
  h
} from "snabbdom";

const patch = init([
  // Init patch function with chosen modules
  classModule, // makes it easy to toggle classes
  propsModule, // for setting properties on DOM elements
  styleModule, // handles styling on elements with support for animations
  eventListenersModule // attaches event listeners
]);

const container = document.getElementById("container");

const vnode = h(
  "div#container.two.classes",
  { on: { click: () => console.log("div clicked") } },
  [
    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);

const newVnode = h(
  "div#container.two.classes",
  { on: { click: () => console.log("updated div clicked") } },
  [
    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

More examples


Table of contents

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.

init

The core exposes only one single function init. This init takes a list of modules and returns a patch function that uses the specified set of modules.

import { classModule, styleModule } from "snabbdom";

const patch = init([classModule, styleModule]);

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.

patch(oldVnode, newVnode);

Unmounting

While there is no API specifically for removing a VNode tree from its mount point element, one way of almost achieving this is providing a comment VNode as the second argument to patch, such as:

patch(
  oldVnode,
  h("!", {
    hooks: {
      post: () => {
        /* patch complete */
      }
    }
  })
);

Of course, then there is still a single comment node at the mount point.

h

It is recommended that you use h to create vnodes. It accepts a tag/selector as a string, an optional data object, and an optional string or an array of children.

import { h } from "snabbdom";

const vnode = h("div#container", { style: { color: "#000" } }, [
  h("h1.primary-title", "Headline"),
  h("p", "A paragraph")
]);

fragment (experimental)

Caution: This feature is currently experimental and must be opted in. Its API may be changed without an major version bump.

const patch = init(modules, undefined, {
  experimental: {
    fragments: true
  }
});

Creates a virtual node that will be converted to a document fragment containing the given children.

import { fragment, h } from "snabbdom";

const vnode = fragment(["I am", h("span", [" a", " fragment"])]);

toVNode

Converts a DOM node into a virtual node. Especially good for patching over pre-existing, server-side generated HTML content.

import {
  init,
  styleModule,
  attributesModule,
  h,
  toVNode
} from "snabbdom";

const patch = init([
  // Initialize a `patch` function with the modules used by `toVNode`
  attributesModule // handles attributes from the DOM node
  datasetModule, // handles `data-*` attributes from the DOM node
]);

const newVNode = h("div", { style: { color: "#000" } }, [
  h("h1", "Headline"),
  h("p", "A paragraph"),
  h("img", { attrs: { src: "sunrise.png", alt: "morning sunrise" } })
]);

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.

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 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.

const vnode1 = h("div", [h("div", [h("span", "Hello")])]);
const 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 work by registering global listeners for hooks. A module is simply a dictionary mapping hook names to functions.

const myModule = {
  create: (oldVnode, vnode) => {
    // invoked whenever a new virtual node is created
  },
  update: (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. JSX examples assume you're using the jsx pragma provided by this library.

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 indicate whether or not the class should stay or go on the vnode.

h("a", { class: { active: true, selected: false } }, "Toggle");

In JSX, you can use class like this:

<div class={{ foo: true, bar: true }} />
// Renders as: <div class="foo bar"></div>

The props module

Allows you to set properties on DOM elements.

h("a", { props: { href: "/foo" } }, "Go to Foo");

In JSX, you can use props like this:

<input props={{ name: "foo" }} />
// Renders as: <input name="foo" /> with input.name === "foo"

Properties can only be set. Not removed. Even though browsers allow addition and deletion of custom properties, deletion will not be attempted by this module. This makes sense, because native DOM properties cannot be removed. And if you are using custom properties for storing values or referencing objects on the DOM, then please consider using data-* attributes instead. Perhaps via the dataset module.

The attributes module

Same as props, but set attributes instead of properties on DOM elements.

h("a", { attrs: { href: "/foo" } }, "Go to Foo");

In JSX, you can use attrs like this:

<div attrs={{ "aria-label": "I'm a div" }} />
// Renders as: <div aria-label="I'm a div"></div>

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 (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 property.

h("button", { dataset: { action: "reset" } }, "Reset");

In JSX, you can use dataset like this:

<div dataset={{ foo: "bar" }} />
// Renders as: <div data-foo="bar"></div>

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.

h(
  "span",
  {
    style: {
      border: "1px solid #bada55",
      color: "#c0ffee",
      fontWeight: "bold"
    }
  },
  "Say my name, and every colour illuminates"
);

In JSX, you can use style like this:

<div
  style={{
    border: "1px solid #bada55",
    color: "#c0ffee",
    fontWeight: "bold"
  }}
/>
// Renders as: <div style="border: 1px solid #bada55; color: #c0ffee; font-weight: bold"></div>

Custom properties (CSS variables)

CSS custom properties (aka CSS variables) are supported, they must be prefixed with --

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.

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.

The all value of transition-property is not supported.

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.

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.

The all value of transition-property is not supported.

Set properties on destroy

h(
  "span",
  {
    style: {
      opacity: "1",
      transition: "opacity 1s",
      destroy: { opacity: "0" }
    }
  },
  "It's better to fade out than to burn away"
);

The all value of transition-property is not supported.

The 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 to the event object that belongs to it.

function clickHandler(ev) {
  console.log("got clicked");
}
h("div", { on: { click: clickHandler } });

In JSX, you can use on like this:

<div on={{ click: clickHandler }} />

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:

// Does not work
const sharedHandler = {
  change: (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:

// Works
const sharedHandler = (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 }
  })
]);

SVG

SVG just works when using the h function for creating virtual nodes. SVG elements are automatically created with the appropriate namespaces.

const 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 and the SVG Carousel example.

Classes in SVG Elements

Certain browsers (like IE <=11) do not support classList property in SVG elements. Because the class module internally uses classList, it will not work in this case unless you use a classList polyfill. (If you don't want to use a polyfill, you can use the class attribute with the attributes module).

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 renderFn is invoked only if the renderFn is changed or [stateArguments] array length or its elements are changed.

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.

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.

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.

JSX

Note that JSX fragments are still experimental and must be opted in. See fragment section for details.

TypeScript

Add the following options to your tsconfig.json:

{
  "compilerOptions": {
    "jsx": "react",
    "jsxFactory": "jsx",
    "jsxFragmentFactory": "Fragment"
  }
}

Then make sure that you use the .tsx file extension and import the jsx function and the Fragment function at the top of the file:

import { Fragment, jsx, VNode } from "snabbdom";

const node: VNode = (
  <div>
    <span>I was created with JSX</span>
  </div>
);

const fragment: VNode = (
  <>
    <span>JSX fragments</span>
    are experimentally supported
  </>
);

Babel

Add the following options to your babel configuration:

{
  "plugins": [
    [
      "@babel/plugin-transform-react-jsx",
      {
        "pragma": "jsx",
        "pragmaFrag": "Fragment"
      }
    ]
  ]
}

Then import the jsx function and the Fragment function at the top of the file:

import { Fragment, jsx } from "snabbdom";

const node = (
  <div>
    <span>I was created with JSX</span>
  </div>
);

const fragment = (
  <>
    <span>JSX fragments</span>
    are experimentally supported
  </>
);

Virtual Node

Properties

sel : string

The sel property specifies the HTML element of the vnode, optionally its id prefixed by a #, and zero or more classes each prefixed by a .. The syntax is inspired by CSS selectors. Here are a few examples:

  • div#container.bar.baz – A div element with the id container and the classes bar and baz.
  • li – A li element with no id nor classes.
  • button.alert.primarybutton element with the two classes alert and primary.

The selector is meant to be static, that is, it should not change over the lifetime of the element. To set a dynamic id use the props module and to set dynamic classes use the class module.

Since the selector is static, Snabbdom uses it as part of a vnodes identity. For instance, if the two child vnodes

[h("div#container.padding", children1), h("div.padding", children2)];

are patched against

[h("div#container.padding", children2), h("div.padding", children1)];

then Snabbdom uses the selector to identify the vnodes and reorder them in the DOM tree instead of creating new DOM element. This use of selectors avoids the need to specify keys in many cases.

data : Object

The .data property of a virtual node is the place to add information for modules 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()

For example h('div', {props: {className: 'container'}}, [...]) will produce a virtual node with

({
  props: {
    className: "container"
  }
});

as its .data object.

children : Array<vnode>

The .children property of a virtual node is the third (optional) parameter to h() 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

[
  {
    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 as well as modules.

key : string | number

The .key property is created when a key is provided inside of your .data 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 property created.

If provided, the .key property must be unique among sibling elements.

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 – a repository containing several example applications that demonstrate an architecture that uses Snabbdom.
  • Cycle.js – "A functional and reactive JavaScript framework for cleaner code" uses Snabbdom
  • Vue.js use a fork of snabbdom.
  • scheme-todomvc build redux-like architecture on top of snabbdom bindings.
  • kaiju - Stateful components and observables on top of snabbdom
  • Tweed – An Object Oriented approach to reactive interfaces.
  • Cyclow - "A reactive frontend framework for JavaScript" uses Snabbdom
  • Tung – A JavaScript library for rendering HTML. Tung helps to divide HTML and JavaScript development.
  • sprotty - "A web-based diagramming framework" uses Snabbdom.
  • Mark Text - "Realtime preview Markdown Editor" build on Snabbdom.
  • puddles - "Tiny vdom app framework. Pure Redux. No boilerplate." - Built with ❤️ on Snabbdom.
  • Backbone.VDOMView - A Backbone View with VirtualDOM capability via Snabbdom.
  • Rosmaro Snabbdom starter - Building user interfaces with state machines and Snabbdom.
  • Pureact - "65 lines implementation of React incl Redux and hooks with only one dependency - Snabbdom"
  • Snabberb - A minimalistic Ruby framework using Opal and Snabbdom for building reactive views.
  • WebCell - Web Components engine based on JSX & TypeScript

Be sure to share it if you're building an application in another way using Snabbdom.

Related packages

Packages related to snabbdom should be tagged with the snabbdom keyword and published on npm. They can be found using the query string keywords: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 the 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.

const sharedNode = h("div", {}, "Selected");
const vnode1 = h("div", [
  h("div", {}, ["One"]),
  h("div", {}, ["Two"]),
  h("div", {}, [sharedNode])
]);
const 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):

const vnode2 = h("div", [
  h("div", {}, ["One"]),
  h("div", {}, [{ ...sharedNode }]),
  h("div", {}, ["Three"])
]);

Another solution would be to wrap shared vnodes in a factory function:

const sharedNode = () => h("div", {}, "Selected");
const vnode1 = h("div", [
  h("div", {}, ["One"]),
  h("div", {}, ["Two"]),
  h("div", {}, [sharedNode()])
]);

Opportunity for community feedback

Pull requests that the community may care to provide feedback on should be merged after such an opportunity of a few days was provided.

snabbdom's People

Contributors

2hu12 avatar caesarsol avatar caridy avatar dependabot[bot] avatar fix-fix avatar grimalschi avatar harrywincup avatar iambumblehead avatar jvanbruegge avatar katyo avatar kay999 avatar mightyiam avatar mkaemmerer avatar mreinstein avatar paldepind avatar patomation avatar raine avatar rayd avatar renovate-bot avatar renovate[bot] avatar risto-stevcev avatar ryota-ka avatar skaterdad avatar sprat avatar staltz avatar stevealee avatar streetstrider avatar tobymao avatar tylors avatar yelouafi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

snabbdom's Issues

prepatch/postpatch hooks not called on modules

the 'prepatch/postpatch' is only called on hooks attached to specific vnodes but not on generic modules.
The hooks are also not called on the first patch operation (element creation)

Expando property support?

Hey @paldepind really great library.. i use sometimes the expando property and in virtual-dom i was able to simply add them when you using h and worked fine however i wasnt able to achieve the same results in snabbdom..

do you know if thats expected ?

thanks

Won't work with node.js

The style module seems to crash when using within Node.js.
Without requiring it everything seems to work fine.

 C:\UBS\Dev\components\nav\node_modules\snabbdom\modules\style.js:1
 (function (exports, require, module, __filename, __dirname) { var raf = (window && window.requestAnimationFrame) || setTimeout;

ReferenceError: window is not defined

I cannot see mention of Node.js within the README. Is it not officially supported ?

React Native

Any ideas how to get this to work with React Native? Cause that would be awesome. 👍

The event listening module should support passing several arguments to even handlers

Today the event listeners module supports passing custom arguments to event handler functions.

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]}}),
]);

However, only one argument is supported. This restriction should be lifted so that a variable amount of arguments is supported.

VNodes can't have both text content and children properties

In the current implementation, it seems that having .text and .children are mutually exclusive. The current code is:

if (is.array(children)) {
    ...
} else if (is.primitive(vnode.text)) {
    api.appendChild(elm, api.createTextNode(vnode.text));
}

Since text content is technically the first node (a text node) child of an element, I think it should instead be more like:

if (is.primitive(vnode.text)) {
    api.appendChild(elm, api.createTextNode(vnode.text));
}
if (is.array(children)) {
    ...
} 

Will PR if approved.

Speed vs low memory usage. Which strategy?

Vnode's elm property provides quick access to the dom elment when patching that's true. But likely to hold up too much space in the memory. This will be problem in big tree structure on the low-profile mobile like devices.

Could elm property reference string is used as Id instead of direct dom object . Are we lost a lot of speed?

For Example:

//hyperscript
h("button", "Button")
//and generated vnode structure may be like
{
    sel: "button"
    text: "Button"
    elm: "autoGeneratedId"
}

can be rendering

<div snabbdom-id="autoGeneratedId">Button</button>

To access the actual dom object if desired in patch process we can be use as

var elm = document.querySelector("[snabbdom-id='autoGeneratedId']")
.......

https://github.com/matt-esch/virtual-dom#example uses another strategy. Anything about on the vnode tree for dom referencing. In outside dom object created with the createElement function is used in the patch process. But I can patch each vnode in snabbdom because each node contains elm property. I love it.

Another google project https://github.com/google/incremental-dom they are using very different methods to provide low memory usage.

isDef()

Reading the source I have noticed plenty (~60) occurrences of !isUndef(). To make code more readable I suggest to replace them with newly introduce isDef() one-liner.

partial update

To continue gitter conversation related to components nesting, I guess it would be extremely handy to add partial update the way it exists in cito.js. In a word, children can be represented as a function, and during redraw pass children's update is skipped if a function returns undefined.

This way it is possible to attach (with patch) new absolutely alien and independent vnode (component) to already existing onde. As long as parent vnode exists, it doesn't see children, and the last one has own independent life cycle.

And this is an application logic and presentation logic separation I have wrote about :)

I guess it would demand minimal code change. Sorry, can not suggest PR as far as didn't grokked a source code yet.

Some nodes not delay-removed when `transition-property: all`

While doing some tests, I noticed that DOM nodes don't get removed after transitioning when I define the transition-property as 'all' instead of the more specific properties (I know it's lower perf, but I like being lazy during testing).

Is it correct to assume that checking the specific property transitionend events is what allows the library to wait for all of them to complete before node removal?

style module does not remove old styles

If you remove a style from the vnode between patches, the style is not removed from the underlying element. It only adds and updates styles. Don't know how common this would be in practice, but I just got bitten by it today. I could open a PR if you agree it's a bug.

eventlisteners module problem with shared data

Because this module mutates the vnode data, replacing a given function with an object pointing to the function, you can't have multiple vnodes sharing the same data (or to be precise: sharing the same {on: ...} branch).

I don't see an obvious fix for this, given this mutation is part of the 'nice trick' that saves it from having to add event listeners on each patch. But sharing event handler data between vnodes seems like a normal thing to do. (In my case I was rendering a set of radio buttons, each having the same change handler based on the event target value.)

Perhaps a warning should be added to the readme, if there is no way around this?

Possible issue when nesting thunks

Hello,

I am using a thunk-like vnode to emulate components with their own local state. It is common for a thunk-like component to have child components (at an arbitrary depth) which are also the same type of thunk-like components.

Adding and updating vnodes work correctly, but the removeVnodes function does not handle the nested thunk-like components correctly. It seems that the removeVnodes and invokeDestroyHook functions would have to be updated to correctly handle nested thunks.

Having a thunk as the root vnode also causes trouble in the patch function.

I also suspect that the vnode returned by the function passed to the thunks function does not have its prepatch/postpatch hooks called.

Unfortunately, I am using clojurescript, so I cannot send you a minimal test case (or be a 100% certain that the issue exists at all when using javascript).

Snabbdom patches over given container

While I've been writing my intergration for snabbdom with Cycle.js, I've come to notice that running for example patch(document.querySelector('.app'), view), snabbdom is actually patching over .app. However my needs are for the view to be appended to .app, because I need to listen to events relative to .app. Is there a way to do this currently or is it possible to add support for this? I'd be happy to submit a PR if it is needed and would be accepted.

Thank you for your time.

exposing vtree traversal methods

Hello--

I would like to add a new vnode into an existing vtree, however, the location where the new vnode is to be inserted will be determined at run time ~~ this determination method is non-normative and will depend on dynamic, application-related factors.

I'm assuming snabbdom is already traversing vtree in order to do it's work when patching DOM. I'm wondering if there might be a way to hook into these traversal capabilities for dynamic vnode insertion purpose ?

Thank you for your ideas/comments

Build output for code sharing with online playground sites.

Sometimes we want to code sharing with community on the online playground sites ( http://codepen.io/, http://jsbin.com/, http://jsfiddle.net/ etc ) Sorry npm and browserify suported http://requirebin.com/ is buggy.

Github does not allow driectly reference script files on the online playground sites but rawgit.com possible with the help.

For example I can use virtual-dom release output https://github.com/Matt-Esch/virtual-dom/blob/master/dist/virtual-dom.js as https://rawgit.com/Matt-Esch/virtual-dom/master/dist/virtual-dom.js

So we can use snabbdom browserify outputs with helping rawgit.com on the online playground sites referencing similiar to https://github.com/paldepind/snabbdom/blob/master/build/snabbdom.with.all.modules.js.

Supporting other platforms other than the DOM

I was wondering if it would be possible, and if it is, if it would be desirable, to split the codebase up a little bit to allow for alternative platforms. Snabbdom being a facility to this.

I'm currently working on my own framework, Motorcycle.js, and I'd like to add support for nativescript in the near future. I was hoping to avoid the need to for creating something entirely specific for Motorcycle if possible, and thought it might be possible to rework Snabbdom to be able to organize this.

Love to hear the thoughts on this.

Event listening improvements

I offer some improvements for event handling:

  1. Virtual events which eliminates different behavior between user-agents.
  2. Listening events only on root node to reduce number of DOM API calls.

Are there any ideas about it?
Of course I haven't implemented this at current time, but I can help to do this, if it's really necessary.

Suggestion: Ability to use arrays of child-nodes everywhere a single node can be used.

One suggestion: It would be helpful if vnodes could insert arrays of vnodes instead of only a single one. This would make it much more flexible and would eliminate the need for "useless" in-between container-tags (which genrally works fine, but is problematic for certain use-cases for example when using a nth-child-selector in css).

To circumvent this, in the moment I use a simple 'h'-wrapper which flattens it's arguments before inserting:

function flatten(data) {
    var res = [];
    function flat(data) {
        _.each(data, function(v) {
            if (v === null || v === undefined || v === false) {}
            else if (_.isArray(v)) flat(v);
            else res.push(v);
        })
    }
    flat(data);
    return res;
}
exports.h = function(tag, opts, args) {
    return h(tag, opts || {}, flatten(Array.prototype.slice.call(arguments, 2)))
};

This makes building node-trees much easier (but requires a {} if there are any child nodes).

Problem with my solution: It won't work for thunks, because data.vnode only supports a child-node. So if there is a new thunk-implementation comming, maybe it's possible to address this problem, too.

Number input not using value properly.

Using snabbdom-cerebral and running into some issue that appear to be snabbdom related.

Here is the jsx markup
<input type="number" on-change={signals.test} value={state.test||5}/>

and here is how the state.test object is getting set

controller.signal('test', [
  ({input,state})=> {
    const int = parseInt(input.target.value);
    const bounded = Math.max(2,Math.min(16,int));
    state.set('test',bounded);
  }
]);

If you console.log before the input renders you will see that the test.state does in fact stay between 2-16 (inclusively) but the input has no such bounds. I know in this case I could use min=2 max=6 on the input but this is a simplified version of more elaborate constraints.

Is this a snabbdom issue related to on-change of inputs?

Save excursion

When we change property value of text inputs, usually we would like to save cursor position, selection range and focus of element, which is in focus.
In my experience, there is two cases, which assume different workarounds:

  1. The new value is same as the value of focussed input: We may simply don't assign new value without any extra work.
  2. The new value is different from current value of focussed input (for example, the value was changed by controller): We need get selection before changing value, and set selection after that. If selection is also set using properties, we must use it instead of current selection.
    I tried to change props plugin to do that. Is it appropriate way? Or I need to create different plugin to work with inputs.
    At the moment, all my fixes is quite simple:
function updateProps(oldVnode, vnode) {
  var key, cur, old, elm = vnode.elm,
      oldProps = oldVnode.data.props || {}, props = vnode.data.props || {},
      preserveExcursion = "value" in props && typeof elm.selectionStart === "number" &&
                          document.activeElement === elm && props.value !== elm.value,
      /* save excursion */
      selection = preserveExcursion ? [
        typeof props.selectionStart === "number" ? props.selectionStart : elm.selectionStart,
        typeof props.selectionEnd === "number" ? props.selectionEnd : elm.selectionEnd
      ] : null;
  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;
    }
  }
  /* restore excursion */
  if (preserveExcursion) {
    elm.setSelectionRange(selection[0], selection[1]);
    elm.focus();
  }
}

module.exports = {create: updateProps, update: updateProps};

Support JSX compilation

JSX almost works already using a pragma that instructs the compiler to use snabbdom/h, there are just 2 edge cases I have found.

  • If no attributes are added to a JSX element, the data argument is null. This causes snabbdom to throw an error.
  • Children are not provided as an array, they are provided as any arguments after the selector and data.

A basic example of what this would look like can be found here.

Many Thoughts and Question

This looks really nice. I can tell you put a lot of thought into it. I've been investigating the elm architecture which has led me here because this snabbdom uses pure functions unlike React! 👍 Anyways, here are some questions, thoughts, and ideas... Answer at your leisure.

  1. Whats difference between props and attributes? I didnt really understand the difference in the README.

  2. When you set a delayed animation on remove, it looks like it listens for the transitionend event which is notoriously inconsistent. With inline styles, it seems like it would be pretty easy to parse the duration of the transition and use a setTimeout like the latest version of React. Sound like a good idea?

  3. I don't really understand the styles module works very well, but it would be really sweet if it the styles were prefixed automatically. I'm also curious how to prefix flexbox since the display key in the object would have to be repeated...

.page-wrap {
  display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox;      /* TWEENER - IE 10 */
  display: -webkit-flex;     /* NEW - Chrome */
  display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
 }
  1. Interesting how you're using requestAnimationFrame for the rendering cycle. Whats the reasoning behind that rather than just setting the value immediately?

  2. It would be really sweet if there was a simple way to purify events like they do in React. Its such a hassle working with keyboard events and all the quirks between different browsers and operating system...

  3. I like how you allow click handlers to be passed an array. Thus you can do a shallow equals on the elements of the array. If you were to use Function.prototype.bind, then the reference will always change and thats not good for re-rendering. But sometimes you want to bind a value, and capture the value from the event. toChildAction is a good example of this here. I've been thinking about this issue a lot lately in regards to react and ramda as well. It would be sweet if there was a standard in fantasyland where objects have a .equals method to use instead of referential equality if it exists. We could create a bind function that keeps track of the original arguments and function so we can call .equals and it will tell us if two functions are effectively the same (same original function and same bound arguments). This would be an awesome addition to Ramda and could be a more generalizable solution for snabbdom. I mentioned this here with some ugly looking code.

  4. I'm curious how you are using this library. Do you have any large examples that I can browse and learn from? Specifically, I'm interested in how to architect the app with components and different views with http and websocket side-effects. It seems like I could just use a patch to subscribe and unsubscribe to data over websockets with the view lifecycle. Still trying to figure this out though. This was the limit I ran into with my elmish example. It abstracts very powerfully, but I couldnt figure out how to deal with sub/unsub....

  5. What are your thoughts on React Native? Would it be possible to write a shim somehow to use this library with React Native? It would be awesome to leverage all the resource facebook is pouring into React.

  6. Have you seen some of the cool Redux Dev Tools? It would be pretty sweet to implement some of these.

  1. Have you checked out Relay and GraphQL? The most interesting thing to me about it is how Relay accumulates resource requests through the view heirarchy to send one giant request as opposed to many smaller requests. I'm trying to figure out how that would work within an Elm-like architecture.

Anyways, thats enough for now. This is a sweet library and so is flyd. Keep up the great work. I'd love to help!

Changing the class list appended to an element name causes the element to be removed and recreated

I know the "correct" way to modify a class list is to use the class module, but I'm using snabbdom-jsx, and it provides a classNames property, which you can supply an array of class names to. The array is then translated to a period-delimited list of classes and appended to the element tag name, e.g.h('div.foo',...) becomes h('div.foo.bar', ...). As a result of this, snabbdom is removing the element entirely and relplacing it with a new element. This seems to me to be incorrect (not to mention inefficient) behaviour, seeing as only the class list has changed. I'll log an issue with snabbdom-jsx as well and suggest use of the class module.

HTML output support

I'm currently working on an integration of snabbdom with Cycle.js, but to be at feature parity with the current Cycle.js solution for view rendering I would need a way to output HTML on the server-side. Are there any solutions that I'm not currently able to find or is this on the roadmap of things?

Thank you for your time and for your work on this library!

init and prepatch module hooks?

I miss the init and prepatch hooks for a module of mine. I am wondering why some vnodes' hooks are not exposed as module hooks? Can this be fixed in the API?

Or maybe I missed something... I would like to process the children of vnodes before the vnodes are rendered: how we can do that for any vnode?

Expose all hooks for modules

I'm happy with the library for its simplicity, performance, and extensibility. It became even more exciting when I discovered that I can write modules to extend that. However, currently only ['create', 'update', 'remove', 'destroy', 'pre', 'post'] can be used when defined in a module. I'm wondering if it is possible to also expose 'insert', 'prepatch', 'postpatch'? For me specifically it will be convenient if I can use 'postpatch', since I want to do some manipulation after all nodes are loaded.

I saw that a quick solution is to just add the 3 hooks into the hooks Array before the definition of init. Are there some concerns not to include all hooks here?

Also it seems that a documentation for developing modules is missing. Although it is really easy to write if we read the code, it's better to at least mention that in README so new comers like me won't miss the treasure:)

The invocation of insert/remove hooks

I tried to use insert hook with canvas node in order to initialize size (using parent node width and aspect ratio) and draw. But I found that I can't do it because insert (and remove) hook actually does not invoked on each vnode when subtree had inserted to DOM.
I don't sure about that behavior is bug or feature. But determining what node would be really inserted or removed is a non-trivial task and breaks some aspects of component-based development.
Is there any simple workarounds for this issue?
The first idea: Implement plugin, which defines insert/remove hooks, which invokes this hooks for all children of current vnode up to end-vnodes of vtree.
The second idea: Change core in same way.

Can't patch elements inside an iframe

I'm using snabbdom-jsx along with snabbdom for this (contrived) example. But I'd like to be able to patch the <div> inside the <iframe>. This code should do it I would think, but I run into an error.

let frame = document.createElement('iframe');
frame.srcdoc = "<div>Thing</div>";
frame.onload = () => {
    patch(frame.contentDocument.body.querySelector('div'), <div>Other thing</div>);
};
document.body.appendChild(frame);

I'm getting the error Uncaught TypeError: Cannot read property 'props' of undefined because we're running the patchVnode function when the oldVnode is still the actual Element. It hasn't been patched to a VNode because this is the first time patch is being called on it.

I think the issue stems from this line. The instanceof check is failing because the element inside the iframe is actually an instance of frame.contentWindow.Element, not the Element reference in the outer frame. Hopefully that makes sense.

I'm wondering if we can do a bit looser check when looking at the oldVnode to see if it's an Element or not. Maybe something along the lines of

if (oldVnode.nodeType === Element.ELEMENT_NODE) {

Is it possible to add functionality for generator functions

I am using a technique that makes use of generator functions.

It would he helpful if the code below:

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));
  };
}

would be changed to not give this error:

Uncaught TypeError: Method [Generator].prototype.next called on incompatible receiver undefined

I am doing something like this:

click:Component.next

best wishes !

Isomorphic snabbdom

It's rather a question. Is it possible to use snabbdom.js in isomorphic apps?
UPD: I found motorcycle-isomorphic-boilerplate, motorcycle.js uses snabbdom in DOM Driver. But what about CSR after SSR - obviously there is no built-in way for components to understand that they were rendered on the server (as React.js does by data-react-checksum attribute)?

virtual-dom thunk equivalent?

This is an exciting project. I wonder if you have plans to implement virtual-dom thunk like structures, so that some parts of the vdom don't have to be diffed if their states haven't changed.

Also, you might want to look at cyclejs, which is an architecture combining FRP with virtual dom.

Link to the Functional Architecture examples

I'm really liking what you're building here, @paldepind, and I was thinking it'd be a good idea to include a link to the functional architecture examples somewhere in the README, as that helped me quite a bit getting started with all this.

Additionally, including a link to the actual source code for the two current examples might also be helpful.

I can create a PR with the necessary changes, if you'd like. Thanks!

'mounted' hook

is there such a thing? One thing I absolutely hate about virtual-dom compared to React is that there is no proper hook for "the element was newly mounted, and was inserted in the document"; this is very useful when you want to do things like measurements or anything that can't work while the element is detached.
And doing setTimeout, setImmediate, requestAnimationFrame or whatever are crazy hacks where the UI can flicker and open you to race conditions.

Simplifying API (settings props, content)

virtual-dom api seems a little bit simplier in some cases for example:

  1. Alloing props directly without need of props
    image({value: 'text'}) vs image({props: {value: 'text'}})

  2. Element content can be not array
    div('.cls', 'Some content') vs div('.cls', ['Some content'])

is it by intention you do not simplify the API?

How to get pointer to real element.

How can you get pointer to the real DOM element.

There are some libraries out there like GSAP and velocity ( animation ) that are useful.

however their api requires access to the real DOM element.

is it possible to do it with snabbdom ?

Root element is not rendering

Hyperscript's root element is not rendering allways. Because snabbdom.js line 184 ... oldCh = oldVnode.children, ch = vnode.children;......

Problem:

 var vnode = h('div#id.two.classes', [
        h('span', 'This is text')
    ]);
    patch(document.getElementById('container'), vnode);

output as

<div id="container"><span>This is text</span></div>

But may be:

<div id="container"><div id="id" class="two classes"><span>This is text</span></div></div>

Subtree patching

see Matt-Esch/virtual-dom#343

Instead of generating a new vtree and diffing it with the old vtree to generate a set of patches, components should create patches for themselves, which are buffered and at each "tick" applied to the DOM.

As far as I understand @Zolmeister, he suggest, that this needs:

  1. Adding hooks to Thunks (which he doesn't think exists right now)
  2. extending the hook function signature with a new 'render' function which generates an in-place

Any thoughts on this issue?

Hero Module - oldVnode not calculating its bounding rectangle

Issue

I'm attempting to get a hero transition working using Cycle.js with cycle-snabbdom (which uses snabbdom 0.2.7).

The hero module executes all of the appropriate hooks, but when it tries to calculate oldRect = oldElm.getBoundingClintRect(), all of the keys are = 0. The newElm calcs are all good. Naturally the incorrect oldRect causes the translation calcs to be wrong, resulting in very weird transitions.

Test App Setup

My setup is very simple: just a checkbox which toggles two vNodes. Do you see anything wrong with these vnode definitions (falseView, trueView) for using with the Hero module?

If you think this should work, I can move this issue over to cycle-snabbdom to see if it's an implementation issue.

CSS:

    body {
      background-color: rgb(230,230,230);
      margin: 0;
      width: 100%;
    }
    .hero {
      transition: transform 1s, opacity 1s;
    }

Cycle App:

import Cycle from '@cycle/core';
import {h, makeDOMDriver} from 'cycle-snabbdom';

const falseView =
  h('div',
    {
      style: {width: '100px', height: '100px', backgroundColor: 'pink', margin: '1rem'},
      hero: {id: 'test-hero-simple'},
    },
    [h('span.smalltext.hero',
      {
        hero: {id: 'test-hero-simple'}
      },
      `Simple Box`)
    ]
  )

const trueView =
  h('div',
    {
      style: {width: '300px', height: '200px', backgroundColor: 'pink', margin: '5rem'},
    },
    [h('span.bigtext.hero',
      {
        hero: {id: 'test-hero-simple'}
      },
      `Simple Box`)
    ]
  )

function main({DOM}) {
  let vTree$ =
    DOM.select('input').events('change')
      .map(ev => ev.target.checked)
      .startWith(false)
      .do((x) => {console.log(`Checkbox value changed to ${x}`)})
      .map(toggled =>
        h('div', {}, [
          h('input#box1', {attrs: {type: 'checkbox'}}), 'Toggle me',
          toggled ? trueView : falseView,
        ])
      )

  return {DOM: vTree$}
}

Cycle.run(main, {
  DOM: makeDOMDriver('#main-container', [
    require(`cycle-snabbdom/node_modules/snabbdom/modules/class`),
    require(`cycle-snabbdom/node_modules/snabbdom/modules/hero`),
    require(`cycle-snabbdom/node_modules/snabbdom/modules/style`),
    require(`cycle-snabbdom/node_modules/snabbdom/modules/props`),
    require(`cycle-snabbdom/node_modules/snabbdom/modules/attributes`),
  ]),
})

Chrome Debugger Data

The oldElm looks like this when inside the post() function. I find it strange that it says parentElement: null.

oldElm: span.smalltext.hero
accessKey: ""
attributes: NamedNodeMap
baseURI: null
childElementCount: 0
childNodes: NodeList[1]
children: HTMLCollection[0]
classList: DOMTokenList[2]
className: "smalltext hero"
clientHeight: 0
clientLeft: 0
clientTop: 0
clientWidth: 0
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: text
firstElementChild: null
hidden: false
id: ""
innerHTML: "Simple Box"
innerText: "Simple Box"
isContentEditable: false
lang: ""
lastChild: text
lastElementChild: null
localName: "span"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: null
nextSibling: null
nodeName: "SPAN"
nodeType: 1
nodeValue: null
offsetHeight: 0
offsetLeft: 0
offsetParent: null
offsetTop: 0
offsetWidth: 0
...(irrelevant 'on...' events)...
outerHTML: "<span class="smalltext hero" style="transform-origin: 0px 0px 0px; opacity: 1;">Simple Box</span>"
outerText: "Simple Box"
ownerDocument: document
parentElement: null
parentNode: null
prefix: null
previousElementSibling: null
previousSibling: null
scrollHeight: 0
scrollLeft: 0
scrollTop: 0
scrollWidth: 0
shadowRoot: null
spellcheck: true
style: CSSStyleDeclaration
tabIndex: -1
tagName: "SPAN"
textContent: "Simple Box"
title: ""
translate: true
webkitdropzone: ""
__proto__: HTMLSpanElement

Which results in this oldRect:

oldRect: ClientRect
   bottom: 0
   height: 0
   left: 0
   right: 0
   top: 0
   width: 0

Thanks!

/examples/svg/index.html has some extraneous code

No big deal, as long as it works, but the one for svg could do without all the css, and of course the title is wrong.
I'll let you know whenever I put together a more interesting svg example. ;-)

Can't add to child array from "onmessage" in websockets application.

I am working on the third page of a project I call "Javascript Monads". The page is called "Javascript Monads Part 2" and is the third item down on the menu at http://schalk.net . It runs at http://schalk.net:3093/ .

I'm stuck on the usually trivial task of writing code to display chat messages. main.js starts with

"use strict";

import cow from './cow';
import snabbdom from 'snabbdom';
import h from 'snabbdom/h';

var newMessage = (v,mon) => {
  let ar = mM11.x;
  ar.push(h('div', mM16.x));
  mM11.ret(ar);
  return mon;
};
mM16.ret('One').bnd(newMessage);

When the web page is refreshed, "One" appears as expected.

      h('input', {style: inputStyle1, on: {keydown: updateLogin},  } ),
      h('div', {props: {id:'chat'}}, mM11.x ),

mM11 and mM16 are instances of Monad which is made available by a script tag in index.html. I had the same problem when I didn't use the Monad instances, so I hope they aren't too much of a distraction. I'll modify the code if you like. mM11.x is the value of mM11, and is an array created by h('div', ' One ' ) when the page loads and mM16.ret('One').bnd(newMessage) executes. The screen shot "After_reload.png" shows that everything succeeds as intended. mM11.x is shown in the console log in the screen shot.
When I run similar code from "onmessage" with "Two" hard coded in and "Three" received from the server, nothing appears on the webpage. The console log shows that mM11.x contains three objects, but the ones with text "Two" and "Three" show "elm: undefined" instead of "elm: div".
Here's the code in "onmessage":

          case "CD#$42":
            mM16.ret('Two').bnd(newMessage);
            mM16.ret(extra).bnd(newMessage).bnd(update);
          break;

As I mentioned above, I get the same behavior without using Monad instances, but I'll include the definition of Monad anyway. What I haven't been able to figure out is why "newMessage()" works as intended at the top of the file, but pushes an object with "elm: undefined" when called from inside "onmessage".

  class Monad {
    constructor(z) {

      this.x = z;

      this.bnd = (func, ...args) => {
        return func(this.x, this, ...args);
      };

      this.ret = a => {
        this.x = a;
        return this;
      };

      this.fmap = (f, mon = this, ...args) => {      
        mon.ret( f(mon.x, ...args));
        return mon;

      };
    }

The browser screenshots are from Chrome running http://schalk.net:3093 in Ubuntu 14.04. The code repository is at https://github.com/dschalk/websockets-monads-part2.
I am a refugee from React (See https://www.fpcomplete.com/user/dschalk/Websockets%20Game%20of%20Score?show=tutorials, running at http://schalk.net:3015/). I love what you and your collaborators are doing. I expect to eventually use pure functions and immutable data in my Javascript Monads project, but not until an application gets so complex that I see an advantage in doing so.
Here are the screen shots:
main js
after_browser_refresh
after_logging_in_as_d
after_sending_the_message_three

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.