The Owl has Landed

Two years ago I decided that instead of porting b8rjs to Typescript, I'd build a completely new library with the same ambitions but encapsulating lessons learned in the preceding eight years of (a) using b8rjs to build several products, and (b) working at Google, whose engineering requirements b8rjs did not satisfy (in particular, b8rjs could not survive minification with variable renaming, which Google considered an absolute security requirement).

tosijs (originally xinjs) is the result. In addition to being written in 100% typescript, it is more tightly focused than b8rjs (which included a bunch of utility libraries and a collection of user interface elements) and offers the following key capabilities:

The Benefits and Costs of using library code

tosijs does all this with no transitive dependencies and minimal creeping lock-in (what a colleague referred to as "cancerous code").

E.g. the color math used by tosijs's CSS functions was built from scratch because all the libraries I could find that offered the needed functionality were, on their own, at least half as large as tosijs altogether. And as native support for color math is added to modern browsers, this code can be gradually removed.

Creeping lock-in is when using a library forces you to write or rewrite your existing code in a way that locks you in.

I think all software libraries should be considered not only in terms of the benefit they deliver, but the costs (present and future) they impose, which I call a disposal tax. Once you've written a bunch of code using this library, how hard is it to switch to a different library? In the case of redux, rxjs, React, Angular, et al, you pretty much need to throw away everything and start over. In the case of tosijs just wrap your existing library in a proxy and you're good to go.

Building UIs with code

In React, JSX lets you build out the UI using an XHTML-like DSL which is almost as nice as just writing HTML. E.g.

import React from 'react' // JSX transform required

export default ({ caption, value }) => <label>
    <span>{value}</span>
    <input value={value} />
  </label>

Pretty cool, but the thing the function returns is actually a sack of stuff for "internal use only" by React, which you best shouldn't mess with. And all this requires specific tooling to work. And the language you write the DOM nodes in is a pseudo-language. In tosijs you would write:

// elements is a proxy
import { elements } from 'tosijs'

// elements creates functions that produce HTML elements
const { label, span, input } = elements 

export default ({ caption, value }) => label(
  span( caption ),
  input({ value })
)

There's no magic needed in the tooling. You're actually writing standard Javascript (or Typescript) and there's less typing.

And the exported function returns actual DOM nodes that behave and can be reasoned about and manipulated exactly as you'd expect, versus buckets of undocumented office-use-only properties. Instead of a virtual DOM, we use the actual DOM.

tosijs provides similar proxies for SVG and MathML elements.

Web Components

tosijs provides a Component base class that makes it easy to define custom-elements both with and without a shadow DOM. The former are easier to style and lighter weight, while the latter allow you to build protected formatting contexts (e.g. for graphs or embedded word-processors or structural layout elements with no actual intrinsic appearance).

E.g. React only supports having child elements in one place. Anything beyond that involves clumsily passing factory functions or children as props. web-components support multiple named slot elements, and tosijs extends this by supporting slots (via the xin-slot custom-element) even in web-components that don't use a shadow DOM.

tosijs also detects tag-name clashes (e.g. if you mix in components from other libraries) and automatically renames its components if necessary.

Finally, tosijs supports the concept of Component blueprint functions that can be hydrated by any compatible version of tosijs into a web-component on-the-fly, and without creating dependencies on a specific version of tosijs.

Interoperability

It's quite common to want to use components from different sources. But what happens if you use two different components that want the tagName labeled-input? Components built with the Component base class will detect name collisions, pick a new unique name, and rewrite CSS in their helper sheet where needed to use the new selector.

Similarly, it's quite common to use components built on top of different versions of the same core library. This can lead to present or future conflicts. The usual solution to this is "peer dependencies". But that only goes so far: component blueprints allow components to be loaded dynamically and hydrated using any compatible version of tosijs. (In essence, components are hydrated via dependency injection.)

Leveraging CSS and CSS-variables

Modern CSS is very powerful and most of the libraries and tools intended to address shortcomings in CSS target old world CSS before CSS-variables were broadly supported and don't work with the shadow DOM of web-components.

tosijs provides syntax sugar and tools for leveraging modern CSS.

For dimensions, this is more powerful and versatile than defining a bunch of sizes and then trying to remember whether your large radius is called "huge" or "xxl". E.g. you can define a base _fontSize: '16px', then base _spacing: vars.fontSize75 on that size for most cases, and then reduce _fontSize when needed, automatically scaling _spacing, but tighten up spacing without reducing font size as much for very tight fits, all without defining numerous idiosyncratically named classes that mostly don't get used or have weird side effects.

When converting XinStyleRule objects to CSS, the css module treats leading _ characters as syntax sugar for creating CSS-variables (_fooBar becomes --foo-bar). The vars proxy emits variable references, so vars.fooBar becomes var(--foo-bar). varDefault emits functions that add default values, so varDefault.fooBar('10px') produces var(--foo-bar, 10px).

In particular, you can retain semantic class names and make the classes simpler and more flexible using CSS variables.

For colors, this means that instead of defining hundreds of color ramps because you might need a 40% brighter version of var(--brand-color), you can just define _brandColor at the :root level and then write vars.brandColor40b. And if you want to have multiple or dynamic themes, you can directly use the included Color class, which is used to make all this work, to manipulate colors on-the-fly.

E.g.

import { StyleSheet, vars, varDefault } from 'tosijs'

StyleSheet('demo', {
  ':root': {
    _fontSize: '16px',
    _textColor: '#222',
  }
  
  body: {
    fontFamily: varDefault.bodyFont('Helvetica Neue, Arial, Sans-serif'),
    fontSize: vars.fontSize,
    color: vars.textColor,
    lineHeight: vars.fontSize150
  }
  
  ':disabled': {
    color: vars.textColor50o
  }
})

becomes:

<style id="demo">
  :root {
    --font-size: 16px;
    --text-color: #222;
  }
  
  body {
    font-family: var(--body-font, Helvetica Neue, Arial, Sans-serif);
    font-size: var(--font-size);
    color: var(--text-color);
    line-height: calc(var(--font-size) * 1.5);
  }
  
  :disabled {
    color: rgba(32, 32, 0, 0.5);
  }
</style>

A typical "modern" stack with CSS pre-processing does things like generates thousands of style definitions just in case you use five of them, and then uses all kinds of build magic to throw away the definitions that don't actually get used. This just lets you use exactly what you need.

State Management

Something like 70% of the code in typical web applications is simply updating the UI because state has changed or updating state because the user or the back end has changed something. Sometimes the code is doing something incredibly clever, but usually it isn't, and tosijs (like b8rjs before it) aims to automate the dumb code out of existence, while making the clever code easier to write.

import { tosi } from 'tosijs'

const { app } = tosi({
  app: {
    name: 'My App',
    docs: [
      {
        name: 'Autobiography',
        content: 'In the beginning there was the semicolon.'
      },
      {
        name: 'Shopping List',
        content: '- eggs\n- milk'
      }
    ]
  }
})

tosi() returns a proxy of application state. Anything you pass to it is assigned to application state, so app now contains a proxy wrapped around the app property of the object passed to tosi. This is mostly "invisible" at runtime except for strings, booleans, and numbers, which are returned as a proxy wrapped around an object wrapper of the value (e.g. app.name will be a proxy wrapped around new String('My App')).

The proxy does one useful thing: it tracks changes to the wrapped state and transparently updates elements built around that state.

E.g.

import { elements } from 'tosijs'

// assume we are using app from before...
elements.div(app.name)
elements.input({ bindValue: app.name })

Produces a <div> element containing a <span> containing 'My App', but it will be updated if app.name is assigned a new value, and an <input> element that is initialized to 'My App' but, if edited by the user, will automatically update app.name and this in turn will update the text in the div.

All this is done for you and you don't need to worry about the <input> losing track of its internal state or being changed unnecessarily. So you can use native <input> elements when that makes sense and get all the validation and accessibility functionality for free.

Also note that you can wire the app state directly to the relevant elements. You don't need to pipe them through a hierarchy, so you don't end up paralyzed by early decisions about user interface layout. You don't need to worry about nested providers. Get data direct from application state and set application state directly.

Here's a live demo of this:

import { tosi, elements } from 'tosijs'

const { liveAppDemo } = tosi({
  liveAppDemo: {
    name: 'My App',
    docs: [
      {
        name: 'Autobiography',
        content: 'In the beginning there was the semicolon.'
      },
      {
        name: 'Shopping List',
        content: '- eggs\n- milk'
      }
    ]
  }
})

const { label, input, span, h3, div, template, details, summary, textarea } = elements

preview.append(
  h3(liveAppDemo.name),
  label(
    span('Edit the app name'),
    input({ bindValue: liveAppDemo.name })
  ),
  div(
    {
      bindList: {
        value: liveAppDemo.docs,
      }
    },
    template(
      details(
        summary(
          input({ bindValue: '^.name', placeholder: 'enter document name' })
        ),
        textarea({ bindValue: '^.content' })
      )
    )
  )
)

Typescript makes it a little tricky to write simple assignment statements since app.name is declared as a String with benefits, even though you can assign strings to it, so tosijs provides some syntax sugar. Any of its proxied values has a xinValue property that allows getting and setting the underlying property, so you can write Typescript:

Note that old naming conventions (such as xinValue) remain supported. They will ultimately be replaced or streamlined, but this is work-in-progress.

app.name.xinValue = 'new value'

Which is almost as clean as Javascript:

app.name = 'new value'

Finally, if you need to touch the underlying data directly (behind 'tosi''s back), tosijs provides a touch() function that simply lets you touch the proxy or its path to trigger needed updates.

E.g.

import { touch } from 'tosijs'

app.xinValue.name = 'another value' // changes the underlying object directly
touch(app.name)                     // tells the state observer that app.name was changed
touch('app.name')                   // same thing

Virtualized Lists

Rendering small amounts of data has long since been trivial for user interfaces, but all user interfaces, native or web-based, reach a breaking point when faced with huge amounts of data.

But, typically, the problem isn't what's visible, but what's scrolled out of view. It's common for web-applications to either "page" large amounts of data or produce incredibly long lists that have to be scrolled through. This presents both a performance problem (it tends to use a lot of memory and CPU) and usability (e.g. it sucks to not be able to see a table's headers when you've scrolled down through its content).

tosijs provides virtualization support out-of-the-box. You just need to tell it that you want a list of things to be virtualized and how big they are.

import { elements, tosi } from 'tosijs'
const { div, template } = elements
const list = Array.from({ length: 10000 }, (_, id) => ({ id }))

const { bigBindTest } = tosi({
  bigBindTest: { list }
})

preview.append(
  div(
    {
      class: 'virtual-grid-example',
      bindList: {
        value: bigBindTest.list,
        idPath: 'id',
        virtual: {
          height: 40,
          visibleColumns: 7,
          rowChunkSize: 2,
        }
      },
    },
    template(
      div({
        class: 'cell',
        bindText: '^.id'
      })
    )
  )
)
.virtual-grid-example {
  height: 100%;
  width: 100%;
  overflow-y: auto;
  display: grid;
  grid-template-columns: 14% 14% 14% 14% 14% 14% 14%;
}

.virtual-grid-example .virtual-list-padding {
  grid-column: 1 / 8;
}

.virtual-grid-example .cell {
  height: 40px;
  line-height: 40px;
  text-align: center;
}

.virtual-grid-example .cell:nth-child(14n+2),
.virtual-grid-example .cell:nth-child(14n+3),
.virtual-grid-example .cell:nth-child(14n+4),
.virtual-grid-example .cell:nth-child(14n+5),
.virtual-grid-example .cell:nth-child(14n+6),
.virtual-grid-example .cell:nth-child(14n+7),
.virtual-grid-example .cell:nth-child(14n+8) {
  background: #0001;
}

If you look at the above demo in the Elements inspector of your browser, you'll see that only the minimum number of elements are actually in the DOM at any given time. The tosijs-ui table component uses this to provide highly performant data-tables with live column resizing, etc. and the filter component lets you build compound filters.

tosijs lettermark

— Tonio Loewald,