Builds components using a simple and explicit API around virtual-dom

Overview

Logo

CI

Etch is a library for writing HTML-based user interface components that provides the convenience of a virtual DOM, while at the same time striving to be minimal, interoperable, and explicit. Etch can be used anywhere, but it was specifically designed with Atom packages and Electron applications in mind.

Overview

Etch components are ordinary JavaScript objects that conform to a minimal interface. Instead of inheriting from a superclass or building your component with a factory method, you access Etch's functionality by passing your component to Etch's library functions at specific points of your component's lifecycle. A typical component is structured as follows:

/** @jsx etch.dom */

const etch = require('etch')

class MyComponent {
  // Required: Define an ordinary constructor to initialize your component.
  constructor (props, children) {
    // perform custom initialization here...
    // then call `etch.initialize`:
    etch.initialize(this)
  }

  // Required: The `render` method returns a virtual DOM tree representing the
  // current state of the component. Etch will call `render` to build and update
  // the component's associated DOM element. Babel is instructed to call the
  // `etch.dom` helper in compiled JSX expressions by the `@jsx` pragma above.
  render () {
    return <div></div>
  }

  // Required: Update the component with new properties and children.
  update (props, children) {
    // perform custom update logic here...
    // then call `etch.update`, which is async and returns a promise
    return etch.update(this)
  }

  // Optional: Destroy the component. Async/await syntax is pretty but optional.
  async destroy () {
    // call etch.destroy to remove the element and destroy child components
    await etch.destroy(this)
    // then perform custom teardown logic here...
  }
}

The component defined above could be used as follows:

// build a component instance in a standard way...
let component = new MyComponent({foo: 1, bar: 2})

// use the component's associated DOM element however you wish...
document.body.appendChild(component.element)

// update the component as needed...
await component.update({bar: 2})

// destroy the component when done...
await component.destroy()

Note that using an Etch component does not require a reference to the Etch library. Etch is an implementation detail, and from the outside the component is just an ordinary object with a simple interface and an .element property. You can also take a more declarative approach by embedding Etch components directly within other Etch components, which we'll cover later in this document.

Etch Lifecycle Functions

Use Etch's three lifecycle functions to associate a component with a DOM element, update that component's DOM element when the component's state changes, and tear down the component when it is no longer needed.

etch.initialize(component)

This function associates a component object with a DOM element. Its only requirement is that the object you pass to it has a render method that returns a virtual DOM tree constructed with the etch.dom helper (Babel can be configured to compile JSX expressions to etch.dom calls). This function calls render and uses the result to build a DOM element, which it assigns to the .element property on your component object. etch.initialize also assigns any references (discussed later) to a .refs object on your component.

This function is typically called at the end of your component's constructor:

/** @jsx etch.dom */

const etch = require('etch')

class MyComponent {
  constructor (properties) {
    this.properties = properties
    etch.initialize(this)
  }

  render () {
    return <div>{this.properties.greeting} World!</div>
  }
}

let component = new MyComponent({greeting: 'Hello'})
console.log(component.element.outerHTML) // ==> <div>Hello World!</div>

etch.update(component[, replaceNode])

This function takes a component that is already associated with an .element property and updates the component's DOM element based on the current return value of the component's render method. If the return value of render specifies that the DOM element type has changed since the last render, Etch will switch out the previous DOM node for the new one unless replaceNode is false.

etch.update is asynchronous, batching multiple DOM updates together in a single animation frame for efficiency. Even if it is called repeatedly with the same component in a given event-loop tick, it will only perform a single DOM update per component on the next animation frame. That means it is safe to call etch.update whenever your component's state changes, even if you're doing so redundantly. This function returns a promise that resolves when the DOM update has completed.

etch.update should be called whenever your component's state changes in a way that affects the results of render. For a basic component, you can implement an update method that updates your component's state and then requests a DOM update via etch.update. Expanding on the example from the previous section:

/** @jsx etch.dom */

const etch = require('etch')

class MyComponent {
  constructor (properties) {
    this.properties = properties
    etch.initialize(this)
  }

  render () {
    return <div>{this.properties.greeting} World!</div>
  }

  update (newProperties) {
    if (this.properties.greeting !== newProperties.greeting) {
      this.properties.greeting = newProperties.greeting
      return etch.update(this)
    } else {
      return Promise.resolve()
    }
  }
}

// in an async function...

let component = new MyComponent({greeting: 'Hello'})
console.log(component.element.outerHTML) // ==> <div>Hello World!</div>
await component.update({greeting: 'Salutations'})
console.log(component.element.outerHTML) // ==> <div>Salutations World!</div>

There is also a synchronous variant, etch.updateSync, which performs the DOM update immediately. It doesn't skip redundant updates or batch together with other component updates, so you shouldn't really use it unless you have a clear reason.

Update Hooks

If you need to perform imperative DOM interactions in addition to the declarative updates provided by etch, you can integrate your imperative code via update hooks on the component. To ensure good performance, it's important that you segregate DOM reads and writes in the appropriate hook.

  • writeAfterUpdate If you need to write to any part of the document as a result of updating your component, you should perform these writes in an optional writeAfterUpdate method defined on your component. Be warned: If you read from the DOM inside this method, it could potentially lead to layout thrashing by interleaving your reads with DOM writes associated with other components.

  • readAfterUpdate If you need to read any part of the document as a result of updating your component, you should perform these reads in an optional readAfterUpdate method defined on your component. You should avoid writing to the DOM in these methods, because writes could interleave with reads performed in readAfterUpdate hooks defined on other components. If you need to update the DOM as a result of your reads, store state on your component and request an additional update via etch.update.

These hooks exist to support DOM reads and writes in response to Etch updating your component's element. If you want your hook to run code based on changes to the component's logical state, you can make those calls directly or via other mechanisms. For example, if you simply want to call an external API when a property on your component changes, you should move that logic into the update method.

etch.destroy(component[, removeNode])

When you no longer need a component, pass it to etch.destroy. This function will call destroy on any child components (child components are covered later in this document), and will additionally remove the component's DOM element from the document unless removeNode is false. etch.destroy is also asynchronous so that it can combine the removal of DOM elements with other DOM updates, and it returns a promise that resolves when the component destruction process has completed.

etch.destroy is typically called in an async destroy method on the component:

class MyComponent {
  // other methods omitted for brevity...

  async destroy () {
    await etch.destroy(this)

    // perform component teardown... here we just log for example purposes
    let greeting = this.properties.greeting
    console.log(`Destroyed component with greeting ${greeting}`)
  }
}

// in an async function...

let component = new MyComponent({greeting: 'Hello'})
document.body.appendChild(component.element)
assert(component.element.parentElement)
await component.destroy()
assert(!component.element.parentElement)

Component Composition

Nesting Etch Components Within Other Etch Components

Components can be nested within other components by referencing a child component's constructor in the parent component's render method, as follows:

/** @jsx etch.dom */

const etch = require('etch')

class ChildComponent {
  constructor () {
    etch.initialize(this)
  }

  render () {
    return <h2>I am a child</h2>
  }
}

class ParentComponent {
  constructor () {
    etch.initialize(this)
  }

  render () {
    return (
      <div>
        <h1>I am a parent</div>
        <ChildComponent />
      </div>
    )
  }
}

A constructor function can always take the place of a tag name in any Etch JSX expression. If the JSX expression has properties or children, these will be passed to the constructor function as the first and second argument, respectively.

/** @jsx etch.dom */

const etch = require('etch')

class ChildComponent {
  constructor (properties, children) {
    this.properties = properties
    this.children = children
    etch.initialize(this)
  }

  render () {
    return (
      <div>
        <h2>I am a {this.properties.adjective} child</h2>
        <h2>And these are *my* children:</h2>
        {this.children}
      </div>
    )
  }
}

class ParentComponent {
  constructor () {
    etch.initialize(this)
  }

  render () {
    return (
      <div>
        <h1>I am a parent</div>
        <ChildComponent adjective='good'>
          <div>Grandchild 1</div>
          <div>Grandchild 2</div>
        </ChildComponent>
      </div>
    )
  }
}

If the properties or children change during an update of the parent component, Etch calls update on the child component with the new values. Finally, if an update causes the child component to no longer appear in the DOM or the parent component itself is destroyed, Etch will call destroy on the child component if it is implemented.

Nesting Non-Etch Components Within Etch Components

Nothing about the component composition rules requires that the child component be implemented with Etch. So long as your constructor builds an object with an .element property and an update method, it can be nested within an Etch virtual DOM tree. Your component can also implement destroy if you want to perform teardown logic when it is removed from the parent component.

This feature makes it easy to mix components written in different versions of Etch or wrap components written in other technologies for integration into an Etch component. You can even just use raw DOM APIs for simple or performance-critical components and use them straightforwardly within Etch.

Keys

To keep DOM update times linear in the size of the virtual tree, Etch applies a very simple strategy when updating lists of elements. By default, if a child at a given location has the same tag name in both the previous and current virtual DOM tree, Etch proceeds to apply updates for the entire subtree.

If your virtual DOM contains a list into which you are inserting and removing elements frequently, you can associate each element in the list with a unique key property to identify it. This improves performance by allowing Etch to determine whether a given element tree should be inserted as a new DOM node, or whether it corresponds to a node that already exists that needs to be updated.

References

Etch interprets any ref property on a virtual DOM element as an instruction to wire a reference to the underlying DOM element or child component. These references are collected in a refs object that Etch assigns on your component.

class ParentComponent {
  constructor () {
    etch.initialize(this)
  }

  render () {
    return (
      <div>
        <span ref='greetingSpan'>Hello</span>
        <ChildComponent ref='childComponent' />
      </div>
    )
  }
}

let component = new ParentComponent()
component.refs.greetingSpan // This is a span DOM node
component.refs.childComponent // This is a ChildComponent instance

Note that ref properties on normal HTML elements create references to raw DOM nodes, while ref properties on child components create references to the constructed component object, which makes its DOM node available via its element property.

Handling Events

Etch supports listening to arbitrary events on DOM nodes via the special on property, which can be used to assign a hash of eventName: listenerFunction pairs:

class ComponentWithEvents {
  constructor () {
    etch.initialize(this)
  }

  render () {
    return <div on={{click: this.didClick, focus: this.didFocus}} />
  }

  didClick (event) {
    console.log(event) // ==> MouseEvent {...}
    console.log(this) // ==> ComponentWithEvents {...}
  }

  didFocus (event) {
    console.log(event) // ==> FocusEvent {...}
    console.log(this) // ==> ComponentWithEvents {...}
  }
}

As you can see, the listener function's this value is automatically bound to the parent component. You should rely on this auto-binding facility rather than using arrow functions or Function.bind to avoid complexity and extraneous closure allocations.

Assigning DOM Attributes

With the exception of SVG elements, Etch assigns properties on DOM nodes rather than HTML attributes. If you want to bypass this behavior and assign attributes instead, use the special attributes property with a nested object. For example, a and b below will yield the equivalent DOM node.

const a = <div className='foo' />
const b = <div attributes={{class: 'foo'}} />

This can be useful for custom attributes that don't map to DOM node properties.

Organizing Component State

To keep the API surface area minimal, Etch is deliberately focused only on updating the DOM, leaving management of component state to component authors.

Controlled Components

If your component's HTML is based solely on properties passed in from the outside, you just need to implement a simple update method.

class ControlledComponent {
  constructor (props) {
    this.props = props
    etch.initialize(this)
  }

  render () {
    // read from this.props here
  }

  update (props) {
    // you could avoid redundant updates by comparing this.props with props...
    this.props = props
    return etch.update(this)
  }
}

Compared to React, control is inverted. Instead of implementing shouldComponentUpdate to control whether or not the framework updates your element, you always explicitly call etch.update when an update is needed.

Stateful Components

If your render method's output is based on state managed within the component itself, call etch.update whenever this state is updated. You could store all state in a sub-object called state like React does, or you could just use instance variables.

class StatefulComponent {
  constructor () {
    this.counter = 0
    etch.initialize(this)
  }

  render () {
    return (
      <div>
        <span>{this.counter}</span>
        <button onclick={() => this.incrementCounter()}>
          Increment Counter
        </button>
      </div>
    )
  }

  incrementCounter () {
    this.counter++
    // since we updated state we use in render, call etch.update
    return etch.update(this)
  }
}

What About A Component Superclass?

To keep this library small and explicit, we're favoring composition over inheritance. Etch gives you a small set of tools for updating the DOM, and with these you can accomplish your objectives with some simple patterns. You could write a simple component superclass in your application to remove a bit of boilerplate, or even publish one on npm. For now, however, we're going to avoid taking on the complexity of such a superclass into this library. We may change our mind in the future.

Customizing The Scheduler

Etch exports a setScheduler method that allows you to override the scheduler it uses to coordinate DOM writes. When using Etch inside a larger application, it may be important to coordinate Etch's DOM interactions with other libraries to avoid synchronous reflows.

For example, when using Etch in Atom, you should set the scheduler as follows:

etch.setScheduler(atom.views)

Read comments in the scheduler assignment and default scheduler source code for more information on implementing your own scheduler.

Performance

The github.com/krausest/js-framework-benchmark runs various benchmarks using different frameworks. It should give you an idea how etch performs compared to other frameworks.

Checkout the benchmarks here.

Feature Requests

Etch aims to stay small and focused. If you have a feature idea, consider implementing it as a library that either wraps Etch or, even better, that can be used in concert with it. If it's impossible to implement your feature outside of Etch, we can discuss adding a hook that makes your feature possible.

Comments
  • Components without an update method throw an error when updated

    Components without an update method throw an error when updated

    The readme claims that any class that constructs an object with an .element property can be used as a component, but component-widget.js attempts to call update in line 63 without checking if it is defined, despite a comment above the offending function that seems to agree with the readme.

    opened by mikedeltalima 17
  • Adding Types

    Adding Types

    This is a work in progress, so feel free to give suggestions, feedback, or engage!

    • Adding type definitions
    old PR

    Description of the Change - Release Notes

    • [X] Converting codebase source to typescript while being completely backward-compatible - Fixes https://github.com/atom/etch/issues/80
    • [x] getting index.d.ts to expose the types so import {dom} from 'etch' gives dom's information in IntelliSense

    Maybe later:

    • Adding type definitions
    • Optimizing the code wherever possible

    Verification Process

    How to review?

    • Use the commit history instead of going through the files: https://github.com/atom/etch/pull/82/commits

    Possible Drawbacks

    • Nothing (backward compatible - zero change in the API and JavaScript code)

    Alternate Designs

    • using @types/etch. But this doesn't allow us to use the power of typescript for optimizing etch and catching the bugs.
    opened by aminya 16
  • Support multi-dimensional refs

    Support multi-dimensional refs

    Allows refs to be multi-dimensional

    <input type="checkbox" ref="selection[foo]" />
    <input type="checkbox" ref="selection[bar]" />
    

    can be accessed with component.refs.selection.foo and component.refs.selection.bar.

    Can go as deep as you want.

    opened by Arcath 16
  • Function refs

    Function refs

    As discussed in https://github.com/atom/etch/pull/50#issuecomment-322491087, accepting a function as a value for ref property seems like a pretty lucrative idea.

    So I was tired of waiting until someone else does that, and here's my stab at it.

    The change itself is somewhat trivial, but I should say that I have only a passing knowledge of etch's code base, so I might've missed some corner cases here or there. I hope someone with a more in-depth knowledge could advise me.

    Tests are somewhat wordy, mostly because it should work pretty much the same for both 'standard' dom nodes and Etch components, hence the test-suite is basically repeated twice. Tests are far from being comprehensive but should cover the most basic stuff.

    A point of discussion, I'm not sure whether when a component is deleted, or ref value is changed, the ref function should be called with undefined or null. I personally find that while null has its uses, in most cases it's interchangeable with undefined, so I try to avoid it in my code (because it's impossible to avoid undefined). But since Etch already seems to prefer null in some cases, maybe using null here would be more consistent. FWIW, React uses null:

    React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

    (from https://reactjs.org/docs/refs-and-the-dom.html)

    Won't argue with either, ~~but for now, I used undefined mostly due to the force of habit.~~

    Update: changed to null for the sake of consistency if nothing else.

    One thing to keep in mind. Using stuff like this

    // ...
    render() {
      return <div ref={node => this.div = node}>...</div>
    }
    // ...
    

    will likely kill rendering performance, because

    1. Arrow function would be re-created on each render
    2. New arrow function won't ever be strict-equal to old arrow function, so updateRef would be executed on each render (which means ref would be called twice per render)

    React's documentation actually suggests doing this, and I don't know how they get around the issue. There is, however, a straightforward workaround available: have a bound function defined outside of render

    // ...
    constructor() {
      this.updateDivRef = node => this.div = node
      // ...
      etch.initialize(this)
    }
    // ...
    render() {
      return <div ref={this.updateDivRef}>...</div>
    }
    // ...
    

    TODO:

    • [ ] Decide on undefined vs null
    • [ ] Add some documentation to README.
    opened by lierdakil 9
  • Allow plain functions to be used as components

    Allow plain functions to be used as components

    Often, a component only needs to take in props/children and render something, and does not maintain any internal state. In those instances, it can be useful to define the component as a function of props and children.

    This adds etch.stateless(renderFn) that implements a component that renders renderFn with props and children during initialize and update.

    @kuychaco has brought up the excellent point that etch.stateless isn't the best name for this; I'm totally open to suggestions

    Signed-off-by: Katrina Uychaco [email protected]

    opened by BinaryMuse 9
  • refs are being assigned to the wrong component

    refs are being assigned to the wrong component

    Looking at the following example:

    class MainComponent {
      //...
      render () {
        class Component {
          constructor (props, children) {
            this.children = children
            this.props = props
    
            etch.initialize(this)
          }
    
          update () {
            return Promise.resolve()
          }
    
          render () {
            return (<div id={this.props.id}>{ this.children }</div>)
          }
        }
    
        return (
          <Component id='outer' ref="outer">
            <Component id='middle' ref="middle">
              <div id="inner" ref="inner" />
            </Component>
          </Component>
        )
      }
    }
    

    I would expect all ref's to be applied to the MainComponent instance. Instead, I am seeing MainComponent with the nested object refs.outer.refs.middle.refs.inner. Surely this is wrong. If the Component class happened to also ref one of its element, with the name 'middle' or 'inner', all hell would break loose.

    opened by twifty 8
  • JSX Dynamic Component Name

    JSX Dynamic Component Name

    Hi,

    Would be thankful for any hints how to render Dynamic Components. Similar to this question.

    I tried different options but it doesn't work after etch.update(this).

    Use case

    class MyComponent {
      constructor (properties) {
        this.properties = properties
        etch.initialize(this)
      }
    
      renderDynComponent () {
        if (case1) {
          return <DynComponent1 />
        }
        else if (case2) {
          return <DynComponent2 />
        }
        return <DynComponentDefault />
      }
    
      render () {
        return <div>{this.renderDynComponent()}</div>
      }
    }
    

    Thanks!

    opened by ivankravets 8
  • Return a promise from updateElement

    Return a promise from updateElement

    I've hit a few situations where I've needed to take action after an update has completed, usually things like registering new event listeners on newly available elements. I'm using getNextUpdatePromise() now, but it occurred to me that it would be convenient to return the update promise from updateElement directly:

    etch.updateElement(this).then(() => {
      // Use this.refs
    })
    

    A minor change, but one that would save callers from an extra import and read more nicely. What do you think?

    opened by smashwilson 7
  • Optimize the DOM vnode factory

    Optimize the DOM vnode factory

    This is to help make performance more predictable.

    • Generates less garbage when subtrees are involved.
    • Avoids a slow splice operation, when we need to check every entry anyways.
    • Avoid searching for event listeners unless we have an obvious prefix.
    opened by dead-claudia 6
  • Some SVG attributes are stripped before rendering

    Some SVG attributes are stripped before rendering

    Steps to reproduce:

    1. Try sticking this JSX in a component's render method:

      <svg className='about-logo' width='330px' height='68px' viewBox='0 0 330 68'>
        <g stroke='none' strokeWidth='1' fill='none' fillRule='evenodd'>
          <g transform='translate(2.000000, 1.000000)'>
            <g transform='translate(96.000000, 8.000000)' fill='currentColor'>
              <path d='M185.498,3.399 C185.498,2.417 186.34,1.573 187.324,1.573 L187.674,1.573 C188.447,1.573 189.01,1.995 189.5,2.628 L208.676,30.862 L227.852,2.628 C228.272,1.995 228.905,1.573 229.676,1.573 L230.028,1.573 C231.01,1.573 231.854,2.417 231.854,3.399 L231.854,49.403 C231.854,50.387 231.01,51.231 230.028,51.231 C229.044,51.231 228.202,50.387 228.202,49.403 L228.202,8.246 L210.151,34.515 C209.729,35.148 209.237,35.428 208.606,35.428 C207.973,35.428 207.481,35.148 207.061,34.515 L189.01,8.246 L189.01,49.475 C189.01,50.457 188.237,51.231 187.254,51.231 C186.27,51.231 185.498,50.458 185.498,49.475 L185.498,3.399 L185.498,3.399 Z'></path>
              <path d='M113.086,26.507 L113.086,26.367 C113.086,12.952 122.99,0.941 137.881,0.941 C152.77,0.941 162.533,12.811 162.533,26.225 L162.533,26.367 C162.533,39.782 152.629,51.792 137.74,51.792 C122.85,51.792 113.086,39.923 113.086,26.507 M158.74,26.507 L158.74,26.367 C158.74,14.216 149.89,4.242 137.74,4.242 C125.588,4.242 116.879,14.075 116.879,26.225 L116.879,26.367 C116.879,38.518 125.729,48.491 137.881,48.491 C150.031,48.491 158.74,38.658 158.74,26.507'></path>
              <path d='M76.705,5.155 L60.972,5.155 C60.06,5.155 59.287,4.384 59.287,3.469 C59.287,2.556 60.059,1.783 60.972,1.783 L96.092,1.783 C97.004,1.783 97.778,2.555 97.778,3.469 C97.778,4.383 97.005,5.155 96.092,5.155 L80.358,5.155 L80.358,49.405 C80.358,50.387 79.516,51.231 78.532,51.231 C77.55,51.231 76.706,50.387 76.706,49.405 L76.706,5.155 L76.705,5.155 Z'></path>
              <path d='M0.291,48.562 L21.291,3.05 C21.783,1.995 22.485,1.292 23.75,1.292 L23.891,1.292 C25.155,1.292 25.858,1.995 26.348,3.05 L47.279,48.421 C47.49,48.843 47.56,49.194 47.56,49.546 C47.56,50.458 46.788,51.231 45.803,51.231 C44.961,51.231 44.329,50.599 43.978,49.826 L38.219,37.183 L9.21,37.183 L3.45,49.897 C3.099,50.739 2.538,51.231 1.694,51.231 C0.781,51.231 0.008,50.529 0.008,49.685 C0.009,49.404 0.08,48.983 0.291,48.562 L0.291,48.562 Z M36.673,33.882 L23.749,5.437 L10.755,33.882 L36.673,33.882 L36.673,33.882 Z'></path>
            </g>
            <g>
              <path d='M40.363,32.075 C40.874,34.44 39.371,36.77 37.006,37.282 C34.641,37.793 32.311,36.29 31.799,33.925 C31.289,31.56 32.791,29.23 35.156,28.718 C37.521,28.207 39.851,29.71 40.363,32.075' fill='currentColor'></path>
              <path d='M48.578,28.615 C56.851,45.587 58.558,61.581 52.288,64.778 C45.822,68.076 33.326,56.521 24.375,38.969 C15.424,21.418 13.409,4.518 19.874,1.221 C22.689,-0.216 26.648,1.166 30.959,4.629' stroke='currentColor' strokeWidth='3.08' strokeLinecap='round'></path>
              <path d='M7.64,39.45 C2.806,36.94 -0.009,33.915 0.154,30.79 C0.531,23.542 16.787,18.497 36.462,19.52 C56.137,20.544 71.781,27.249 71.404,34.497 C71.241,37.622 68.127,40.338 63.06,42.333' stroke='currentColor' strokeWidth='3.08' strokeLinecap='round'></path>
              <path d='M28.828,59.354 C23.545,63.168 18.843,64.561 15.902,62.653 C9.814,58.702 13.572,42.102 24.296,25.575 C35.02,9.048 48.649,-1.149 54.736,2.803 C57.566,4.639 58.269,9.208 57.133,15.232' stroke='currentColor' strokeWidth='3.08' strokeLinecap='round'></path>
            </g>
          </g>
        </g>
      </svg>
      
    2. The fillRule and strokeWidth attributes (and others too, probably) are stripped from the rendered DOM element.

    bug 
    opened by mnquintana 6
  • Changing the root DOM node of a component

    Changing the root DOM node of a component

    Since Etch components must opt-in to updates via the update method, and Etch updates each one individually via performElementUpdate, there is a situation where patching does not work as expected. Here is a test case to demonstrate:

    class Component {
      constructor () {
        this.renderDiv = true
        etch.createElement(this)
      }
    
      render () {
        if (this.renderDiv) {
          return <div>Imma Div</div>
        } else {
          return <span>Imma Span</span>
        }
      }
    }
    
    let component = new Component()
    component.renderDiv = false
    etch.updateElementSync(component)
    

    If you're anything like me, you might be surprised that component.element.outerHTML is still <div>Imma Div</div>. This actually makes perfect sense, because virtual-dom can't actually patch the div to make it a span; in fact, patch returns a new root node so that you can do whatever you need to with it.

    This is particularly troublesome in Etch because each component's element is patched independently; for example, imagine a scenario where a top-level component renders a different component depending on a flag, and those components each render yet another component:

    ┌───────────────────────────────────────────────────────────────────────┐
    │ ┌───────────────────────────────────────────────────────────────────┐ │
    │ │                          <Grandparent />                          │ │
    │ └───────────────────────────────────────────────────────────────────┘ │
    │                                   │                                   │
    │             Flag True             │            Flag False             │
    │                                   │                                   │
    │                                   │                                   │
    │ ┌───────────────────────────────┐ │ ┌───────────────────────────────┐ │
    │ │          <ParentA />          │ │ │          <ParentB />          │ │
    │ └───────────────────────────────┘ │ └───────────────────────────────┘ │
    │                 │                 │                 │                 │
    │                 │                 │                 │                 │
    │                 ▼                 │                 ▼                 │
    │ ┌───────────────────────────────┐ │ ┌───────────────────────────────┐ │
    │ │          <ChildA />           │ │ │          <ChildB />           │ │
    │ └───────────────────────────────┘ │ └───────────────────────────────┘ │
    │                 │                 │                 │                 │
    │                 │                 │                 │                 │
    │                 ▼                 │                 ▼                 │
    │ ┌───────────────────────────────┐ │ ┌───────────────────────────────┐ │
    │ │            <div />            │ │ │           <span />            │ │
    │ └───────────────────────────────┘ │ └───────────────────────────────┘ │
    └───────────────────────────────────────────────────────────────────────┘
    

    In this case, it's not obvious that the root DOM node of Grandparent might change from a div to a span, since ChildA and ChildB may be far removed, or rendered only in certain conditions, or among a larger tree of other components.

    @nathansobo and I discussed a few ways to handle this issue (Nathan please remind me if I forgot any):

    1. Just don't support returning a different type of root DOM node from a component's render

      This has potential advantages conceptually (e.g. a component only ever maps to a single DOM node, which will always be the same reference). A small change to performElementUpdate to detect the root node type changing could be used to implement this cleanly.

      To deal with this, I'd imagine components would either have their contents wrapped in lots of divs or else components would need to be less fine-grained than you might see in other component frameworks (e.g. React).

    2. Automatically swap out nodes in Widget#destroy if we detect the node has a parent

      In this case, we would do what I think the user probably expects most of the time. It doesn't work for the root DOM node of the root component unless the user has attached it to the DOM before it updates for the first time, but works nicely for components further down the component hierarchy. One potential downside of this technique is that the user doesn't have an opportunity to clean up e.g. event handlers or other references to DOM nodes.

      We realized that the reason this isn't an issue with React is the synthetic event system.

    3. Provide an API that is called when the root node is changed / needs to be updated

      This would solve the issue when the root DOM node for the root component changes (as discussed in option 2), and would allow users to have a chance to clean up references to the nodes if necessary. However, this introduces a fair amount of new complexity into the library, and it's unclear if it's worth it.

    4. Force the user to provide a container

      This type of issue is probably why React, et al. requires a container, but we'd like to avoid this.

    opened by BinaryMuse 6
  • Null-elements are not allowed?

    Null-elements are not allowed?

    There are use-cases when it is not necessary to create an element for a component, for example, when we render WebGL/regl or canvas2d layers:

    <canvas id="canvas">
    <Grid canvas="#canvas" type="cartesian" />
    <Plot canvas="#canvas" data={data} />
    <Text canvas="#canvas" text="Test Plot" />
    

    Would that be reasonable to disable strong assertion of instance.element property? Or not forcing render to return etch virtual-dom?

    Faced this issue trying to make gl-component API compatible with etch.

    opened by dy 1
  • How to move an Etch component's child?

    How to move an Etch component's child?

    Consider the following scenario:
    I have a root component that holds some rows. I also have a button that should be a child of the latest row at all times.

    On the root component creation it holds a single row which in turn holds the button, so the inital markup looks like this:

    <Root>
      <Row ref="row0">
        <Button ref="btn" />
      </Row>
    </Root>
    

    Then at some point I append another Row inside Root and I want the markup to look like this:

    <Root>
      <Row ref="row0"></Row>
      <Row ref="row1">
        <Button ref="btn" />  // this should point to the same DOM node as the previous Button
      </Row>
    </Root>
    

    Here's my attempt at doing this:

    class Button {
      constructor() {
        etch.initialize(this);
      }
    
      render() {
        return (
          <button>Test</button>
        );
      }
    
      update() {
        return etch.update(this);
      }
    }
    
    class Row {
      constructor(props, children) {
        this.children = children;
        etch.initialize(this);
      }
    
      render() {
        return (
          <div>
            {this.children}
          </div>
        );
      }
    
      update() {
        return etch.update(this);
      }
    }
    
    export default class Root {
      constructor() {
        this.otherRows = [];
        this.rowCount = 1;
        etch.initialize(this);
      }
    
      render() {
        return (
          <div>
            <Row ref="row0">
              <Button ref="btn" />
            </Row>
            {this.otherRows}
          </div>
        );
      }
    
      addRow() {
        const lastRow = this.refs[`row${this.rowCount - 1}`];
        const button = lastRow.children.pop();
        const newRow = new Row({}, [button]);
    
        this.otherRows.push(newRow);
        this.update();
        this.rowCount++;
      }
    
      update() {
        return etch.update(this);
      }
    }
    

    And when I call the addRow method after Root's establishment, I get the following markup:

    <div> // This is the Root
      <div>  // This is a Row
        <button />
      </div>
      <undefined>
        <button />
      </undefined>
    </div>
    

    And it seems like the two buttons that appear in the markup are different DOM nodes.
    How do I achieve my goal?

    opened by illright 4
  • Add support for reverting the value of a controlled input or select

    Add support for reverting the value of a controlled input or select

    Imagine you want a "controlled" color picker, so write the following:

    class ColorPicker {
      constructor(props) {
        this.props = props;
        etch.initialize(this);
      }
      handleChange(event) {
        const value = event.target.value;
    
        if (value !== this.props.value) {
          // revert the value so that it stays consistent with the `props`
          // this is the part that doesn't currently work <------------------------------
          etch.update(this);
    
          // notify the parent of the change
          this.props.onChange(value);
        }
      }
      render() {
        return <input {...this.props} type="color" onChange={this.handleChange} />;
      }
      update(nextProps) {
        if (shallowDiffers(this.props, nextProps)) {
          this.props = nextProps;
          etch.update(this);
        }
      }
    }
    

    And imagine you want to have an instance that refuses some colors:

    const picker = new ColorPicker({value: '#fff', onChange: handleChange});
    document.body.appendChild(picker.element)
    
    function handleChange(color) {
      if (color.endsWith('ff')) {
        // color must have the blue at max
        picker.update({value: color, onChange: handleChange});
      }
    }
    

    This is not currently possible because when the etch.update(this) in the handleChange is called, it calls updateProps which updates the input.value only if the new value is !== than the old one. But in this case the new value is always === the old one. Ref. lib/update-props.js:59

    This PR solves this case for input and select type elements.

    opened by zaygraveyard 0
  • Add support for `false` as child

    Add support for `false` as child

    This allows the following notation:

    render() {
      const {on} = this.props;
    
      return <div>{on && 'Is on'}</div>;
    }
    

    Where on is a boolean

    opened by zaygraveyard 0
  • Children can't be modified without instantiating new component instances?

    Children can't be modified without instantiating new component instances?

    For example, since a component constructor receives children in the second arg, then if children ever change, the only way to have it updated is constructing a new instance? This is unlike React, where the instance is kept alive, and this.props.children is modified. Could this be hint that new instances are being created when maybe there's an alternate way to avoid creating new instances (and thus reduce overhead)?

    (same with props if those are only received through constructor)

    opened by trusktr 1
Owner
Atom
Free and open source text editor, brought to you by GitHub
Atom
Pure and simple virtual DOM library

Maquette Maquette is a Javascript utility which makes it easy to synchronize the DOM tree in the browser with your data. It uses a technique called 'V

AFAS Software 736 Jan 4, 2023
Atomico a micro-library for creating webcomponents using only functions, hooks and virtual-dom.

Atomico simplifies learning, workflow and maintenance when creating webcomponents. Scalable and reusable interfaces: with Atomico the code is simpler

Atomico 898 Dec 31, 2022
Million is a lightweight (<1kb) Virtual DOM. It's really fast and makes it easy to create user interfaces.

?? Watch Video ?? Read the docs ?? Join our Discord What is Million? Million is a lightweight (<1kb) Virtual DOM. It's really fast and makes it easy t

Derek Jones 5 Aug 24, 2022
minimalist virtual dom library

petit-dom A minimalist virtual DOM library. Supports HTML & SVG elements. Supports Render functions and Fragments. Custom components allows to build y

Yassine Elouafi 485 Dec 12, 2022
A Fast & Light Virtual DOM Alternative

hyper(HTML) ?? Community Announcement Please ask questions in the dedicated discussions repository, to help the community around this project grow ♥ A

Andrea Giammarchi 3k Dec 30, 2022
Component oriented framework with Virtual dom (fast, stable, with tooling)

Bobril Main site bobril.com Changelog of npm version: https://github.com/Bobris/Bobril/blob/master/CHANGELOG.md Component oriented framework inspired

Boris Letocha 359 Dec 4, 2022
A demo to show how to re-use Eleventy Image’s disk cache across Netlify builds.

Re-use Eleventy Image Disk Cache across Netlify Builds Live Demo This repository takes all of the high resolution browser logos and processes them thr

Eleventy 9 Apr 5, 2022
Storybook add-on to enable SWC builds.

storybook-addon-swc Storybook addon that improves build time by building with swc. ?? Examples webpack4 webpack5 ?? Installation $ npm install -D stor

Karibash 49 Dec 20, 2022
Portfolioshop builds custom portfolio websites with submitted user data.

Portfolio Shop What our project does? We are trying to build a website to make the process of building personal portfolios easier. Often we have seen

Portfolio Shop 44 Dec 22, 2022
🤖 Persist the Playwright executable between Netlify builds

?? Netlify Plugin Playwright Cache Persist the Playwright executables between Netlify builds. Why netlify-plugin-playwright-cache When you install pla

Hung Viet Nguyen 14 Oct 24, 2022
Stacks Voice is a reference project that builds on the SIP018 signed structured data standard to create an accountless internet forum.

Stacks Voice Stacks Voice is a reference project that builds on the SIP018 signed structured data standard to create an accountless internet forum. Th

Clarity Innovation Lab 4 Dec 21, 2022
A GitHub action to automate Rojo project builds.

Rojo Build Action This action swiftly builds your rojo places, models & assets. Inputs output Required This is the file you want the action to output

Compey 3 Oct 23, 2022
Custom Vitest matchers to test the state of the DOM, forked from jest-dom.

vitest-dom Custom Vitest matchers to test the state of the DOM This library is a fork of @testing-library/jest-dom. It shares that library's implement

Chance Strickland 14 Dec 16, 2022
An extension of DOM-testing-library to provide hooks into the shadow dom

Why? Currently, DOM-testing-library does not support checking shadow roots for elements. This can be troublesome when you're looking for something wit

Konnor Rogers 28 Dec 13, 2022
An app to manage tasks. A user can add, delete and edit a task and mark it as completed, It uses simple GUI and relies on DOM manipulation in pure JS and using local storage.

An app to manage tasks. A user can add, delete and edit a task and mark it as completed, It uses simple GUI and relies on DOM manipulation in pure JS and using local storage.

KHITER Mohamed Achraf 6 Aug 20, 2022
API para Ocean AR Hackathon por innovación virtual.

Ocean-AR-Backend API para Ocean AR Hackathon por innovación virtual. Dependencies Dependencies Installation npm i express cors jsonwebtoken sequelize

Luis Armando Prado 3 May 14, 2022
Shizuku Launcher is a simple AWS Virtual Machine helper.

shizuku-launcher-web Shizuku Launcher is a simple AWS Virtual Machine helper. Shizuku Launcher offers multiple solutions to keep your credential secur

Seraphim Lou 16 Oct 11, 2022
JS Cloudimage 360 View - A simple, interactive resource that can be used to provide a virtual tour of your product

JS Cloudimage 360 View - A simple, interactive resource that can be used to provide a virtual tour of your product

Scaleflex 1.9k Jan 7, 2023
Shizuku Launcher is a simple AWS Virtual Machine helper. Now in Next.js

Shizuku Launcher Shizuku Launcher is a simple AWS Virtual Machine helper. Shizuku Launcher offers multiple solutions to keep your credential security

Seraphim Lou 50 Jan 3, 2023