/tonic

A low profile component framework

Primary LanguageJavaScriptOtherNOASSERTION

tests GZip size install size module semantic versioning Common Changelog license

Tonic

Tonic is a low profile component framework for the web. It's designed to be used with contemporary Javascript and is compatible with all modern browsers. It's built on top of Web Components.

See the API docs

Contents

Install

npm i -S @substrate-system/tonic

tl;dr

This is a front-end view library, like React, but using web components.

Tip

DOM state, such as element focus and input values, is preserved across multiple calls to reRender.

Use

Bundler

import Tonic from '@substrate-system/tonic'

Pre-bundled

This package exposes minified JS files too. Copy them so they are accessible to your web server, then link to them in HTML.

Copy

cp ./node_modules/@substrate-system/tonic/dist/index.min.js ./public/tonic.min.js

HTML

<script type="module" src="./tonic.min.js"></script>

Get Started

Building a component with Tonic starts by creating a function or a class. The class should have at least one method named render which returns a template literal of HTML.

import Tonic from '@substrate-system/tonic'

class MyGreeting extends Tonic {
  render () {
    return this.html`<div>Hello, World.</div>`
  }
}

or

function MyGreeting () {
  return this.html`
    <div>Hello, World.</div>
  `
}

The HTML tag for your component will match the class or function name.

Note

Tonic is a thin wrapper around web components. Web components require a name with two or more parts. So your class name should be CamelCased (starting with an uppercase letter). For example, MyGreeting becomes <my-greeting></my-greeting>.


Register

Next, register your component with Tonic.add(ClassName).

Tonic.add(MyGreeting)

HTML

After adding your Javascript to your HTML, you can use your component anywhere.

<html>
  <body>
    <my-greeting></my-greeting>

    <script src="index.js"></script>
  </body>
</html>

Note

Custom tags (in all browsers) require a closing tag even if they have no children. Tonic doesn't add any "magic" to change how this works.


Render

When the component is rendered by the browser, the result of your render function will be inserted into the component tag.

<html>
  <head>
    <script src="index.js"></script>
  </head>

  <body>
    <my-greeting>
      <div>Hello, World.</div>
    </my-greeting>
  </body>
</html>

A component (or its render function) may be an async or an async generator.

class GithubUrls extends Tonic {
  async * render () {
    yield this.html`<p>Loading...</p>`

    const res = await fetch('https://api.github.com/')
    const urls = await res.json()

    return this.html`
      <pre>
        ${JSON.stringify(urls, 2, 2)}
      </pre>
    `
  }
}

Rerender

Call tonicInstance.reRender() to render your component again with updated state. This is totally decoupled from any kind of state machine, so you can choose how to batch state updates, and just re-render when necessary.

Tip

DOM state, such as focus and input values, is preserved across multiple calls to reRender.

Events

There is a convention for event handler method names. Name a method like handle_example, and the method will be called with any example type event.

Events Example

import { Tonic } from '@substrate-system/tonic'

class ButtonExample extends Tonic {
  handle_click (ev) {
    ev.preventDefault()
    if (Tonic.match(ev.target as HTMLButtonElement, 'button')) {
      // button clicks only
      this.increment()
    }
    this.props.onbtnclick('hello')
  }

  render () {
    return this.html`<div id="test">
      example
      <button id="btn">clicker</button>
    </div>`
  }
}

State

this.state is a plain-old javascript object. Its value will be persisted if the component is re-rendered. Any element that has an id attribute can use state, and any component that uses state must have an id property.

Setting the state will not cause a component to re-render. This way you can make incremental updates. Components can be updated independently. And rendering only happens only when necessary.

Remember to clean up! States are just a set of key-value pairs on the Tonic object. So if you create temporary components that use state, clean up their state after you delete them. For example, if I have a component with thousands of temporary child elements that all use state, I should delete their state after they get destroyed. Delete Tonic._states[someRandomId]

API

Event listeners

Add a method with an event name, and it will be called with any matching events.

Event Listener Example

import { Tonic } from '@substrate-system/tonic'

class MyClicker extends Tonic {
  click (ev:MouseEvent) {
    // automatically called on any click
    ev.preventDefault()
    console.log('click')
  }

  render () {
    return this.html`<div>
      <button>click the button</button>
    </div>`
  }
}

Tonic.add(MyClicker)

DOM state

DOM state (like element focus) should be preserved across re-renders.

docs

See API docs.

types

See src/index.ts.

tag

Get the HTML tag name given a Tonic class.

static get tag():string;
class ExampleTwo extends Tonic {
    render () {
        return this.html`<div>example two</div>`
    }
}

ExampleTwo.tag
// => 'example-two'

emit

Emit namespaced events, following a naming convention. The return value is the call to element.dispatchEvent().

Given an event name, the dispatched event will be prefixed with the element name, for example, my-element:event-name.

emit (type:string, detail:string|object|any[] = {}, opts:Partial<{
    bubbles:boolean;
    cancelable:boolean
}> = {}):boolean

emit example

class EventsExample extends Tonic {
  // ...
}

// EventsExample.event('name') will return the namespace event name
const evName = EventsExample.event('testing')

document.body.addEventListener(evName, ev => {
  // events bubble by default
  console.log(ev.type)  // => 'events-example:testing'
  console.log(ev.detail)  // => 'some data'
})

const el = document.querySelector('events-example')
// use default values for `bubbles = true` and `cancelable = true`
el.emit('testing', 'some data')

// override default values, `bubbles` and `cancelable`
el.emit('more testing', 'some data', {
  bubbles: false
  cancelable: false
})

static event

Return the namespaced event name given a string.

class {
  static event (type:string):string {
      return `${this.tag}:${type}`
  }
}

example

class EventsExample extends Tonic {
  // ...
}

EventsExample.event('testing')
//  => 'events-example:testing'

dispatch

Emit a regular, non-namespaced event.

{
  dispatch (eventName:string, detail = null):void
}

dispatch example

class EventsExample extends Tonic {
  // ...
}

document.body.addEventListener('testing', ev => {
  // events bubble by default
  console.log(ev.type)  // => 'testing'
  console.log(ev.detail)  // => 'some data'
})

const el = document.querySelector('events-example')
el.dispatch('testing', 'some data')

// override default values
el.dispatch('more testing', 'some data', {
  bubbles: false
  cancelable: false
})

Develop

On any version bump, we run npm run build, which calls all the other build scripts.

build ESM

npm run build-esm
npm run build-esm:min

build Common JS

npm run build-cjs
npm run build-cjs:min

build UMD modules

npm run build:main
npm run build:minify

Useful links