Docs Examples

Examples

Intro

These components are mostly complete examples (depending on your use-cases) that can be used as a starting point to build your own components or apps.

See the docs page for more details.

Badge

The Badge component creates a notification badge with a counter and unread alert.

Demo

Example
Add Subtract

Code

To update the notification count, pass in the count property.

HTML

<tonic-badge></tonic-badge>

JS

tonicBadge.value = 5

Api

Properties

Property Type Description Default
id string Adds the id attribute.
name string Adds the name attribute.
count string Updates the count property. 0
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Members

Property Description
value Getter/setter for the badge count.

Button

The Button component creates a button.

Demo

Example
Click me

Code

HTML

<tonic-button
  async="true"
  id="tonic-button-example"
  value="click-me">Click me
</tonic-button>

JS

const button = document.getElementById('tonic-button-example')
button.addEventListener('click', e => {
  setTimeout(() => {
    button.loading(false)
  }, 3e3)
})

Api

Properties

Property Type Description Default
id string Button with id attribute.
name string Button with a name attribute.
type string Type of button (i.e. submit).
value string Value of the button. Submit
disabled boolean Button with the disabled attribute. false
autofocus boolean Button with the autofocus attribute. false
async boolean Make button asynchronous. false
is-active boolean Active button. false
width string Width of the button. 150px
height string Height of the button. 38px
radius string Radius of the button. 2px
fill string Filled button.
text-color string TextColor of the button.
href string Add a location (url) for click event.
tabindex number Add a tabindex for the button.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
click() Click event
loading(state) Removes loading from an async button.

Chart

An example component that uses chart.js 2.7.2.

Code

HTML

<tonic-chart
  type="horizontalBar"
  width="300"
  height="150px"
  tooltip="false"
  src="/chartdata.json">
</tonic-chart>

JSON

{
  "labels": ["Foo", "Bar", "Bazz"],
  "datasets": [
    {
      "backgroundColor": ["#c3c3c3", "#f06653", "#8f8f8f"],
      "data": [478, 267, 34]
    }
  ]
}

Api

Properties

Property Type Description Default
title string The title of the chart.
type string The type of the bar chart.
tooltip bool Show or don't show the tooltip.
width string Width of the chart (include the unit, %, px etc).
height string Height of the chart (include the unit, %, px, etc).

Instance Methods & Members

Method Description
draw(Object, Object) Draws (or re-draws) the chart. The first parameter is the data and the second is options.

Checkbox

The Checkbox component is used to create a styled checkbox, with or without a label. You can also create a custom checkbox using SVG icons.

Demo

Example

Api

Properties

Property Type Description Default
id string Adds id attribute. required
name string Adds name attribute.
disabled boolean Adds disabled attribute. false
checked boolean Adds checked attribute. false
size string Changes the width and height of the icon. 18px
icon-on string Add a custom SVG icon on state.
icon-off string Add a custom SVG icon for the off state.
color string Changes the color of the icon. --primary
tabindex number Add a tabindex for the checkbox.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Properties

Method Description
value A getter/setter that returns true if the checkbox is checked or false if the checkbox is not checked.

Static Methods

Method Description
addIcon(state, fn) Add a custom SVG as the icon for the given state Where the state parameter is either on or off and the fn parameter is a function that returns your SVG's xml. The function will receive the color prop as an argument.

Dialog

A Dialog is not a component, it is a base class. You can extend it to create your own dialog class which can be registered and then used as a tag.

Demo

Example
Click To Open

Code

HTML

<tonic-dialog id="example-dialog" message="Click update for timestamp">
</tonic-dialog>

JS

class TonicDialog extends Tonic.Dialog {
  click (e) {
    if (!Tonic.match(e.target, '#update')) return

    this.reRender(props => ({
      ...props,
      message: `Date stamp ${Date.now()}`
    }))
  }

  render () {
    return `
      <header>Dialog</header>
      <main>
        ${this.props.message}
      </main>
      <footer>
        <tonic-button id="update">Update</tonic-button>
      </footer>
    `
  }
}

Tonic.add(TonicDialog)
Tonic.init()

const link = document.getElementById('example-dialog-link')
const dialog = document.getElementById('example-dialog')

link.addEventListener('click', e => dialog.show())

Api

Properties

Property Type Description Default
id string Adds an id attribute.
name string Adds a name attribute.
width string Sets the width of the dialog.
height string Sets the height of the dialog.
overlay string Adds a background overlay. true
background-color string Sets the background color of the overlay. rgba(0,0,0,0.5)
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
show() Shows the dialog. Returns a promise that can be awaited while the animation finishes.
hide() Hides the dialog. Returns a promise that can be awaited while the animation finishes.
click() Click event.

Icon

The Icon component is used to create an SVG icon with a custom size and color.

Your single SVG sprite file should have the following base structure, using <symbol> and an id to refer to the specific icon:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
  <symbol id="example">
    <path />
  </symbol>
</svg>

Demo

Example

Code

HTML

<tonic-icon
  symbol-id="example"
  src="/sprite.svg"
  fill="red"
  size="40px">
</tonic-icon>

Api

Properties

Property Type Description Default
size string Changes the width and height of the icon. 25px
fill string Changes the color of the icon. var(--primary)
src string Allow a custom icon from a sprite. ./sprite.svg
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Input

The Input component creates an input that can be invalidated.

Demo

Example

Code

HTML

<tonic-input
  label="Email Address"
  type="email"
  width="280px"
  id="tonic-input-example"
  placeholder="Enter a valid email address"
  spellcheck="false"
  error-message="Invalid Email">
</tonic-input>

The input will validate automatically if you specify the type or the pattern attribute.

You can also validate or invalidate an input with Javascript using the methods setValid() and setInvalid()

JS

setInvalid.addEventListener('click', (e) => {
  input.setInvalid('There was a problem')
})

Api

Properties

Property Type Description Default
id string Input with id attribute.
name string Input with name attribute.
type string Type of input (text, password, email). text
required boolean Makes the input required. false
disabled boolean Makes the input disabled. false
spellcheck boolean Enable spellcheck on the input. false
invalid boolean Adds the invalid attribute. false
aria-invalid boolean Adds aria-invalid attribute. false
placeholder string Inserts placeholder text.
error-message string Changes error message text.
label string Adds a label to the input.
src string Adds an icon to the input.
position string The position of an icon, if specified.
pattern string Regex for checking value.
width string Width of the input. 250px
radius string Radius of the input. 3px
tabindex number Add a tabindex for the input.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods

Method Description
setValid() Sets the input to valid.
setInvalid(msg) Invalidate the input.

Instance Members

Property Description
value Getter/setter for the value of the input.

Panel

A Panel is not a component, it is a base class. You can extend it to create your own panel class which can be registered and then used as a tag.

Demo

Example
Click to open

Code

HTML

<tonic-panel
  id="content-panel-example"
  overlay="true">
</tonic-panel>

JS

const fetch = require('node-fetch')

class TonicPanel extends Tonic.Panel {
  async getArticle (title) {
    try {
      const res = await fetch(`https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=${title}&origin=*`)
      return Object.values((await res.json()).query.pages)[0]
    } catch (err) {
      return { title: 'Error', extract: err.message }
    }
  }

  async click (e) {
    if (e.target.value === 'close') {
      return this.hide()
    }

    if (e.target.value === 'get') {
      const page = await this.getArticle('HTML')

      this.reRender(props => ({
        ...props,
        ...page
      }))
    }
  }

  render () {
    return `
      <header></header>
      <main>
        <h3>${this.props.title || 'Hello'}
        <p>${this.props.extract || 'Click "get" to fetch the content from Wikipedia.'}</p>
      </main>
      <footer>
        <tonic-button value="close">Close</tonic-button>
        <tonic-button value="get" async="true">Get</tonic-button>
      </footer>
    `
  }
}

Tonic.add(TonicPanel)
Tonic.init()

//
// For this example, a button element will trigger the
// `.show()` method on the panel when it is clicked.
//
const panelLink = document.getElementById('content-panel-link-example')
const panel = document.getElementById('content-panel-example')

panelLink.addEventListener('click', e => panel.show())

Api

Properties

Property Type Description Default
id string Adds the id attribute.
name string Adds the name attribute.
position string Changes the position of the panel. right
overlay boolean Shows an overlay behind the panel, blocks page interaction. false
background-color string Changes the background color of the overlay. rgba(0,0,0,0.5)
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
show() Shows the panel.
hide() Hides the panel.
click() Click event.

Popover

The popover component creates a popover activated by a click event. It is positioned in relation to the trigger.

Demo

Item 1
Item 2
Item 3
Example
+

Code

HTML

<tonic-popover id="popover-example" width="175px" for="popover-example-trigger">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
</tonic-popover>

Api

Properties

Property Type Description Default
for string Adds a for attribute. required
width string Changes the width style. auto
height string Changes height style. auto
open boolean Determines the default state of the popover. false
padding string Changes padding style. 15px
margin number Changes margin style. 10
position string Changes position of popover. Can be one of: top, topleft, topright, bottom, bottomleft, or bottomright. bottomleft
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
show() Shows the popover.
hide() Hides the popover.

ProfileImage

The ProfileImage component is used to create an SVG icon with a custom size and color.

Demo

Example

Code

HTML

<tonic-profile-image
  id="profile-image-example-editable"
  size="150px"
  editable="true">
</tonic-profile-image>

JS

const profile = document.getElementById('profile-image-example-editable')

profile.addEventListener('change', e => console.log(e.data))
profile.addEventListener('error', e => console.log(e.message))

Api

Properties

Property Type Description Default
id string Adds the id attribute.
name string Adds the name attribute.
src string Add an image source.
size string Changes the width and height of the image. 25px
radius string Change the border-radius of the image. 5px
border string Change the border of the image (i.e. '1px solid white').
editable boolean Add an edit overlay. false
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Events

Name Description
change Emitted when the src changes.
error Emitted when there was a problem reading the provided input.

ProgressBar

The ProgressBar component creates an updatable progress bar.

Demo

Example
Start Stop

Code

HTML

<tonic-progress-bar id="progress-bar-example">
</tonic-progress-bar>

Api

Properties

Property Type Description Default
width string Changes the width of the progress bar. 280px
height string Changes the height of the progress bar. 15px
color string Changes the color of the progress bar. --accent
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods

Method Description
setProgress(number) Sets the progress (percentage).

Instance Members

Method Description
value A getter/setter that provides the current percentage value of the progress bar.

Range

The Range component creates a range input, or slider.

Demo

Example

Code

HTML

<tonic-range
  label="The value is %i%"
  id="tonic-range-example">
</tonic-range>

Api

Properties

Property Type Description Default
id string Input with id attribute. Required
name string Input with name attribute.
disabled boolean Makes the input disabled. false
width string Width of the track. 250px
height string Height of the track. 4px
radius string Radius of the track. 3px
min string Least possible value. 0
max string Greatest possible value. 100
step string Number the value must adhere to. 1
label string Label that displays the current value. Use %i, %f, etc to represent the value. false
thumbColor string Color of the slider "thumb" var(--window)
thumbRadius string Radius of the slider "thumb" 50px
value string Default value 50
tabindex number Add a tabindex for the range.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Members

Property Description
value Get the current value of the range input.

Router

The Router component will render its children components if the browser's current url matches its path property. This component will detect pushstate, popstate and replacestate events and re-render with the attributes of the url as props.

Demo

Example
Hello, World number prop has the value . 404

Code

HTML

<tonic-router id="page1" path="/examples.html">
  <i>Hello, World</i>
</tonic-router>

<tonic-router id="page2" path="/bar/:number">
  <b>number</b> prop has the value <b id="page2-number"></b>.
</tonic-router>

<tonic-router none>404</tonic-router>

JS

const select = document.getElementById('tonic-router-select')
const page2 = document.getElementById('page2')

select.addEventListener('change', e => {
  window.history.pushState({}, '', select.value)
})

page2.addEventListener('match', () => {
  const { number } = page2.getProps()
  const el = document.getElementById('page2-number')
  el.textContent = number
})

Api

Properties

Property Type Description Default
path string A tokenized string to match against the current url, /books/:book for example.
none string If specified, and no matches have been made so far, this component will render.
id string If specified, provides a way to reference the component instance and listen for events on it.

Events

Name Description
match Emitted when a content section receives the show class because it matches the current url.

Select

The Select component creates a select input.

Demo

Example

Code

HTML

<tonic-select>
  <option value="a">Option A</option>
  <option value="b">Option B</option>
  <option value="c">Option C</option>
</tonic-select>

JS

const select = document.getElementById('options-example-1')
const notification = document.getElementsByTagName('tonic-toaster')[0]

select.addEventListener('change', ({ target }) => {
  notification.create({
    type: 'success',
    message: `Selected option was "${select.value}".`,
    title: 'Selection',
    duration: 2000
  })
})

Api

Properties

Property Type Description Default
id string Select box with id attribute.
name string Select box with name attribute.
required boolean Makes the select box required. false
disabled boolean Makes the select box disabled. false
label string Adds a label to the select box.
width string Width of the select box. 250px
height string Height of the select box.
radius string Radius of the select box. 2px
multiple boolean Show as multiple select.
size string The number of visible items for a multiple select.
value string The default value that will be selected.
tabindex number Add a tabindex for the select box.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods

Method Description
change() The native change event on the select input.
loading(state) Adds loading to the current select box.

Instance Members

Property Description
option A getter/setter that provides the currently selected option from the select input inside the component.
value A getter/setter that provides the current value of the select input from inside of the component.
selectedIndex A getter/setter that provides the selected index of the select input inside the component.

Tabs

The Tabs component creates a menu that activates sections when clicked on.

Demo

Example
One Two Three
Content One
Content Two
Content Three

Code

Tabs have two important concepts. The idea of a group and the idea of a name. Each tab in a tab group will have content that is associated by a name.

The structure inside the component is arbitrary: spans, links, links inside divs, they can all be different. You just need to add the data-tab-name property to the clickable item.

The default tab should be specified using the selected property.

You can specify a tabindex for each tab individually in your html.

HTML

<tonic-tabs group="profile" selected="one">
  <span data-tab-name="one">One</span>
  <span data-tab-name="two">Two</span>
  <div class="special-tab">
    <img src="/three.png" data-tab-name="three"/>
  </div>
</tonic-tabs>

You can use any tag for the content — section is a nice one to use — and the tag containing the content can be located anywhere in your document.

HTML

<section data-tab-group="profile" data-tab-name="one">
  Content One
</section>

<section data-tab-group="profile" data-tab-name="two">
  Content Two
</section>

<section data-tab-group="profile" data-tab-name="three">
  Content Three
</section>

Api

Properties

Property Type Description Default
id string Adds the id attribute.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
click() Click event.

Textarea

The Textarea component creates a text area.

Demo

Example
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way—in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.

Code

Html

<tonic-textarea
  placeholder="Placeholder"
  rows="6"
  label="Text Area">
  <!-- Content Goes Here -->
</tonic-textarea>

Api

Properties

Property Type Description Default
id string Text area with id attribute.
name string Text area with name attribute.
placeholder string Add placeholder to text area.
spellcheck boolean Enable spellcheck. true
disabled boolean Text area with disabled attribute. false
required boolean Set text area to required. false
readonly boolean Set text area to readonly. false
autofocus boolean Enable autofocus on the text area. false
resize string Set to none to disable resize.
rows string Set number of rows.
cols string Set number of columns.
minlength string Set the minimum character length.
maxlength string Set the maximum character length.
width string Set width of text area.
height string Set height of text area. 100%
radius string Set radius of text area. 2px
tabindex number Add a tabindex for the text area.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
value A getter/setter that provides the current value of the text area from inside of the component.

Toaster

The Toaster component creates a container for all toaster items to be added to.

Demo

Example
Notify Me

Code

The following code should be included once on the page:

HTML

<tonic-toaster></tonic-toaster>

To create a new toaster item:

JS

const notification = document.querySelector('tonic-toaster')

document
  .getElementById('tonic-toaster-example')
  .addEventListener('click', e => notification.create({
    type: 'success',
    title: 'Greetings',
    message: 'Hello, World'
  }))

Api

Properties

Property Type Description Default
id string Adds an id attribute.
name string Adds a name attribute.
type string Adds an alert type (success, warning, danger, info).
title string Adds a title.
message string Adds a message.
dismiss boolean If set to false, the close button will not be added to the toaster. true
duration number Adds a duration. center
position string (On Parent tonic-toaster Element) Position of the toaster items, can be left, right or center. center
theme string (On Parent tonic-toaster Element) Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
show() Shows the toaster.
hide() Hides a toaster item.
click() Removes a toaster item.
create() Creates a toaster item.
destroy() Removes a toaster item.

ToasterInline

The ToasterInline component creates an inline toaster item that appears on the screen either for a duration or until the user acknowledges it.

Demo

Example
Notify Me
Hello, World

Code

HTML

<tonic-toaster-inline id="toaster-1">
</tonic-toaster-inline>

JS

const toaster1 = document.getElementById('toaster-1')
const toasterLink1 = document.getElementById('toaster-link-1')

toasterLink1.addEventListener('click', e => toaster1.show())

An inline toaster that is displayed initially:

HTML

<tonic-toaster-inline
  id="toaster-2"
  dismiss="false"
  display="true">
  Displayed initially. Uses HTML.
</tonic-toaster-inline>

NOTE: An inline toaster item that is displayed initially must declare each property in the HTML and display it using display="true". This will create the notification.

Otherwise, the properties for the toaster item to be created must be specified in the javascript, where it is created.

Api

Properties

Property Type Description Default
id string Adds an id attribute.
name string Adds a name attribute.
title string Adds a title.
message string Adds a message. If no message attribute is provided the inner HTML will be used.
type string Adds an alert type, success, warning, danger or info).
duration number The duration that the component will be displayed before being hidden.
dismiss boolean If set to false, the close button will not be added to the toaster item.
display boolean Specifies whether toaster is displayed initially. false
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
show() Shows the toaster.
hide() Hides a toaster item.
click() Removes a toaster item.
create() Creates a toaster item.
destroy() Removes a toaster item.

Toggle

The Toggle component creates a toggle.

Demo

Example

Code

HTML

<tonic-toggle
  id="toggle-example"
  label="Change">
</tonic-toggle>

Api

Properties

Property Type Description Default
id string Adds the id attribute required
name string Adds the name attributes.
disabled boolean Makes the toggle disabled. false
checked boolean Turns the toggle "on". false
label string Adds a label to the toggle
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods

Method Description
change() Bind to change event.

Instance Members

Method Description
value A getter/setter that returns the current value (state) of the toggle.

Tooltip

The Tooltip component creates a dynamically positioned pop-up tooltip filled with custom content that shows during the hover state of the corresponding trigger element.

Demo

Example
Hover over this text

Code

The element that will be used to trigger the display of the tooltip must contain an id that matches the for attribute on the tonic-tooltip element.

HTML

<span id="tonic-tooltip-example">Hover over this text</span>

<tonic-tooltip for="tonic-tooltip-example">
  <img src="./tonic.svg" width="100px">
</tonic-tooltip>

Api

Properties

Property Type Description Default
for string Adds a for attribute. required
width string Changes the width style.
height string Changes height style.
theme string Adds a theme color (light, dark or whatever is defined in your base CSS. light

Instance Methods & Members

Method Description
show() Shows the tooltip.
hide() Hides the tooltip.

Windowed

A base class used for creating a windowed component.

If you need to render large data sets (hundreds of thousands of rows for example), you can use a technique known as windowing. This technique renders a subset of your data, while giving the user the impression that all the data has been rendered.

Demo

This demo generates the data after you click the overlay. Generating 500000 rows of data can take a second or two.

Example
Click to Load

Code

HTML

<tonic-windowed row-height=30>
</tonic-windowed>

JS

const Tonic = require('@conductorlab/tonic')

class TonicWindowed extends Tonic.Windowed {
  async click (e) {
    const row = Tonic.match(e.target, '[data-id]')

    if (row) {
      console.log(await this.getRow(+row.dataset.id))
    }
  }

  renderRow (row) {
    return `
      <div class="tr" data-id="${row.id}">
        <div class="td">${row.title}</div>
        <div class="td">${row.date}</div>
        <div class="td">${row.random}</div>
      </div>
    `
  }

  render () {
    return `
      <div class="th">
        <div class="td">Title</div>
        <div class="td">Date</div>
        <div class="td">Random</div>
      </div>
      ${super.render()}
    `
  }
}

Tonic.add(TonicWindowed)
Tonic.init()

//
// This demo generates the data after you click the overlay instead of
// on page load since 500K rows of data can take a few seconds to create.
//
const windowed = document.getElementsByTagName('tonic-windowed')[0]
const overlay = document.getElementById('click-to-load')

overlay.addEventListener('click', e => {
  const rows = []

  for (let i = 1; i < 500001; i++) {
    rows.push({
      id: i - 1,
      title: `Row #${i}`,
      date: String(new Date()),
      random: Math.random().toString(16).slice(2)
    })
  }

  overlay.classList.add('hidden')
  windowed.load(rows)
})

Api

Properties

Property Type Description Default
row-height Number Sets the height of each row. required 30
rows-page-page Number The total number of rows per page to render. 100
height String Sets the height of the outer container. inherit
theme String Adds a theme color (light, dark or whatever is defined in your base CSS. light
debug Boolean Add alternating page colors. false

Instance Methods

Method Description
load(Array) Loads an array of data.
loaded() Called after the load function has been called.
getRows() Returns an array of all rows that are currently loaded.
getRow(Number) Get a row of data (returns an awaitable promise).

Instance Methods For Implementers

Method Description
render() Render the component, calling super.render() will render the row container structure.
renderEmptyState() If implemented, should return a structure that represents a state where there are no rows.
renderLoadingState() If implemented, should return a structure that represents a state where has not yet completed.