News for hackers. Stuff that matters.
Re:React Fiber Architecture by jiaweihli on Sunday August 07, 2016 @06:03PM (#12243933)
Can someone explain the benefits of React's DOM diffing model?

Rather than try to diff two DOM trees and optimize reconciliation, why not use one-way data binding and update exactly what has changed, with 0 reconciliation cost? Either way, the upfront work - linking DOM elements with model attributes - is the same. In JSX this is done by interpolating variables into the template, and in one-way data binding this is done via data attributes.

Anecdotally, I've found one-way data binding (using Rivets[1]) to be very fast in practice for a view hierarchy ~10 layers deep.

[1] http://rivetsjs.com/

Re:React Fiber Architecture by Silhouette on Sunday August 07, 2016 @08:11PM (#12244536)
Rather than try to diff two DOM trees and optimize reconciliation, why not use one-way data binding and update exactly what has changed, with 0 reconciliation cost?

If all of your rendered HTML corresponds 1:1 with the underlying data model, there's no particular advantage to the declarative approach used by React.

However, once you start to have relationships in the underlying data, so DOM events in one place can affect the desired DOM content somewhere else, simple one-way data binding is not sufficient.

For example, suppose we have an HTML table that needs to be rendered from some underlying data structure in our JS. How do you do that with simple one-way data binding -- what are you binding to what, exactly? If you're managing the HTML directly, you need to allow for things like rows being added or removed, not just updating the content of an individual cell.

Now suppose that table also allows you to sort by different columns and filter so only certain rows are shown. Rendering the correct HTML now requires keeping track of the underlying data model and all of the UI-related state, with the actual rows to be shown affected by several different factors.

Now suppose the table is going to have many rows, and pagination is required in the markup and controls.

You certainly can handle all of the related events manually, but in order to keep the rendered HTML correct you now need to write code that understands each possible change in the underlying data and UI in every possible context, and the combinatorics can get quite unpleasant here.

The alternative that declarative rendering tools like React offer is that you can specify what your rendered table should look like in absolute terms, using whatever inputs need to be considered but ignoring the existing state of the DOM. You still need to consider however many factors you have that affect the rendering, which might still be somewhat complicated in a case like this, but at least you only need to consider them from a single, neutral starting point, not relative to every possible starting point.

Re:React Fiber Architecture by spankalee on Sunday August 07, 2016 @08:28PM (#12244615)
I don't get how your table example justifies the need for such a complex rendering pipeline.

There are plenty of template libraries that can optimally re-render a list/table after row insert/remove/move operations. Events generated by elements in rows can easily be associated with the proper data item.

React doesn't own declarative templating, and if you only use one-way databinding, and re-render only what changes (again, plenty of template libraries do this), you get `v=f(d)` and efficient updates. Why the extra complexity?

Re:React Fiber Architecture by Silhouette on Sunday August 07, 2016 @08:48PM (#12244696)
The table was just an example. The point is that if you use a declarative rendering approach, any non-trivial rendered output you want to generate only needs to be specified once, relative to a neutral starting point.

React certainly doesn't own the idea of declarative rendering, I agree, but what template libraries do you have in mind that offer that sort of functionality without either being limited to some specific case (tables, say), having questionable performance properties, or implementing the same sorts of techniques that virtual DOM-based libraries like React are using?

Perhaps it would help if you could give some concrete examples of the libraries you are thinking of, and point at some documentation (or give your own example code) to show how they would handle the kinds of events I described in my post above more efficiently and/or with cleaner code than a library using declarative rendering and a virtual DOM such as React.

Re:React Fiber Architecture by jiaweihli on Sunday August 07, 2016 @08:51PM (#12244718)
Are you thinking of computed properties? If so, there are many libraries that have solved this, e.g.:

https://vuejs.org/guide/computed.html

https://guides.emberjs.com/v2.3.0/object-model/computed-prop...

When implemented using one-way data binding (as both of the examples do), this is more performant than DOM diffing.

Re:React Fiber Architecture by Silhouette on Sunday August 07, 2016 @09:02PM (#12244771)
No, I'm talking about arbitrary relationships in the underlying data model, such that arbitrary events from anywhere in the DOM can lead to arbitrary changes in rendering anywhere in the DOM.

Computed properties of the kind you linked to, when then used to drive rendering via one-way data binding, are a common but relatively simple example.

And yes, that sort of direct DOM manipulation is likely to be faster, often much faster, than DOM diffing in the cases it covers. The advantage of the more general diff-based libraries is their generality, not their rendering speed.

Re:React Fiber Architecture by jiaweihli on Sunday August 07, 2016 @09:43PM (#12244955)
Can you give an example of a more general problem that you see React solving better? The example you gave earlier doesn't fully answer this.
Re:React Fiber Architecture by Silhouette on Sunday August 07, 2016 @10:52PM (#12245185)
Just imagine any non-trivial set of relationships in the underlying data, and then some rendered content that doesn't just depend on individual data points.

For the record, I haven't actually seen anyone address my earlier example with the sorted/filtered/paginated table yet.

Another typical example might be a complicated form where some fields are shown or hidden or have different options available depending on the values of other fields, perhaps including circular dependencies.

Another might be some sort of dashboard that adds a tab/tile/panel for each of some varying set of data sources and adjusts the layout or level of detail depending on how many sources need to be included.

Another might be rendering a chart showing several different data series over time, where the scales and positions of the axes are adapted to span the entire data set.

Of course you could manually update the DOM in response to relevant changes in the data in all of these cases, but keeping track of all the different variations and transitions gets old very quickly once your UI has a few different cases like this.

Re:React Fiber Architecture by jiaweihli on Sunday August 07, 2016 @11:06PM (#12245239)
I think I understand what you're getting at - correct me if I'm wrong.

React's templating allows you to execute arbitrary JS logic when rendering, which is more versatile than simple one-way data binding.

My thoughts there are that I'd probably extract the logic first into the view model before passing the buck to the templater. For example, instead of filtering/sorting a collection in the template, I'd create a `normalizedCollection` computed property in the view model first (which helps with testing as well). In practice I've found that Rivets' binders are enough - showing/hiding/looping over data covers nearly every UI.

In the case of bigger chunks getting un/re-rendered (such as adding tabs/tiles/panels), you can take advantage of a framework that does sub-view management (such as Marionette[1]).

Computed properties can solve the hidden fields and multi-data series chart problem you mentioned.

[1] http://marionettejs.com/docs/v2.4.7/marionette.layoutview.ht...

Re:React Fiber Architecture by Silhouette on Sunday August 07, 2016 @11:37PM (#12245346)
React's templating allows you to execute arbitrary JS logic when rendering, which is more versatile than simple one-way data binding.

Yes, that's what I'm getting at here. In particular, you only have to write that arbitrary JS logic once to cover both the rendering and all the updating cases, so you get the same kind of automagic monitoring in your view that data binding gives but in the general case.

As an aside, nothing about React precludes using a separate view-model style layer between your base data model and the rendering logic to deal with computing derived information. Indeed, this is often useful as a form of cache if you have computationally expensive work to do when certain source data changes, for example to summarise a large data set or compute the layout for some complex visualisation. Again, computed properties seem to be a variation on this theme.

No doubt there are other ways to achieve the desired results, though inevitably they need their own version of plumbing to connect everything up, and in quite a few that I've seen over the years it's still difficult to co-ordinate updates and maintain good performance as systems scale up.

The main advantages of a library like React, in my experience at least, are that it is simple and universal in its design and interface, but also reasonably transparent about both behaviour and performance characteristics, with enough hooks that you can help it out in cases where the basic usage is inadequate.

Re:React Fiber Architecture by spankalee on Sunday August 07, 2016 @06:30PM (#12244082)
I'm with you. All this complexity is baffling, when there's a very optimized rendering engine sitting there in the form of the browser, and soon a suitable component model.

If you wire up your components so that you just re-render the components that have data changes, you get the benefits of dom diffing, without having to diff.

You can skip all this framework JS, and just directly write an async-rendering Web Component. It's pretty compact and easy to understand. I just wrote up a sketch that would work with one of the incremental-dom-based template libraries:

    class AsyncWebComponent extends HTMLElement {
      constructor() {
        super();
        this.isLayoutValid = true;
        this.attachShadow({mode: 'open'});
        this._foo = 'bar';
      }
      
      // Accessors could be generated with decorators or a helper library
      set foo(value) {
        this._foo = value;
        // You could check for deep equality before invalidating...
        this.invalidate();
      }
      
      get foo() {
        return this._foo;
      }
    
      connectedCallback() {
        this.invalidate(); // trigger the initial render
      }
    
      render() {
        // Call into template library to re-render component.
        // If the template is incrementally updated (say with incremental-dom),
        // then only child components with data that changes will be updated.
        templateLib.render(this.template, this.shadowRoot);
      }
    
      invalidate() {
        if (this.isLayoutValid) {
          this.isLayoutValid = false;
          // scheduleRenderTask enqueues tasks, so they'll be run in order down the component tree
          // A simple and correct scheduler is to just enqueue a microtask with Promise.resolve().then(task)
          scheduleRenderTask(() => {
            this.render();
            this.isLayoutValid = true;
          });
        }
      }
    }
edit: example uses. In a template:

    <async-web-component foo="[[foo]]"></async-web-component>
When the parent component renders and sets `foo`, the child will schedule a task to re-render.

In JS:

    let e = document.querySelector('async-web-component');
    e.foo = 'baz'; // e schedules a task to re-render
    e.foo = 'qux'; // e doesn't schedule a task, because one is pending
Re:React Fiber Architecture by underwater on Sunday August 07, 2016 @10:57PM (#12245210)
Of course you can do manual dirty tracking. But why would you ever want to do that on every single component when you could get it for free?

React's DOM digging has zero cognitive overhead so the benefits are essentially free to me as a developer.

Re:React Fiber Architecture by spankalee on Monday August 08, 2016 @12:26AM (#12245490)
This is a sketch of a raw custom element with no library for sugar. A library that assisted in the pattern would presumably implement the accessors for you.

ES/TypeScript decorators would be an easy way to do this, or just a function that fixes up the class after declaration.

Re:React Fiber Architecture by underwater on Monday August 08, 2016 @03:08AM (#12245935)
So implement the accessors logic and invalidation logic, centralize the rerender scheduling and you've rebuilt React.
Re:React Fiber Architecture by scotty79 on Monday August 08, 2016 @08:43AM (#12247245)
What if your component has a lot of nodes? Do you re-render them all? I guess that's the reason they made react. Even if the state of component changes most of the DOM nodes of render component stays the same and re-rendering them would take too long.
Re:React Fiber Architecture by kensign on Sunday August 07, 2016 @07:02PM (#12244229)
thank you, thank you, thank you. Aurelia is an excellent system for this exact use of a web component.
Re:React Fiber Architecture by spankalee on Sunday August 07, 2016 @07:16PM (#12244301)
My example was "plain" custom elements, nothing to do with Aurelia.

Last I checked Aurelia used a lot of the Web Components terminology, but didn't actually create or use custom elements. Did that change?

Re:React Fiber Architecture by kensign on Sunday August 07, 2016 @11:19PM (#12245285)
yes
Re:React Fiber Architecture by spankalee on Monday August 08, 2016 @12:24AM (#12245482)
So Aurelia components are web components? I can create one with document.createElement('my-aurelia-component'), and container.appendChild(), and the element will fully work and have it's lifecycle callbacks called?

I tried to look in the documentation, but couldn't see this clearly stated. It looked like Aurelia would have to be in charge of lifecycle to get dependency injection to work. Specifically, custom element constructors are called by the browser with no arguments: how does this work with Aurelia components that expect to receive constructor arguments via dependency injection?

Re:React Fiber Architecture by kensign on Monday August 08, 2016 @01:04AM (#12245606)
that work is handled by Aurelia itself. You don't explicitly need to define the element.

http://aurelia.io/hub.html#/doc/article/aurelia/framework/la...

Re:React Fiber Architecture by spankalee on Monday August 08, 2016 @01:57AM (#12245731)
Sorry, I still don't get it. Take the CustomerDetail example in the "Component Instantiation Through Dependency Injection" section:

    @inject(HttpClient)
    export class CustomerDetail {
      constructor(http) {
        this.http = http;
      }
    }
If this really creates a Web Component, how does `this.http` ever get set? The browser will call the constructor with no arguments.

What exactly gets passed to `document.registerElement()` (for the v0 Custom Elements API) or `customElements.define()` (for the v1 Custom Elements API)? Are you saying that Aurelia generates and registers a separate custom element class? That's not in the docs. If so, how does that element find the instances to inject into the user-defined constructors?

The main issue that talks about custom element support is still open, and the answer really does seem to be that Aurelia can't create custom elements: https://github.com/aurelia/framework/issues/7

This unfortunately seems to confirm that Aurelia uses the terminology of Web Components, but doesn't actually use or create real Web Components.

Re:React Fiber Architecture by kensign on Monday August 08, 2016 @02:43PM (#12249952)
yeah... You might want to try it out and read the docs before you make such claims

https://github.com/aurelia/web-components

remember too, the ES6 is transpiled. Also, I am done with the nerd war. If you have questions, use the gitter channel.

Re:React Fiber Architecture by spankalee on Monday August 08, 2016 @03:27PM (#12250268)
"nerd war"? Wow, good to see you go then.

That link you just posted is not contained in any of the docs or links that either you or I posted above. I can't actually find it in the entire documentation hub, so even if I did "read the docs", how was I supposed to find it?

Bye.

Re:React Fiber Architecture by underwater on Monday August 08, 2016 @02:57AM (#12245888)
It's component diffing, not DOM diffing. I agree that the later is unnecessary. omponent diffing is an implementation detail that enables the declarations that makes React worth using.

Imagine a parent component that conditionally composes a Button that is either red or blue. You could track that button instance and flip the property if necessary. But that requires a lot of error prone boilerplate, as most real applications might have many states depending on many inputs.

With React you just define which variant you want in the render function of the parent. No state transitions necessary. React then does the hard work of understanding that you rendered a red button then rendered a blue button, so it should reconcile the two.

Re:React Fiber Architecture by kentor on Monday August 08, 2016 @05:55PM (#12251143)
Data-binding is crap for many reasons. Here's a big one: inability to use immutable data types, except for the trivial case of a static component.

When you're diffing the vdom, the system doesn't care where the data comes from, i.e. the data can come from a plain js array or an Immutable.js list.

Second reason: When you have to worry about how to get your model to play nice with the view, that's a leak in the abstraction. This applies to ALL data-binding systems.