What should a front-end framework do?

tosijs is the new name of xinjs. Updating the documentation is a work in progress.

<tosi-carousel dots auto=2>
  <tosi-icon icon="tosiFavicon" size=200></tosi-icon>
  <tosi-icon icon="tosiUi" size=200></tosi-icon>
  <tosi-icon icon="tosiPlatform" size=200></tosi-icon>
</tosi-carousel>
tosi-icon {
  margin: 10px;
  display: block;
  height: 240px;
}

tosi-carousel::part(pager) {
  scrollbar-color: transparent transparent;
}

Most front-end programming today is done using a framework—a library that makes it easier to create chunks of user interface and allows developers to avoid the nitty-gritty details of the DOM APIs. While many frameworks simplify aspects of web development, tosijs is designed to provide a robust, highly sophisticated foundation for building the most demanding and complex web applications, and even desktop apps, with unparalleled efficiency and maintainability.

tosijs original design was spurred by a simple observation: you don't make complex things simpler by making simple things complex. Our aim isn't just to slightly reduce boilerplate for trivial examples like a to-do list—though tosijs certainly does that. Instead, our true focus is on compounding these simplifications across an entire, large-scale project, and by getting out of the way of things that work, rather than wrapping them in layers of abstraction that reduce performance and mask functionality.

What do we mean by "wrapping things that work in layers of abstraction that reduce performance and mask functionality?"

Take the native HTML <input> element. It offers mature functionality, built-in accessibility, and sophisticated, customizable validation support that is often obfuscated or absent from framework-specific "wrapper" components. These wrappers are "necessary" because frameworks like Angular and React are prone to re-rendering the element at the slightest provocation, losing crucial state (like what you selected or where the caret is).

By consistently minimizing overhead, reducing lines of code, and leveraging native browser capabilities where it makes sense, tosijs aims to make fundamentally complex architectures manageable, debuggable, and performant in a way that other frameworks often fail to achieve either initially, or as they evolve and scale.

In my opinion, the main goal of a framework is to minimize the amount of code you need to write to accomplish your goal, but not at the expense of functionality, performance, maintainability, or scalability.

In my experience, for building user interfaces on a web stack, this involves:

Reusable Composable Components

Creating reusable components used to be quite difficult, and a number of frameworks provided systems for doing this, notably React and Angular, but after a bad start—the initial design was not fully thought out and wasn't consistent across browsers—web-components (a.k.a. custom elements) do this very well, work consistently across browsers, and offer capabilities that React and Angular don't match. Web-components:

E.g. you can target different "slots" within a web-component using the slot attribute:

<tosi-sidenav min-size="400px">
  <h4 slot="nav">
    Navigation Stuff
  </h4>
  <ul slot="nav">
    <li><a>Home</a></li>
    <li><a>Contents</a></li>
  </ul>
  <div>
    <h1>Hello world</h1>

    <p>This is inside the default slot</p>
  </div>
</tosi-sidenav>

How hard is this kind of thing to do? Here's a simple example implemented using tosijs's Component base class.

const { Component, elements } = tosijs

const { slot, div } = elements

class Slotted extends Component {
  static styleSpec = {
    ':host': {
      display: 'inline-flex',
      flexDirection: 'column',
      padding: 10,
      alignItems: 'center',
      boxShadow: 'inset 0 0 0 2px #aaa'
    }
  }
  
  content = [
    slot({name: 'above'}),
    slot(),
    slot({name: 'below'})
  ]
}

const slotted = Slotted.elementCreator({tag: 'my-slotted'})

preview.append(
  slotted(
    div('I am in the middle'),
    div({slot: 'below'}, 'I end up at the bottom'),
    div({slot: 'above'}, 'I end up on top'),
  )
)

Note if you provide a static styleSpec in a Component subclass, it gains a shadowDOM. If you provide a styleSpec in the elementCreator() call, this becomes a stylesheet in the outer DOM, :host is changed to the component's tagName (which might get changed to avoid collisions), and <slot> elements are replaced with <tosi-slot> elements that have the same compositing behavior.

In React you can implement this using a combination of children and props—which works—but it's clumsy.

And beyond this, web-components:

Even if you don't use the shadowDOM, web-components leverage custom HTML tag-names to make scoping styles very easy, without resorting to a proliferation of class identifiers. Using a class to specify a component built out of <div> elements, causes problems with managing CSS on large projects because a class overrides a tag, whereas a custom tag-name does not and effectively creates its own namespace.

This last bullet is quite significant. A React component with server-side rendering needs to run on the server and on the client, you end up hydrating data into HTML, sending the rendered HTML, and then sending code across that knows how to render the HTML (again) to handle updates, and all this wastes bandwidth and CPU cycles, and the user may experience a performance "thunk".

Creating Custom Elements

tosijs provides a convenient abstract base class—Component—that lets you build robust components that even handle things like name collisions (e.g. if you use web-components from two different libraries that register the same tag-name, subclasses of Component will automatically register themselves under a unique name if needed).

Registration tagName Collision Handling

How does tosijs handle tagName-collision? It automatically picks new names until the collision disappears. tosijs provides extensive support for web-components that don't use the shadowDOM (which makes them more performant and easier to style).

If you write (light DOM) style rules for a web-component using ':host' these will be rewritten using the component's registered tag-name. So if you ask for the tag my-component and it ends up being renamed to my-component2 then its styles will still be targeted correctly.

import { Component, elements, PartsMap } from 'tosijs'

interface MyComponentParts extends PartsMap {
  input: HTMLInputElement,
  caption: HTMLElement
}

const { label, span, input } = elements

export class MyComponent extends Component<MyComponentParts> {
  disabled = false
  caption = ''
  value = ''
  
  constructor() {
    super()
    
    this.initAttributes('disabled', 'caption')
  }
  
  handleChange = () => {
    this.value = this.parts.input.value
  }
  
  content = () => label(
    span({
      part: 'caption'
    }),
    input({
      part: 'input',
      onInput: this.handleChange
    })
  )
  
  render() {
    super.render()
    
    this.parts.caption.textContent = this.caption
    this.parts.input.disabled = this.disabled
    if (this.parts.input.value !== this.value) {
      this.parts.input.value = this.value
    }
  }
}

export const myComponent = MyComponent.elementCreator({
  tag: 'my-component'
})

A few notes on this:

tosijs also supports Component "blueprint" functions that can be hydrated by any compatible version of tosijs at run-time (so you don't run into issues where two components created with different versions of the same library can't co-exist).

import { PartsMap, XinBlueprint } from 'tosijs'

interface MyComponentParts extends PartsMap {
  input: HTMLInputElement,
  caption: HTMLElement
}
const blueprint: XinBlueprint<MyComponentParts> = (tag, { elements, Component }) => {
  const { label, span, input } = elements
  class MyComponent extends Component<MyComponentParts> {
    // same contents as before
  }
  return {
    type: MyComponent
  }
}

Managing State

A huge amount of user-facing code is devoted to managing application state and synchronising it to the DOM. All of this code needs to be written, tested, maintained, and so on. Ideally this code should be as minimal and robust as possible. Throughout my career, I have constantly strived to make this code trivial or unnecessary to write, test, or maintain.

A very simple bit of binding code might synchronise app.user.name with an <input> field:

const app = {
  user: {
    name: 'Anne Example'
  }
}

const nameField = document.createElement('input')
nameField.value = app.user.name
nameField.addEventListener('input', () => {
  app.user.name = nameField.value
})

But what happens if app.user.name is changed somewhere else?

In React you'd either handle this using a hook or a custom effect or pass the value down through the virtual DOM using something like Redux.

In tosijs you'd use a tosi() proxy:

import { tosi } from 'tosijs'
const { app } = tosi({
  app: {
    user: {
      name: 'Anne Example'
    }
  }
})

tosi() passes back an observer proxy wrapped around the value you passed to it. Any change made through the proxy triggers updates as needed. So, this code:

import { elements } from 'tosijs'
const { input } = elements

document.body.append(input({ bindValue: app.user.name }))

Will create an <input> that updates app.user.name when the user edits it, but will also be updated if app.user.name is changed elsewhere.

How does the observer proxy work? It wraps an object with a proxy that remembers where the value it contains came from. If the value isn't an object (e.g. a string, number, or boolean) it wraps it in the corresponding Javascript object (e.g .String, Number, Boolean) and wraps that in a proxy.

So, app.user.name is a proxy wrapped around new String('Anne Example') that has a tosiPath ('app.user.name') and a tosiValue ('Anne Example'). In new code, prefer the accessor forms—app.user.name.tosi.path and app.user.name.tosi.value—because they're reached through a symbol key and so can never be masked by a data property of the same name.

The root object, xin, is a singleton. And the path is basically the Javascript path to the value within xin, but it also supports the concept of "id-paths" which allow unique and stable references to objects in arrays, e.g. imagine app contains an array of messages which each look like: {id: '12345', title: 'a message',...}. You could refer to a message as app.messages[id=12345] rather than app.messages[2].

Debugging state issues is usually straightforward. A common trick is to simply make xin (the singleton state object) available as a global and interrogate it. If xin.foo.bar contains the right value, the problem is in the binding. If it isn't, you haven't put the data where you think you did.

Creating DOM Elements

One of the most popular aspects of React is JSX, a domain-specific language that combines XHTML and Javascript while being neither, allowing a developer to write something that looks like HTML to produce code that ultimately generates the HTML somewhat resembles the source code.

interface MyProps {
  caption: string
}

export default (props: MyProps) => <div>{props.caption}</div>

This produces a function that returns a sack of properties that then can be inserted in a "virtual DOM" and ultimately turned into the <div> you first thought of.

Note that if you import this function as MyComponent you'll end up with a virtual DOM element named <MyComponent> that contains the actual (and virtual) <div>. Typically there will be more purely virtual DOM elements (with no actual corresponding DOM element) compared to real ones, and the most important elements for purposes of debugging will be those components which cannot be found in the DOM and require using the custom React debugging extension, which is surprisingly crude despite over a decade of development.

Also, every real DOM element (which is implemented in highly optimized native code) will have multiple virtual DOM elements (implemented in far less optimized Javascript) that occupy memory and consume processor cycles.

It's also worth noting that JSX is intrinsically tied to the concept of a virtual DOM. It's easy to write your own JSX implementation, but it's impossible to divorce it from the concept of the "virtual DOM". So, even if you think having to use a DSL is just great, there's that.

Finally, if you care about this, LLMs tend to have a huge amount of mediocre to bad React code in their training data and will hallucinate React solutions to problems given the slightest provocation (this goes beyond LLMs—a lot of lint tools will tell you that a web-component's render method is wrong because it doesn't look like a React component's render method). JSX is supported by the Angular tech stack these days, and I imagine Angular developers are driven nuts by LLMs mis-identifying their code as React code and helpfully suggesting horribly incorrect changes (on top of getting confused between the two Angular trees…)

In my opinion, a good framework doesn't define new and unnecessary DSLs, even if they didn't have the issues JSX has.

The best way to produce DOM nodes, in my opinion, is either HTML or pure Javascript. The former option benefits from decades of careful optimization, but suffers from weaker code-quality support (HTML does not have the kind of code quality tooling Typescript and Javascript have) while the latter can be clumsy. (See the vanilla js example under Managing State, above.)

tosijs provides elements a proxy that produces ElementCreator functions. This is easiest to explain by example:

In React you can produce a list component like this:

interface MyProps {
  list: string[]
}

export default (props: MyProps) => <ul>
  ...props.list.map((s: string) => <li>{s}</li>)
</ul>

With elements you can write this:

const { ul, li } = elements

export default (list: string[]) => ul(...list.map((s: string) => li(s)))

So, without prepropressing or transpilation you get to build the DOM with less code, the code you write traffics in actual DOM elements with standard APIs, and that code is written in Typescript / Javascript, not a DSL.

Synergies

Because all these things work together there are some powerful synergies.

E.g. if you write this vanillaJS:

const app = {
  user: {
    name: 'Anne Example'
  }
}

const input = document.createElement('input')
input.value = app.user.name
document.body.append(input)

You've simply created an <input> element with the correct initial value.

Adding code to sync the state to the DOM is quite a bit of extra work to handle user edits. But to handle cases where the state is changed directly and now the DOM needs to be updated, things get really nasty.

If you stick app.user.name in some places in the DOM, and then it is changed, how do you make sure what's on the screen is updated? React literally just renders everything again from scratch, with some optimizations to avoid rendering some things unnecessaily, and having to explicitly work around pathologies in the behavior of weird and unusual things like <input> fields. Oh right, those aren't weird and unusual, they're absolutely everywhere and pretty much the whole reason you need to manage state in applications.

By contrast, in tosijs if you write:

const { app } = tosi({
  app: {
    user: {
      name: 'Anne Example'
    }
  }
})

document.body.append(input({ bindValue: app.user.name }))

tosijs will automatically bind the proxy to the value of the <input>. That's the really hard problem solved straight out of the box with no extra code. In fact, for complex operations, that's usually all you want because storing changed state may involve a round-trip to a server, failure handling, etc.

Now, if you write:

app.user.name = 'Some other example'

The <input> will be updated.

Here's all of this in action:

const { elements, tosi } = tosijs

const { exampleApp } = tosi({
  exampleApp: {
    user: {
      name: 'Anne Example'
    }
  }
})

const { h1, label, input, div, pre, span } = elements

preview.append(
  h1(
    'Hello ',
    span({bindText: exampleApp.user.name})
  ),
  div(
    label(
      span('Edit name'),
      input({bindValue: exampleApp.user.name})
    )
  ),
  pre(
`Try opening the developer console and interacting with exampleApp.
E.g. you can type exampleApp.user.name = "some other example"`
  )
)

window.exampleApp = exampleApp

And this is pin-point efficient. Only things bound to app.user.name get updated. When you bind data to a DOM element with tosijs it tracks exactly what data is bound where. Try using the Chrome debugger tools and turn on Rendering > Paint flashing.

Performance

tosijs is designed from the ground up to avoid worst-case performance issues.

Virtualized List Binding

tosijs supports virtual list binding out of the box. As long as you know the height (or minimum height) of an item within a list and the container you put the list in has a set size, tosijs will virtualize the list.

E.g. imagine you have a list of all the currently defined emoji (or some recent subset thereof) and you want to render an emoji picker.

This gives you a scrolling list of thousands of emoji (each of which is quite expensive to render) but only the visible DOM elements are rendered. This example does exactly that.

const { elements, tosi, throttle, touch } = tosijs

const request = await fetch(
  'https://raw.githubusercontent.com/tonioloewald/emoji-metadata/master/emoji-metadata.json'
)
const list = await request.json()

const { emoji } = tosi({ emoji: {
  filter: '',
  list
} })

const filterEmoji = throttle(
  () => {
    const needle = emoji.filter.trim().toLocaleLowerCase()
    console.log(needle)
    const useFilter = !!needle
    for(const item of emoji.list.valueOf()) {
      item.hidden = useFilter && !(item.name.toLocaleLowerCase().includes(needle))
    }
    touch(emoji.list)
  }
)

const { input, div, span, template } = elements

preview.append(
  input({ 
    placeholder: 'filter emoji', 
    bindValue: emoji.filter,
    onInput: filterEmoji
  }),
  div(
    {
      style: {
        height: '250px',
        overflowY: 'auto'
      },
      bindList: {
        hiddenProp: 'hidden',
        idPath: 'name',
        value: emoji.list,
        virtual: {
          height: 30
        }
      }
    },
    template(
      div(
        { class: 'row' },
        span({bindText: '^.chars'}),
        span({bindText: '^.name'}),
      )
    )
  )
)
.preview .row {
  display: grid;
  grid-template-columns: 80px auto;
}

Using Specialized Libraries

<!-- this is using my mapbox token, please don't abuse it -->
<tosi-map
  token="pk.eyJ1IjoicG9kcGVyc29uIiwiYSI6ImNqc2JlbWU0bjA1ZmY0YW5ycHZod3VhbWcifQ.arvqfpOqMgFYkKgQ35UScA"
  map-style="mapbox://styles/mapbox/streets-v12"
></tosi-map>
.preview tosi-map {
  width: 100%;
  height: 100%;
}

Typically, complex libraries are shipped as vanilla javascript, and need to be wrapped using host components. tosijs typically can use non-rendered libraries directly, and simply wrap rendered libraries in a very thin wrapper, allowing full and direct access to the underlying API.

E.g. tosijs-ui (a component library provided for use with tosijs) provides lightweight wrappers for mapboxjs, babylonjs, and bodymovin that provide complete access to the underlying API with no overhead.

And in cases—like mapbox or webrtc tools—where a given library is large, isn't always needed, and/or using it requires the user is online, you can load a blueprint asynchronously, and that blueprint can itself load its dependencies asynchronously, as needed.

tosi platform logo

Radically Simplifying Complex Apps: The tosijs Advantage

Even if your current workflow revolves around React and JSX, tosijs offers a fundamentally simpler approach to managing and mutating application state. Instead of relying on manual "effect" handlers or cumbersome prop drilling through partial DOM hierarchies, tosijs's tosi() proxy system provides automatic, pin-point DOM updates. You can simply useTosi() to create hooks to tosijs data-paths, letting tosijs handle the synchronization efficiently and precisely.

useTosi is part of the tiny react-tosijs library that allows you to create a hook for any data-path. You can just shove data into the state singleton and pipe it anywhere it's needed.

Beyond state management, tosijs provides a genuine path to escape the confines of "invasive" frameworks that can lead to tangled dependencies and escalating complexity. We've all experienced the "trauma" of maintaining sprawling and convoluted Redux codebases or navigating an intricate web of interacting React Hooks. With tosijs, you can seamlessly integrate vanilla JavaScript libraries, leveraging tosi() to pipe data and track changes, allowing for clean, side-by-side operation with existing legacy functionality. Over time, this enables a gradual, strategic migration towards a codebase that's cleaner, more maintainable, and free from burdensome framework-specific dependencies.

const { elements, tosi, touch } = tosijs

const { h1, div, input, span, template, button } = elements

class Todo {
  items = [] // { done: boolean, task: string }
  
  constructor(tasks = []) {
    this.items = tasks
  }
  
  addTask(task) {
    if (task) {
      this.items.push({
        done: false,
        task
      })
    }
  }
}

const todo = new Todo([
  {
    task: 'Get milk',
    done: false
  },
  {
    task: 'Feed cat',
    done: false
  }
])

const { todoProxy } = tosi({
  todoProxy: {
    items: todo.items,
    newItem: ''
  },
})

preview.append(
  h1('To Do'),
  div(
    {
      bindList: {
        value: todoProxy.items
      }
    },
    template(
      div(
        { class: 'todo-item' },
        input({type: 'checkbox', bindValue: '^.done'}),
        span({bindText: '^.task'})
      )
    )
  ),
  div(
    input({ 
      placeholder: 'add item', 
      bindValue: todoProxy.newItem, 
      onKeyup(event) {
        if (event.key === 'Enter') {
          event.target.nextElementSibling.click()
        }
      }
    }),
    button(
      { 
        onClick() {
          todo.addTask(todoProxy.newItem.valueOf())
          todoProxy.newItem = ''
          touch(todoProxy.items)
        },
        bindEnabled: todoProxy.newItem
      }, 
      'Add Todo Item'
    )
  )
)
.todo-item {
  display: grid;
  grid-template-columns: 44px auto;
}

.todo-item input[type=checkbox] {
  height: 16px;
}

button[disabled] {
  pointer-events: none;
  opacity: 0.5;
}

For those building fresh, tosijs empowers you to use your favorite Web Component libraries alongside standards-driven HTML. You can effortlessly drop in custom Web Components as direct, superior replacements or enhancements for often-substandard native HTML elements like <input type="date"> or <select>, significantly improving user experience without compromising on standard web practices.

One of the most common performance bottlenecks in web applications is handling large tabular data. tosijs tackles this head-on by providing nearly trivial support for virtualized list bindings. This means you no longer have to devise complex strategies to break up large datasets to maintain a smooth user experience. Instead, you can focus on simply ensuring you're not loading unnecessarily massive amounts of data in the first place.

While tosijs might initially remind you of focused, lightweight libraries like Svelte, SolidJS, or Vue.js, there's a crucial distinction. Those libraries primarily concentrate on simplifying the development of simple applications. tosijs, by contrast, is laser-focused on radically simplifying the development of rich and genuinely complex applications. Making simple apps even simpler is a welcome side-effect, but it's not our ultimate goal.

tosijs represents a significant evolution in front-end frameworks. Our objective is to deliver native-like usability, performance, and robustness on the web stack. This allows developers to accomplish more with less code written, fewer dependencies, smaller package sizes, reduced bandwidth consumption, and significantly easier maintenance. It's about a fundamental shift: write less code, build less code, read less code, fix less code, and—ultimately—get far more done.

Colophon

This website replaces my old Wordpress-based blog because I was sick of paying for lackluster PHP hosting, didn't like with Wordpress did to my text, was sick of plugins breaking, and wanted to see how quickly I could build a functional blog site using the tosijs stack.

After a couple of weeks of coding, the site has been stable and I honestly put about as much work into maintaining it as I used to put into fixing issues with Wordpress. (Obviously, if I paid for wordpress hosting specifically it would involve almost zero effort.)

Blog posts are written in markdown, edited using the CodeMirror editor, rendered using marked, and the blog itself is hosted on Google Firebase. All the glue and UI is done using tosijs, tosijs-ui, and tosijs-platform. The latter is a work-in-progress and this is the testbed for it.

Finally, all the interactive examples are themselves embedded using tosijs-ui's <tosi-example> web-component.

— Tonio Loewald,