Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The fastest template library/engine for building web-based user interfaces and apps.

License

NotificationsYou must be signed in to change notification settings

nextapps-de/mikado

Repository files navigation

Mikado - Webs fastest templating engine

Mikado is the webs fastest template engine for building user interfaces. Carefully crafted to get the most out of the browser. Also providing the fastest Express Render Engine of today. Super-lightweight, outstanding performance, no dependencies.

Getting Started  • Options  • API  • Benchmark  • Template Compiler  • Server-Side-Rendering  • Express Render Engine  • Reactive  • Hydration  • Web Components (Shadow DOM)  • Changelog

When you are coming from any previous version:Migration Guide 0.8.x

Benchmark:

Demo:

Support this Project

Mikado was getting so much positive feedback and also feature requests. Help keeping Mikado active by a personal donation.

Donate using Open CollectiveDonate using Github SponsorsDonate using LiberapayDonate using PatreonDonate using BountysourceDonate using PayPal

Table of contents

Rendering has greatimpact on application performance, especiallyon mobile devices. Mikado takestemplating performance to a new level and provides youkeyed,non-keyed recycling and alsoreactive paradigm switchable out of the box.Additionally, Mikado provides aserver-side-rendering approach on a top-notch performance level along full support forhydration to inject templates progressively within the client's runtime.Server and client are sharing the same template definitions simply written inHTML-like markup.The server side approach will also come with thefastest middleware render engine for Express you can get today.Packed with a smart routing feature for event delegation and full support for web components by using the Shadow DOM, Mikado gives you everything you'll need to buildrealtime applications on a cutting edge performance level.

  1. Get Latest
  2. Feature Comparison: Mikado Light
  3. Benchmark Ranking (Rendering Performance)
  4. API Overview
  5. Mikado Options
  6. Getting Started (Basic Example)
  7. Rules and Conventions
  8. Advanced Example
  9. Template Compiler
  10. Template Expressions
  11. Routing & Event Delegation
  12. Recycling Modes:
  13. Views:
  14. DOM State Caching
  15. View State
  16. Custom Callbacks
  17. Static Templates
  18. Server-Side Rendering (SSR)
  19. Express Render Engine
  20. Template Features:
  21. Reactive Features:
  22. Template Pools
  23. Hydration
  24. Web Components (Shadow DOM)
  25. Full Template Example
  26. Best Practices
  27. Concept of Shared Components
  28. Custom Builds

Get Latest

Do not use the "src" folder of this repo. It isn't meant to be used directly, instead it needs compilation. You can easily perform acustom build, but don't use the source folder for production. You will need at least any kind of compiler which resolve the compiler flags within the code. The "dist" folder is containing every version which you probably need including unminified modules.

BuildFileCDN
mikado.bundle.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.debug.js
mikado.bundle.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.min.js
mikado.bundle.module.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.module.debug.js
mikado.bundle.module.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.module.min.js
mikado.es5.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.es5.debug.js
mikado.es5.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.es5.min.js
mikado.light.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.debug.js
mikado.light.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.min.js
mikado.light.module.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.module.debug.js
mikado.light.module.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.module.min.js
Javascript ModulesDownloadhttps://github.com/nextapps-de/mikado/tree/0.8.4/dist/module
Javascript Modules (Minified)Downloadhttps://github.com/nextapps-de/mikado/tree/0.8.4/dist/module-min
Javascript Modules (Debug)Downloadhttps://github.com/nextapps-de/mikado/tree/0.8.4/dist/module-debug
mikado.custom.jsRead more about "Custom Build"

All debug versions are providing debug information through the console and gives you helpful advices on certain situations.

Bundles

Bundles export all their features as static functions to the public class namespace "Mikado" e.g.Mikado.register().

The abbreviations used at the end of the filenames indicates:

  • bundle All features included, Mikado is available onwindow.Mikado
  • light Only basic features are included, Mikado is available onwindow.Mikado
  • es5 bundle has support for EcmaScript5, Mikado is available onwindow.Mikado
  • module bundle is a Javascript module, Mikado is available byimport Mikado from "./mikado.bundle.module.min.js"
  • min bundle is minified
  • debug bundle has enabled debug mode (only for development purposes, do not use for production)

Module

When using modules you can choose from 2 variants:mikado.xxx.module.min.js has all features bundled on the public class namespace e.g.Mikado.register(), whereas the folder/dist/module/ export most of the features as functions which needs to be imported explicitly byimport { register } from "./dist/module/mikado.js".

Also, for each variant there exist:

  1. A debug version for the development
  2. A pre-compiled minified version for production

Browser

Load the bundle by a script tag:

<scriptsrc="dist/mikado.bundle.min.js"></script><script>// ... access Mikado</script>

NPM

Install Mikado via NPM:

npm install mikado

Thedist folder are located innode_modules/mikado/dist/.

Javascript Modules

Use the bundled version exported as a module:

<scripttype="module">importMikadofrom"./dist/mikado.bundle.module.min.js";// bundled access by e.g. Mikado.register()</script>

Also, pre-compiled non-bundled production-ready modules are located indist/module-min/.

<scripttype="module">importMikado,{register}from"./dist/module-min/mikado.js";// bundled access by Mikado.register isn't available// requires direct access by e.g. register()</script>

You can also load modules via CDN:

<scripttype="module">importMikadofrom"https://unpkg.com/mikado@0.8.404/dist/module/mikado.js";</script>

Loading modules via CDN commonly expects to build/bundle your app properly before distribution. Do not load them via CDN in production.

Feature Comparison "Bundle vs. Light"

Featuremikado.bundle.jsmikado.light.js
Template Render Engine
DOM State Caching
Shared Pools / Live Pools
Keyed Recycle
Non-keyed Recycle
Reconcile (Diffing)
Hydration
Template Expressions
Conditional Template Structures
Includes/Partials/Loops
Shadow DOM
Web Components-
Runtime Compiler-
Event Delegation + Routes-
Reactive (Proxy, Observer)-
Asynchronous Render-
View Manipulation Helpers-
DOM Cache Helpers-
File Size (gzip)9.3 kb3.7 kb

Benchmark Ranking (Rendering Performance)

Run the benchmark (non-keyed recycle):
https://raw.githack.com/nextapps-de/mikado/bench/

Run the benchmark (keyed recycle):
https://raw.githack.com/nextapps-de/mikado/bench/#keyed

Run the benchmark (internal/data-driven):
https://raw.githack.com/nextapps-de/mikado/bench/#internal

The values represent operations per second, each benchmark task has to process a data array of 100 items. Higher values are better, except for memory (the sum of allocated memory during the whole test).

Keyed Test Results

LibraryRAMCreateReplaceUpdateOrderRepaintAddRemoveToggleClearScoreIndex
mikado553589278019981613426253605293062930589215151219320292
solid442438223020362131013443645952489178587082531237
inferno462551215114722139001679647802072777245417623834
mithril451672150515406138681663835992110956534152522328
stage056203024461121397491103344271808372099043419935
redom81151714211024296141087028571606248752807516022
domc1243600342434373472351235926670454010030212038
innerhtml672791267624712823279929435752390110340510535
surplus9229692577228123862379228541973023869169132
doohtml7123972308220822082229227542852945631628229
sinuous15120382112245424592461250648203276595568125
jquery10321951919189320922093208439032594192206621
lit-html19914101329134913511333139324151764208374615
ractive187073967269068669172512479177394227
knockout10813992892912912803555244293424124

Theindex is a statistic rank having a maximum possible value of 100, this requires a library to be the best in each test category (regardless how much better).Thescore value is based on median factorization, here a score of 100 represents the statistical midfield.

API Overview

Most of these methods are optional, you can just useview.render(data) to apply all changes automatically.

Constructor:

Instance properties:

Static properties (not included in mikado.light.js):

Static methods:

Static methods (not included in mikado.light.js):

Instance methods:

Instance methods (not included in mikado.light.js):

View manipulation helpers (optional, not included in mikado.light.js):

Static DOM Cache helpers (optional, not included in mikado.light.js):

Observable constructor (optional, not included in mikado.light.js):

Observable array-like methods (optional, not included in mikado.light.js):

Mikado Options

Each Mikado instance, also named includes/partials can have their own options. Except inline partials always inherits the same options from its parent. For this reason you should prefer named includes over inlining in certain situations.

OptionDescriptionDefault
root
mount
The destination root element on where the template should be rendered.null
templateYou will need to assign a template to the Mikado instance (or the name of the template when already registered/loaded).
asyncPerform the.render(data) task asynchronously and return a Promise.false
cacheEnable/disableDOM state caching which can greatly increase performance by a factor up to 25. When enabled make sure to use theDOM Cache Helpers when manipulating the DOM directly on properties which are also covered by template expressions.false
observeWhen usingMikado.Array() for reactive approach you will need to pass this array instance to this property.null
recycleWhen enabled all dom elements which are already rendered will be re-used (recycled) for the next render task. This performs better, but it may produce issues when manual dom manipulations was made which are not fully covered by the template. Alternatively use thekeyed strategy, which limits recycling of components by matching the same data key (e.g. ID).false
statePass an extern object which should be referenced as thestate used within template expressions.{ }
poolPooling can greatly enhance both the keyed and non-keyed recycle strategy.false
hydrateProgressively enables hydration of already existing DOM structures when mounted. Make sure the existing DOM structure is based on the same template. When something differs from the given template schema, the hydration will stop and silently falls back into the default build strategy.false

Getting Started (Basic Example)

The Mikado Compiler requires Node.js to be installed. This is probably the simplest step in this guide.

Install Mikado from NPM (this will also install the compiler):

npm install mikado

Assume there is an array of data items to render (or just one item as an object):

constdata=[{username:"User A",tweets:["foo","bar","foobar"]},{username:"User B",tweets:["foo","bar","foobar"]},{username:"User C",tweets:["foo","bar","foobar"]}];

Accordingly, a templatetpl/partial/user.html might look like:

<table><tr><td>User:</td><td>{{ data.username }}</td></tr><tr><td>Tweets:</td><td>{{ data.tweets.length }}</td></tr></table>

Compile the template:

In your console type this command line:

npx mikado-compile ./tpl/

Load library and initialize template as ES6 modules:

<scripttype="module">importMikadofrom"mikado.bundle.module.min.js";importtemplatefrom"tpl/partial/user.js";constview=newMikado(template,{/* options */});</script>

Load library and initialize template as legacy ES5:

<scriptsrc="mikado.bundle.min.js"></script><scriptsrc="tpl/partial/user.es5.js"></script><script>varview=newMikado("user/list",{/* options */});</script>

The name of a template inherits from its corresponding filename starting by the folder you've passed through the--src flag when calling the compiler.

After creation, you need mount the Mikado view instance to an HTML element as a destination for your render tasks:

view.mount(HTMLelement);view.render(data);

You can also chain methods:

Mikado(template).mount(HTMLelement).render(data);

Rules and Conventions

There is just a single convention you always need to keep in mind:

Every template has to provide one single root element as the outer boundary.

Instead of doing this in a template:

<header><nav></nav></header><section><p></p></section><footer><nav></nav></footer>

Wrapping everything into a single outer root element by doing this:

<main><header><nav></nav></header><section><p></p></section><footer><nav></nav></footer></main>

You can also use a<div> or any other element as a template root (also custom elements). The root element can also hold two special attributeskey andcache. We will come later to it.

Advanced Example

A bit more complex template:

<sectionid="{{ data.id }}"class="{{ this.state.theme }}"data-index="{{ index }}">  {{@ var is_today = data.date === state.today }}<divclass="{{ data.class }} {{ is_today ? 'on' : 'off' }}"><divclass="title"style="font-size: 2em">{{ data.title.toUpperCase() }}</div><divclass="content {{ index % 2 ? 'odd' : 'even' }}">{{# data.content }}</div><divclass="footer">{{ state.parseFooter(data) }}</div></div></section>

You can use any Javascript within the {{ ... }} curly bracket notation. The scope is limited by the template, so variables from one template can't be accessed within another template (usestate for this purpose).

To pass HTML markup as a string, the curly brackets needs to be followed by# e.g.{{# ... }}. For better performance, relevant tasks avoid passing HTML contents as a string.

To use Javascript outside an element's context you need to prevent concatenation of the returned value. For this purpose, the curly brackets need to be followed by@ e.g.{{@ ... }}.

Within a template there are severalreserved keywords you can use as an identifier:

IdentifierDescription
dataA full reference to the passed data item. Within loops the keyword data points to each of the looped data items.
stateAn optional payload used to manually pass in custom specific values or helper functions. The state will be delegated through all nested templates.
indexRepresents the index of the currently rendered data item (starting by 0 for the first item).
thisProvides you access to the Mikado view instance (e.g. this.state).
windowGives access to the global namespace.
_p
_v
_x
_o
_f
_inc
private identifiers, used by internal processing

You cannot change the names of those preserved keywords, also make sure you didn't override them.

It is recommended to pass custom functions via thestate object (see example abovestate.parseFooter = function(str){ return str; }). Alternatively you can also nest more complex computations inline as an IIFE and return the result.

<divclass="date">{{     (function(){         var date = new Date();        // perform some code ...        return date.toLocaleString();    }())}}</div>

To finish the example from above you need one single data object or an array ofdata items:

vardata=[{"id":"230BA161-675A-2288-3B15-C343DB3A1DFC","date":"2019-01-11","class":"yellow, green","title":"Sed congue, egestas lacinia.","content":"<p>Vivamus non lorem <b>vitae</b> odio sagittis amet ante.</p>","footer":"Pellentesque tincidunt tempus vehicula."}];

Provide the optionalstate payload which includes specific values and helper methods used within template expressions:

conststate={today:"2019-01-11",theme:"custom",parseFooter:function(data){returndata.footer;}};

Mount the view to a target element as a destination for all the render tasks:

view.mount(HTMLelement);

Render a mounted template:

view.render(data,state);

Render asynchronously automatically by just providing a callback function:

view.render(data,state,function(){console.log("finished.");});

To render asynchronously by using promises you need to set the callback value totrue:

// callback "true" will use Promisesview.render(data,state,true).then(function(){console.log("finished.");});// same, but uses async/await:awaitview.render(data,state,true);console.log("finished.");

When async should be the default strategy for all render tasks then you can also set theasync option flag:

constview=newMikado(template,{async:true});awaitview.render(data,state);console.log("finished.");

Compile Templates

Define an HTML-like template and use double curly brackets to markup dynamic expressions which should be calculated and replaced during runtime:

<table><tr><td>User:</td><td>{{ data.username }}</td></tr><tr><td>Tweets:</td><td>{{ data.tweets.length }}</td></tr></table>

Save this template e.g. totpl/partial/user.html

The preserved keyworddata is a reference to the passed data item. You can access the whole nested object.

Mikado comes with a builtin template compiler you can simply access by typingnpx mikado-compile into your console. The compiler uses a very simple command-line interface (CLI) running on Node.js to perform compilation tasks. The template compiles into a native javascript file which needs to be passed during creation of a Mikado instance. The same markup is also used for the server-side rendering part, so you can share the same template sources for client and server rendering.

Show help to list all available commands:

npx mikado-compile --help

Compile the template through the command line by:

npx mikado-compile tpl/partial/user.html

Basic Notation:

npx mikado-compilesource <destination>

When no destination folder was set, the compiled files will be saved to the source folder. After compilation, you will have 3 different files:

  1. list.js the template compiled as a ES6 module (which needs to be imported)
  2. list.es5.js the template compiled as ES5 compatible Javascript (which automatically register when loaded by script tag)
  3. list.html the source template you have implemented (do not delete it)

Extended Notation:

npx mikado-compile --src{ source } --dest{ destination } --extension html --type module --compact

Compiler Flags:

  • --type module,-t module export as javascript modules (recommended)
  • --type es5,-t es5 export as ES5-compatible package
  • --extension html,--ext html,-e html the file extension which should be compiled
  • --inline,-i or--compact,-c switch the build strategy to optimize either the performance (inline) or size (compact)
  • --force,-f force overwriting existing files
  • --pretty,-p do not minify the compiled result
  • --watch,-w start the watcher for automatically compile when files has changed (just for development purposes)

Supported flags as attributes on the template root:

<!-- switch the build strategy to prebuilt enabled cache --><tablecache="true"></table>
<!-- switch the build strategy to prebuilt disabled cache --><tablecache="false"></table>

Using the flag attributes are the most performant variants but also cost you some flexibility, because the cache strategy couldn't be changed in runtime, it needs to change in markup before compilation.

Auto Naming

There is a new naming system which will apply by default. The name of your html files will be used as unique identifiers of your templates.Because several folders can include same filenames, the template name inherits from the full path you pass in as--src.

Assuming the following file structure:

tpl/view/start.htmltpl/view/user.htmltpl/view/cart.htmltpl/partial/start.htmltpl/partial/user.htmltpl/partial/cart.html

The command should define the path/tpl/ as the source root because it is the most inner folder which covers all files:

npx mikado-compile ./tpl/

The template names then becomesview/start,view/user,view/cart andpartial/start,partial/user,partial/cart for the partials. So when including just use this name in your expression<table include="partial/user">

The wrong way is to compile the folder /view/ and /partial/ separately, because their template names will be same.

npx mikado-compile ./tpl/view/npx mikado-compile ./tpl/partial/

This might also work, but it is better not to do.

Prebuilt Cache Strategy

The option{ cache: true/false } when creating a Mikado instance could be better declared withing templates on their root element, let the compiler produce more optimized code for this strategy.

<tablecache="true"><!-- ... --></table>

Also use this approach when setcache="false":

<tablecache="false"><!-- ... --></table>

Watcher (Auto-Compile)

A perfect fit for your local development environment is spawning a watcher to automatically compile files when they get changed. Just use the same command line you would also use for a full compilation and append the flag--watch or-w to it:

npx mikado-compile ./tpl/ --watch

Don't close the console, otherwise the watcher will stop. You can stop the watcher explicitly by pressingCTRL + C.

Template Expressions

The template notation expects double curly brackets{{ ... }} for any kind of dynamic expressions.

Except when using {{@ ... }} for inline code notation, the returned value of every dynamic expression will be replaced to its position.

Value Insertion{{ ... }}

<div>{{ data.value }}</div>
view.render({value:"test"});

You can also combine multiple expressions with non-expression contents:

<div>The title "{{ data.title }}" has the value: {{ data.value }}</div>
view.render({title:"title",value:"test"});

You can also mix text nodes with elements on the same root element:

<div>Title:<b>{{ data.title }}</b><br>Value: {{ data.value }}</div>
view.render({title:"title",value:"test"});

Also, you can use expressions within every attribute:

<divdata-id="{{ data.title }}"class="{{ data.class }}">{{ data.value }}</div>
view.render({id:1,value:"test",class:"test"});

Every Javascript syntax is allowed withing expression:

<divstyle="color: {{ data.active ? 'green' : 'black' }}; {{ data.value ? '' : 'display: none;' }}"></div>
view.render({active:true,value:"not empty"});

Since expressions just need to return a value you can also use IIFE:

<div>{{     (function(){         var date = new Date();        // perform some code ...        return date.toLocaleString();    }())}}</div>
view.render();

JS Inline Code{{@ ... }}

The inline code expression is the only one which doesn't return a value to be rendered in place, it just executes.

<div>    {{@ const value = data.title.toUpperCase(); }}<h1>{{ value }}</h1></div>
view.render({title:"title"});

The scope is limited to the template scope, but you can assign tostate alternatively to share values across nested instances:

<div>    {{@ state.value = data.title.toUpperCase(); }}<divinclude="header"><!-- contents of header.html:        <h1>{{ state.value }}</h1>        --></div></div>
view.render({title:"title"});

Truthy Values{{? ... }}

This will just output the result when it is notnull,undefined,NaN orfalse.

<div>{{? data.value }}</div>
view.render([{value:null},{value:NaN},{value:undefined},{value:false}]);

Escape Values{{! ... }} (SSR only)

This will escape the value before return. This is just important for the server-side-rendering part, the client automatically escape contents by default (except when using the HTML-expression).

<div>{{! data.value }}</div>
view.render({value:"<b>html is not allowed</b>"});

HTML Contents{{# ... }}

This will allow for inserting HTML returned string.

Be aware of this can potentially lead into security issues like XSS. Use carefully!

<div>{{# data.value }}</div>
view.render({value:"<b>html is allowed</b>"});

Sanitizer

Mikado provides you high performant helper function you can use in this context to escape contents or to sanitize.

view.render({value:"<b>html allowed</b><br>"+Mikado.escape("<b>not allowed</b>")});
view.render({value:"<b>html allowed</b><br>"+Mikado.sanitize("<b>not allowed</b>")});

Using the sanitizer will remove the tags completely, whereas when escaping the content aren't removed but just escaped.

Reactive Bindings{{= ... }}

Define properties by using pure data object notation without any javascript inside:

<divclass="{{= data.class }}">{{= data.value }}</div>
// store must be an array of elements:conststore=[{class:"active",value:"foo"}];// it needs a initial render if store isn't empty:view.render(store);// the store array now was proxified!

Now you can change the properties ofstore and the corresponding DOM elements will change automatically:

store[0].class="inactive";store[0].value="bar";

Runtime Compiler

Alternatively of using thenpx mikado-compile you can also compile templates during runtime.

If a page has set aContent-Security-Policy (CSP) header field, using the runtime compiler has disadvantage when not configurescript-src 'unsafe-eval'. It is recommended to use the Mikado native compiler, which is CSP-friendly and also can optimize your templates more powerful.

The runtime compiler uses the performance optimizedinline strategy for every task, you can't switch it. The compiler property flagcache="true" orcache="false" on a template root is not supported, therefore you can't use 2 of the most performant strategies. But they are just slightly faster, so this shouldn't be an issue.

Those features aren't supported by the runtime compiler:

  • cache="true" orcache="false" on a template root
  • using any other compiler strategy thaninline
  • detect and replace repeating inline includes
  • detect and solve/unroll non-dynamic expressions, e.g.<h1>{{ "foor" + "bar " }}</h1> will transform to a static content<h1>foobar</h1> and removes the expression completely
  • runtime-ready templates aren't available on page load (they need to compile)
  • the runtime compiler does not pass the"crazy template" test

Examples

Define some HTML template structure:

<templateid="user-list"><!-- just a single outer root element allowed: --><table><tr><td>User:</td><td>{{ data.user }}</td></tr><tr><td>Tweets:</td><td>{{ data.tweets.length }}</td></tr></table></template>

Template definitions used by the runtime compiler needs manual naming when used as named includes.

The template name will derive from<template> or<template name="user-list"> and becomesuser-list.When using named includes you will need to use this name for referencing, e.g.<div include="user-list">".

Compile the template and use it for creating a Mikado view instance:

consttemplate=document.getElementById("user-list");consttpl=Mikado.compile(template);constview=newMikado(tpl,{/* options */});view.render(data);

When the template was get through element ID you can use a shortcut:

consttpl=Mikado.compile("user-list");

Also, you can compile the template and use it for registration as a named include referenced by another template e.g.<div include="user-list">":

Mikado.register(Mikado.compile("user-list"));

You can use non-template elements for defining templates also:

#user-list{display: none }
<!-- just a single outer root element allowed: --><tableid="user-list"><tr><td>User:</td><td>{{ data.user }}</td></tr><tr><td>Tweets:</td><td>{{ data.tweets.length }}</td></tr></table>

Last but not least you can pass the template markup as a string:

consttpl_str=`<table name="user-list">  <tr>    <td>User:</td>    <td>{{ data.user }}</td>  </tr>  <tr>    <td>Tweets:</td>    <td>{{ data.tweets.length }}</td>  </tr></table>`;consttpl=Mikado.compile(tpl_str);constview=newMikado(tpl,{/* options */});view.render(data);

Using Inline Code

The runtime compiler does not support all places of inserting inline code expressions. In some situations it might produce issues like here:

<tableid="user-list"><tbodyforeach="data.entries">  {{@    /* the browser will move this before<table>! */     const value = "test";  }}<tr><td>Value: {{ value }}</td></tr></tbody></table>

The runtime compiler didn't parse the template by string, instead the compiler creates a dom structure when passing a template as string.On the example above the{{@ ... }} expression is treated as a text node by the browser.Since the position isn't allowed to place text nodes (after<table>,<tbody>,<tr>) the browser moves this text node up to the outer scope of the table. But the inline code is now executed within the first outer template function, instead the inline loop template function needs the value and is running in its own scope.

In this situation you can store values onstate to pass through inline looped partials.Or you can use the<script> tag in combination with the js-expression. The latter will keep the hierarchy, because those tags won't move outside by the browser:

<tableid="user-list"><tbodyforeach="data.entries"><script>{{@constvalue="test";}}</script><tr><td>Value: {{ value }}</td></tr></tbody></table>

Don't forget to use the expression notation, otherwise it will be inserted as a normal code element.

When the<script> just including js-inline code expression it won't be added to the template as a script element.

Routing & Event Delegation

All the special attributes used to assign event routing within templates are inherited from the native inline listener name but without the prefixon, e.g. to bind routing for an "onclick" just useclick.

Let's take this example:

<tableforeach="data"data-user="{{ data.user }}"><trdata-id="{{ data.id }}"entry><td>Item:</td><tdclick="item-show">{{ data.name }}</td><td><aclick="item-edit:entry">Edit</a></td><td><aclick="item-delete:entry">Delete</a></td><td><aclick="item-sort:root">Sort</a></td></tr></table>

There are 4 click listeners. The attribute value represents the name of the route.Some of the listener has a route separated by colon ":", this will delegate the event from the route e.g. "item-delete" to the closest element which contains the attribute "entry".You can freely choose attribute names, but it shouldn't collide with native attributes.The last listener contains the keywordroot which is a shortcut to automatically forward the components root (the <table> in this example) astarget to the assigned route.

Forwarding events to a parent element by using the colon notation is also helpful when you have corresponding data-attributes assigned to an outer context and each of the nested listener needs to access those values.

Define routes:

view.route("show-user",function(target,event){alert(target.textContent);});view.route("delete-user",function(target,event){// target was delegated to "root" by using the colon expressionalert(target.dataset.id);// when target is delegated you can still get the// original element where the event was fired:constanchor=event.target;});

Routes are stored globally, so they share through all Mikado instances.

List of all supported events:

  • tap (synthetic touch-enabled "click" listener, see below)
  • change, input, select, toggle
  • click, dblclick
  • keydown, keyup, keypress
  • mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, mousewheel
  • touchstart, touchmove, touchend
  • submit, reset
  • focus, blur
  • load, error
  • resize
  • scroll

Synthetic events:

EventDescription
tapThe tap event is a synthetic click event for touch-enabled devices. It also fully prevents the 300ms click delay. The tap event automatically falls back to a native click listener when running on non-touchable device.

Event Bubbling

When multiple listeners of the same type are nested, the event will bubble up to the HTML root element when enabling the global flagMikado.eventBubble = true, otherwise bubbling will stop on the most inner definition which gets matched.

<table><trclick="route-tr"><tdclick="route-td"></td><td></td><td></td></tr></table>
Mikado.route("route-td",function(target,event){console.log("clicked td");});Mikado.route("route-tr",function(target,event){console.log("clicked tr");});

By default, the above example will just execute the route named "route-td" when clicked on the TD element. WhenMikado.eventBubble = true was enabled the bubble continues after calling the most inner matched handler and both routes will be executed when clicking on TD element.

To control Mikados internal event bubbling mechanism you can pass in options as the 3rd parameter when defining routes:

Mikado.route("route-td",function(){/*...*/},{stop:true});

Supported Options (mixable):

  • stop: boolean stop capturing/bubbling the event up to the root element (stops Mikado event + native event)
  • prevent: boolean prevents the default behavior for this native event
  • cancel: boolean just stop bubbling the Mikado event, but the native event bubbling will still continue
  • once: boolean just catch the event once and remove the route then

Event Cache

You can cache more complex event delegations by setting the global flagMikado.eventCache = true.A candidate for a complex delegation is forwarding a different target to the handler by using the ":" colon notation or when usingMikado.eventBubble = true.

When using Event Cache the scope of forwarding custom target elements to the handler and also nested routes of the same event type should be defined in the same template scope. Thinks may break when components are shared through multiple instances.

This is okay, because all partials are inline:

<tableforeach="data.result"><!-- a new template scope --><trforeach="data.user"click="route-tr:root"><!-- a new template scope --><tdclick="route-td:root">{{ data.username }}</td></tr></table>

When using extern includes it might produce unexpected behavior:

tpl.html:

<tableforeach="data.result"entry><!-- a new template scope --><trforeach="data.user"include="tpl-td"><!-- a new template scope --></tr></table>

tpl-td.html:

<tdclick="route-td:entry">{{ data.username }}</td>

This will have no side effects when the partial "tpl-td.html" is just use for the template "tpl.html".But imagine you have another template which includes "tpl-td.html" andalso one of the recycle strategies (keyed, non-keyed) was enabled on both.In this specific situation the cache might point to a false element<table entry> used to forward to the handler.Then you need to choose between: 1. limiting the scope of used event notation to the template scope, 2. do not enableMikado.eventCache = true.

Explicit Register/Unregister Event Delegation

You can use Mikado routing and event delegation feature everywhere, also outside a template. Just apply the event attribute as you would do in a template.

<body><divclick="handler">Click Me</div></body>
Mikado.route("handler",function(target,event){console.log("Clicked");});

Then you have to explicit register the global "click" listener once:

Mikado.listen("click");

Because events automatically register when creating the template factory under the hood. When no template was created which includes the same type of event, a global listener does not exist. For that reason, you have to explicitly register the listener once.

Control the Native Event Flow

The default "EventListenerOptions" are set totrue by default and is using the capturing phase, this is preferred since the event is required on a global listener.

When you need to configure event capturing and passive listener globally just register the specific listener manually before creating any Mikado instance which is including references to this specific event type:

Mikado.listen("touchmove",{passive:true,capture:true});

Unregister listener:

Mikado.unlisten("click");

Mikado will store the originalEventListenerOptions when calling.listen(event) under the hood, to make sure the listener will be removed properly.

Dispatch Routes

Manually dispatch a route:

view.dispatch("route-name");

Manually dispatch a route and pass parameters for the assigned handler:

view.dispatch("handler",target,event);

Keyed & Non-Keyed Recycling

Each template instance can run in its own mode independently.

1. Non-Keyed Recycle

A non-keyed recycle strategy will re-use all existing components without any limitations and is faster than keyed but also has some side effects when not used properly. That's why limitation by keyed data is a more common strategy for recycling. But when an unlimited recycle strategy was used carefully you won't get any disadvantages.

Just provide a template as usual:

<div><div>User:</div><div>{{data.name}}</div></div>

along with these options:

varview=newMikado(template,{recycle:true});

This will switch Mikado into a recycle strategy to enable re-use of already rendered components.

2. Keyed Recycle

A keyed strategy limits the recycle strategy on components matching the given data key. It just requires aunique identifier on each rendered item (e.g. the ID).

Just add the attributekey to theroot element of a template (or the root of an inline partial) and assign the scope to the unique identifier will automatically switch Mikado into keyed-recycle mode:

<divkey="data.id"><div>User:</div><div>{{ data.name }}</div></div>

A given key in template does not need therecycle: true option to be passed.

varview=Mikado(template);

This will switch Mikado into a recycle strategy which is limited by its corresponding data keys.

Create, Mount, Destroy Views

Create a view by passing a template and customized options:

varview=Mikado(template,options);

Create a view and also mount it to a target element right away (you can also do this before render):

varview=Mikado(template,{mount:HTMLElement});

Whenever.mount() is called for the first time, the template factory will be created once. Also, within this routine the hydration will apply when enabled. You can "prebuild" views by mounting early. Bigger sized applications does not hold all views in memory, so here it is recommended to mount the view right before renderview.mount(node).render(data).

Mount or re-mount a view to an HTML element:

view.mount(element);

Destroy a view:

view.destroy();

Render Templates

Render just a single data object:

view.render({/* object */});

Render a template repeated incrementally through a set of data items:

view.render([/* array of objects */]);

Render a template and also pass a custom state:

view.render(data,state);

When passing a custom state you can still access the original view state by usingthis.state within template expressions.

Schedule an asynchronous render task without any callback:

view.render(data,state,true);

All asynchronous render tasks will be scheduled to the next animation frame.

Schedule an asynchronous render task by using a callback:

view.render(data,state,function(){// finished});

Schedule a render task by using promises (requires the optionasync to be enabled during initialization):

view.render(data,state).then(function(){// finished});

Or as async/await (requires the optionasync to be enabled during initialization):

awaitview.render(data,payload);// finished

Render a static template (didn't include any dynamic contents):

view.render();

Create Components

Just create a component from a template without adding/assigning/rendering them to the root ("orphan"):

varpartial=view.create(data);

Orphans are not a part of the internal render tree of a view. The construction of orphan components is also really fast.

Modify Views

Add one data item to the end:

view.add(data);

Add one data item to a specific index position (did not replace):

// add to beginning:view.add(data,0);

Add one data item to a reversed index position (did not replace):

// add before the last element:view.add(data,-1);

Append multiple data items to the end:

view.append(data);

Append multiple data before an index:

// append to beginningview.append(data,0);

Append multiple data before a reversed index position:

// append before the last element:view.append(data,-1);

Remove a specific template node:

Parameter:remove(position, <count>)

view.remove(node);

Remove a specific template node by its index:

view.remove(20);

Remove a specific template node by its reversed index:

// remove the last:view.remove(-1);

Remove a range of nodes starting from a specific node or index (included in removal):

view.remove(20,10);
view.remove(node,20);

Remove last 20 node items by using reversed index:

view.remove(-20,20);

Remove previous 20 node items starting of a given node/index (included in removal):

view.remove(node,-20);

Remove all:

view.clear();

Replace a data item/node:

view.replace(node,data);
view.replace(index,data);

Update a single data item/node:

view.update(node,data);
view.update(index,data);

Common View Helpers

Get a components root element by a specific index:

varnode=view.node(index);

Get the index from a specific components root element:

varindex=view.index(node);

Get the length of all components currently rendered:

varlength=view.length;

Get the current template name which is assigned to a Mikado instance:

varname=view.name;

Get the mounted root element on which the template is assigned to:

varelement=view.root;

Manipulate Views

Mikado provides you several optional helper functions to manipulate the DOM and also keep them in sync with the internal view state. Using the helper functions also will gain performance.

All helpers support passed parameter by index or by node.

Helpers let you apply simple transformations without running through the whole render loop of the template. Reconciliation isn't the holy grail, it is just for your laziness. In certain situations it is just more efficient to apply a known transformation directly instead of altering the data and request a whole render task.

Move a data item/node to a specific index position:

view.move(node,15);// 15 from startview.move(node,-15);// 15 from end

Move a data item/node to the top or bottom:

view.first(node);view.last(node);

Move a data item/node by 1 index up or down:

view.up(node);view.down(node);

Move a data item/node by a specific offset (pretty much the same asshift):

view.up(node,3);view.down(node,3);

Shift a data item/node relatively by a specific offset (both directions):

view.shift(node,3);view.shift(node,-3);

Move a data item/node before or after another data item/node:

view.before(node_a,node_b);view.after(node_a,node_b);

Swap two data items/nodes:

view.swap(node_a,node_b);

DOM State Caching

Caching of DOM properties can greatly increase performance (up to 20x). There are just a few situations where caching will not improve performance, it fully depends on your application.

Recommendation: enable caching when some of your data will stay unchanged from one to another render task. Disable caching when changes on data almost requires a fully re-render.

The state cache will just apply whenrecycle was enabled or thekeyed strategy was used. Otherwise, the cache is never used.

Caching is disabled by default, you will need to explicitly set this flag when initializing:

constview=newMikado(template,{recycle:true,cache:true});

It is very recommended reading the next section to understand how caching is working.

State Caching Concept

Let's take a simple template as an example:

<root><divclass="active">{{ data.title }}</div></root>

The template above has just one dynamic expression. It could be rendered as follows:

view.render({title:"foobar"});

Assume you get new data and wants to update the view, but the new data has still the same value for thetitle:

view.render({title:"foobar"});

This time, when cache was enabled no changes are applied to the text node, since the new value matches the previous cached value.That specific part now executes more than 10,000 times faster. Make a maximum use of this strategy will speed up things amazingly.

Now let's come to the most important part when using caching properly. Assume you have rendered the template above with caching enabled. Now youmanually change parts of the DOMwhich is covered by a dynamic template expression:

varnode=document.querySelector(".active");node.textContent="manual change";

The changes will apply to the DOM as expected. Now you re-render the template with the "old" state from the previous render:

view.render({title:"foobar"});

This time the change will not apply! Because the internal cache assumes that the current value is still "foobar" and skips the change.

You have 2 options in this situation:

  1. Do not manually change dom entries which are part of a dynamic template expression and update specific parts through rendering templates only.
  2. Using theDOM Cache Helpers Mikado provides you exactly for this situation.

DOM Cache Helpers (optional)

Caching helpers let you apply manual changes to the DOM easily without going out of sync with the corresponding view instance.

It is recommended also using these helpers to any DOM changes regardless if it is part of the template or not. Generally, these helpers will greatly improve your application performance.

A well implemented application can still save between 20 and 40% of unnecessary DOM access just by using those helpers everywhere. On regular implementations it is almost between 50% and 70%.

Set an attribute of a node (will not replace old attributes):

Mikado.setAttribute(node,"href","/foo");

Set multiple attributes of a node (will not replace old attributes):

Mikado.setAttribute(node,{id:"foo",href:"/foo"});

Get an attribute value of a node:

varattr=Mikado.getAttribute(node,"href");

Remove an attribute of a node:

varattr=Mikado.removeAttribute(node,"href");

Remove multiple attributes of a node:

varattr=Mikado.removeAttribute(node,["href","target"]);

Check existence of a nodes attribute:

varhref=Mikado.hasAttribute(node,"href");

Set class name of a node (fully replaces old classes):

Mikado.setClass(node,"class_a class_b");```~~~~```jsMikado.setClass(node,["class_a","class_b"]);

Add a classname to a node:

Mikado.addClass(node,"class_a");

Add multiple classnames to a node:

Mikado.addClass(node,["class_a","class_b"]);

Get all classnames of a node (returns an array):

varclassList=Mikado.getClass(node);

Toggle classnames of a node:

varclassList=Mikado.toggleClass(node,"class_a");

Toggle classnames of a node to a specific state (a short variant of conditional "add" and "remove"):

varclassList=Mikado.toggleClass(node,"class_a",true);

Toggle multiple classnames of a node:

varclassList=Mikado.toggleClass(node,["class_a","class_b"]);

Toggle multiple classnames of a node each of them to a specific state:

varclassList=Mikado.toggleClass(node,{"class_a":true,"class_b":false});

Check existence of a nodes classnames:

varclass_a=Mikado.hasClass(node,"class_a");

Removes a classnames of a node:

Mikado.removeClass(node,"class_a");

Removes multiple classnames of a node:

Mikado.removeClass(node,["class_a","class_b"]);

Set the whole elements inline style tagstyle="..." (fully replaces old styles):

Mikado.setCss(node,"top: 0; padding-right: 10px");
Mikado.setCss(node,["top: 0","padding-right: 10px"]);

Get all inline styles of a nodes style tag:

varcss=Mikado.getCss(node);

Set a specific inline style of a node (will not replace old styles):

Mikado.setStyle(node,"padding-right","10px");

Set multiple specific inline styles of a node (will not replace old styles):

Mikado.setStyle(node,{"top":0,"padding-right":"10px"});

Get a specific inline style value of a node:

varpadding=Mikado.getStyle(node,"padding-right");

Set text of an element or text node:

Mikado.setText(node,"This is a title.");

Get text of an element or text node:

vartext=Mikado.getText(node);

Set inner HTML of an element:

Mikado.setHtml(node,"<b>This is a title.</b>");

Get inner HTML of an element:

varhtml=Mikado.getHtml(node);

View State

Every Mikado instance has by default a state object you can access byview.state.

State is a payload keeping values and functions during runtime you can use within template expressions additionally to the data.The state also will be delegated through the whole render loop (including partials).You can bind one global state to every Mikado instances, you can also assign a dedicated state for each view.Additionally, a custom state could be passed on all render tasks.

constview=Mikado(template,options);console.log(view.state);// {}

When creating an instance you can optionally pass an extern state via options to share the same state object through multiple views:

conststate={foo:1};constview_a=Mikado(template_a,{ state});constview_b=Mikado(template_b,{ state});console.log(view_a.state);// { foo: 1 }console.log(view_b.state);// { foo: 1 }

You can access the state within templates by the builtin keyword "state" or also by using "this" which points to the current Mikado instance.

<div><p>{{ state.foo }}</p><!-- output: 1 --><p>{{ this.state.foo }}</p><!-- output: 1 --></div>

When using.render() you can optionally pass a state as 2nd parameter which will temporarily override the views default keyword "state" for this specific render task:

conststate={foo:1};constview=Mikado(template,{ state});view.render(data,{foo:2});
<div><p>{{ state.foo }}</p><!-- output: 2 --><p>{{ this.state.foo }}</p><!-- output: 1 --></div>

As you can see you can still access the original state by usingthis.state.

When usingforeach the keyworddata within nested template expressions refers to the most inner element.

<!-- data points to root --><tableforeach="data.rows"><!-- data points to root.rows[] --><trforeach="data.columns"><!-- data points to root.rows[].columns[] --><td>{{ data.value }}</td></tr></table>

If you need the root data element within nested templates then just assign the data to thestate or pass a temporary state object as 2nd parameter by simply using.render(data, data). Now you can access the root data element viastate through all the template scopes.

Custom Callbacks

The 2nd parameterview of custom callbacks points to the Mikado view instance.

Define custom callbacks during initialization:

varview=newMikado(template,{on:{create:function(node,view){console.log("created:",node);},recycle:function(node,view){console.log("recycled:",node);},insert:function(node,view){console.log("inserted:",node);},update:function(node,view){console.log("updated:",node);},replace:function(node,view){console.log("replaced:",node);},remove:function(node,view){console.log("removed:",node);},mount:function(root,view){console.log("mounted:",root);},unmount:function(root,view){console.log("unmounted:",root);}}});
CallbackDescription
createCalled when a new template node was created (not recycled).
recycleCalled when a template node was recycled instead of created.
insertCalled when a template node was inserted into DOM.
updateCalled when a template node was updated.
replaceCalled when a template node was replaced ny another template node.
removeCalled when a template node was removed.

Static Templates

When a template has no dynamic expressions (within curly brackets) which needs to be evaluated during runtime Mikado will handle those templates asstatic and skips the dynamic render part. You can render static views without passing data.

Once (One-time rendering)

When a template just needs to be rendered once you can theoretically create, mount, render and destroy as follows:

Mikado(template).mount(root).render().destroy();

You can also simply use a shorthand function:

// static views doesn't require dataMikado.once(root,template);
// if the view has dynamic contents just pass dataMikado.once(root,template,data);// full example by also using async callbackMikado.once(root,template,data,state,callback);

There is one important advantage when usingonce overrender. It will always append to the root without mounting:

Mikado.once(document.body,template);

When usingrender instead you probably can't do that, because it needs mounting anddocument.body isn't a root which just includes elements from the same template.So usingMikado.once is great when initializing your app and building the shape of the DOM layout.

If a view was destroyed you will need to create the Mikado instance again when re-using.

Server-Side Rendering (SSR)

Just use the same template syntax (or same source files also served for the client).

constmikado=require("mikado/ssr");constview=awaitmikado.compile("view/start.html",{compression:true,debug:false,cache:200});// render the html markupconsthtml=view.render([{/* data */}]);// send the html to the client, e.g.:res.send(html);

Supported Options (mixable):

  • compression minify the html markup (true/false)
  • debug when enabled it compiles the template on every render, good for development environments (true/false)
  • cache sets the size of the encoder-cache (true/false/number)
  • csr when set to "false" it fully unlocks template restrictions applied by the support of client-side-rendering

SSR-exclusive Mode

By explicitly setting the optioncsr to "false" you can switch into SSR-exclusive mode where the limitation of having one outer element as the template root is unlocked, also there is anextract directive to place logical placeholder elements, which will be self-extracted when rendered.

constmikado=require("mikado/ssr");constview=awaitmikado.compile("view/start.html",{csr:false});
<divif="data.length"extract><tableforeach="data"><tr><td>1</td></tr><tr><td>2</td></tr><tr><td>3</td></tr></table></div>

Those templates aren't supported by the client render engine, also you can't hydrate them.

Express Render Engine

constmikado=require("mikado/express");constexpress=require("express");constapp=express();// set path to your static viewsapp.set("views",[__dirname+"/view"// ...]);// set path to your partial views (optional)app.set("partials",[__dirname+"/partial"// ...]);// register engine to filetype .htmlapp.engine("html",mikado);// enable engine for filetype .htmlapp.set("view engine","html");

Custom Options

You can set options by Expressapp.set:

// enable compression (optional)app.set("view compression",true);// enable cache and set pool size (optional)app.set("view cache",200);// set debug to false to enable compiler cacheapp.set("view debug",false);

Or you can specify options bymikado.options alternatively:

mikado.options={compression:true,cache:200,debug:false};

Render Views

Register a route and render the file./view/start.html:

app.get("/",function(req,res){res.render("view/start",[{/* data */}]);});

Includes

Partials gets its own instance under the hood. This performance gain also makes a template factory re-usable when the same partials are shared across different views.

Be aware of circular includes. A partial cannot include itself or somewhere later in its own chain.

Assume you've created one or more partial templates. Make sure each of the partial templates is providing one single root as the outer bound.

The file structure might look like:

  • tpl/header.html
  • tpl/article.html
  • tpl/footer.html

You will need to compile the templates:

npx mikado-compile ./tpl/

You have to register all partial templates oncebefore you initialize the templates which will including them:

importtpl_headerfrom"./tpl/header.es6.js";importtpl_articlefrom"./tpl/article.es6.js";importtpl_footerfrom"./tpl/footer.es6.js";Mikado.register(tpl_header);Mikado.register(tpl_article);Mikado.register(tpl_footer);

When using templates in ES5 compatible format, they are automatically registered by default when loaded.

Include partial templates in another templatetpl/section.html:

<section><headerinclude="header"></header><articleinclude="article"></article><footerinclude="footer"></footer></section>

The "section" from above could be also included by another one (and so on):

<html><body><mainforeach="data.sections"include="section"></main></body></html>

Loop Partials

Assume the template example from above is a tweet (title, article, footer).

<section><title>{{ data.title }}</title><tweetsforeach="data.tweets"include="tweet"><!-- tweet --><!-- tweet --><!-- tweet --></tweets></section>

This expression will render the template "tweet" through an array of data items/tweets. The template "tweet" is getting the array valuedata.tweets asdata.

Thelimit andoffset attributes could be used optionally to specify a custom portion of the partial loop:

<tweetsforeach="data.tweets"include="tweet"limit="5"offset="5"></tweets>

Theoffset attribute could also be negative to reverse the boundary direction, e.g. loop through the last 5 items:

<tweetsforeach="data.tweets"include="tweet"limit="5"offset="-5"></tweets>

Inline Loops

You can also loop through an inline partial. Mikado will extract and referencing this partial to its own instance under the hood.

<main><title>{{ data.title }}</title><tweetsforeach="data.tweets"><section><headerinclude="header"></header><articleinclude="article"></article><footerinclude="footer"></footer></section></tweets></main>

You can also nest loops:

<!-- root view --><tweetsforeach="data.tweets"><!-- new partial template --><tweet><h1>{{ data.title }}</h1><title>Comments:</title><divforeach="data.comments"><!-- new partial template --><comment><p>{{ data.content }}</p><title>Replies:</title><divforeach="data.replies"><!-- new partial template --><p>{{ data.content }}</p></div></comment></div></tweet></tweets>

Every looped partial has to provideone single element root as the outer bound.

In this example every foreach-expression is wrong (you will find the right example above):

<tweetsforeach="data.tweets"><!-- no outer bound! --><h1>{{ data.title }}</h1><title>Comments:</title><divforeach="data.comments"><!-- no outer bound! --><p>{{ data.content }}</p><title>Replies:</title><divforeach="data.replies"><!-- no outer bound! -->      {{ data.content }}</div></div></tweets>

Conditional Template Structures

<main><titleif="data.tweet.length">Tweets: {{ data.tweet.length }}</title><titleif="!data.tweet.length">No tweets found.</title></main>
<main><title>{{ data.title }}</title><tweetsif="data.tweets.length"foreach="data.tweets"><section>{{ data.content }}</section></tweets></main>
<main><title>{{ data.title }}</title><tweetsforeach="data.tweets"><sectionif="data.content">{{ data.content }}</section></tweets></main>

Think in real code branches, instead of doing this:

<main>  {{@ var result = (function(){ return "some big computation"; }()) }}<sectionif="data.content">{{ result }}</section></main>

Doing this:

<main><sectionif="data.content">    {{ (function(){ return "some big computation"; }()) }}</section></main>

Conditional branches will skip their expressions inside when not taken.

Also, try to assign computations outside a loop by using the state to delegate values to the scope of the partial loop:

<main>  {{@ state.result = (function(){ return "some big computation"; }()) }}<tweetsforeach="data.tweets"><section>{{ state.result }}</section></tweets></main>

Reactive Properties (Proxy)

Mikado provides you a reactive approach to listen for changes to the data and apply them accordingly to the DOM.It is based on native Proxy feature which has great performance, a small memory footprint and fully falls back to a legacy observer when Proxy is not available.Using a reactive strategy can additionally boost performance beyond a factor of 100 when updating specific data instead of leverage a full render task.It depends on your application or current view, this feature has an advantage when updating datapartially has to process more often than full data updates.

Template markup:

<table><tr><td>Name:</td><td>{{= data.name }}</td></tr><tr><td>Email:</td><td>{{= data.email }}</td></tr></table>

The expression for an observable property uses this syntax:{{=. You can combine with other expressions, but should be defined at least, e.g.{{#= or{{!= or{{?=.

You can't use any Javascript code inside reactive expressions, just the full data scope of the value is allowed to specify within those expressions.

When using reactive properties you'll need to manage a store (could be a simple Array) which gets proxified under the hood.

// store must be an array of elements:conststore=[/* Array of objects */];// create, mount and initial render the store by using// a template which has reactive properties includedMikado(template).mount(root).render(store);// the store now has proxified item properties!// do not throw it away, instead apply updates on itstore[0].name="John Doe";store[0].email="john@doe.com";// when data changes, the corresponding DOM elements// will automatically change also

The data store must be an Array of elements, also when just having one item. Because the array index reference gets proxified, that's why you can't pass a single object.

If you just have a single data item, and you don't like the array index access you can also define a reference, but you need to do this after initially callingrender:

conststore=[{class:"active",value:"foo"}];// the store isn't proxifiedconsttest=store[0];// initial renderview.render(store);// the store array now was proxified!constitem=store[0];// these objects aren't the same anymoreconsole.log(test===item);// false// nothing will change on screen:test.value="bar";// this works properlyitem.value="bar";

On the upper example nothing on the DOM will change when you set the valuestest.value = "bar", because this reference holds the un-proxified original version.Setitem.value = "bar" will work properly.

Limitations

Actually there are some limitations on template expressions.

1. Fields from deeply nested data objects are not reactive:

vardata={id:"foobar",// <-- observablecontent:{// <-- observabletitle:"title",// <-- NOTbody:"body",// <-- NOTfooter:"footer"// <-- NOT}};

2. Template expressions including any kind of Javascript syntax are not supported:

<table><tr><td>Name:</td><!-- Supported: --><td>{{= data.name }}</td></tr><tr><td>Tweets:</td><!-- Not Supported: --><td>{{= data.tweets ? data.tweets.length : 0 }}</td></tr></table>

Just use plain property notation within the curly brackets.

Strict-Proxy Mode

Wheneverall your template expressions are just using proxy notation it enables a special "strict-proxy" mode under the hood, which further boosts performance from every update to a maximum. This mode has no advantage when every render loop has to apply almost new items.

This enables "strict-proxy" mode:

<item><caption>    Name:</caption><p>{{= data.name }}</p><caption>    Email:</caption><p>{{= data.mail }}</p></item>

This won't enable it:

<item><caption>    Name:</caption><p>{{= data.name }}</p><caption>    Email:</caption><p>{{ data.mail }}</p></item>

Also using conditionals, includes, loops and inline Javascript will prevent switching to the "strict-proxy" mode. You can't switch this mode by yourself. It just activates when conditions are met.

Observable Array (Virtual NodeList)

In addition to react on changes of property values you can additionally also listen to changes made to the Array index of the store.Mikado provides you an observable Array that acts like a native Array and apply all changes to a synchronized NodeList under the hood.It also uses native Proxy which fully falls back to a legacy observer, when not available.

Semantically the observable array you will get fromMikado.Array() is equal to an array-like Javascript Array.

Create an observable array:

varstore=newMikado.Array();

Create an observable array with initial data:

varitems=[ ...];varstore=newMikado.Array(items);

Every observable array requires binding to amounted Mikado instance, because it needs to apply render tasks somewhere:

varview=Mikado(template,{observe:store,mount:root});

You can also mount an observable array to a Mikado instance (and also switch mounting):

conststore=newMikado.Array();constview=Mikado(template,{mount:root});store.mount(view);

Now the observable array is linked with your instance. Whenever you change the array all changes will apply automatically to the corresponding DOM components.

You can use all common array built-ins, e.g.:

store.push({ ...});

varlast=store.pop();

store.unshift({ ...});

varfirst=store.shift();

store.slice(3,1);

store.splice(0,1,{ ...});

You canget and set via array index access. This feature also has a non-proxy fallback included.

store[0]={ ...};
store[store.length]={ ...};
varfirst=store[0];

You can replace the array contents by:

varitems=[ ...];store.set(items);

This is recommended instead of pushing each item one by one,store.set will also handle keyed reconciliation.

A list of all supported array prototypes:

  • length
  • push(obj)
  • pop()
  • shift(obj)
  • unshift(obj)
  • slice(index, count)
  • splice(index, count, insert)
  • concat(arr)
  • indexOf(obj)
  • lastIndexOf(obj)
  • includes(obj)
  • filter(fn)
  • map(fn)
  • reverse()
  • sort(fn)
  • swap(a, b)
  • forEach(fn)
  • set(arr) (used to replace the array contents)

These methods are implemented without some extensions like parameter chaining, e.g.array.push(a, b, c) is not available, instead, you have to call push for each item one by one.

There are some methods which slightly differs from the original implementation of native Arrays. The following methods will apply changesin place and returning the original reference instead of making a copy:

  • concat
  • filter
  • map

Whenever you need the original native Array behavior including all extensions and variants you can simply do that by:

constnew_array=[ ...];constcopy=Array.prototype.concat.call(store,new_array);
constcopy=Array.prototype.map.call(store,obj=>obj);

In a situation when falling back to the non-proxy polyfill because of missing support for native Proxy, there is a limitation.You cannot fill sparse arrays or access indexes which are greater than the currentarray.length.There is just one undefined index that could always access (by read/write) that is the last "undefined" index on an array when you callarray[array.length].This index is a special marker that increases the "virtual" array size.Whenever you assign a value to this special index the size of the observable index growth automatically and the next "undefined" index in the queue becomes this marker.This limitation is not existing when the ES6 proxy is available.

Also, there are some divergent characteristics when using reflection:

varstore=Mikado.Array();console.log(store.constructor===Array);// -> falseconsole.log(store.prototype===Array.prototype);// -> falseconsole.log(storeinstanceofArray);// -> falseconsole.log(Array.isArray(store));// -> falseconsole.log(storeinstanceofMikado.Array);// -> true

The proxy feature theoretically allows all those checks but could not be used to keep the polyfill working in addition to sharing most of the same codebase. Alternatively you can use aninstanceof check for identification.

Transactions

Since the array observer apply all changes on the array index instantly to the DOM, reconciliation has no chance to run.For this purpose you can use thestore.transaction() feature, which let you apply all changes within a function and commit them by taking reconciling into account.

store.transaction(function(){// collect changes:store[0].title="John";store[12].class="active";store[10]=store.pop();store[11]=store.shift();});// changes applied

A transaction is used when editing anexisting state in a bulk. Whenever you want to initialize a new state, e.g. when data was coming from a server, you should usestore.set(data) instead.

Component Pools

Using pools greatly enhance the strategy of keyed and non-keyed recycling. Mikado detects automatically if it needs to use keyed or non-keyed pooling and will apply different strategies optimized for each of them.

Pools just enables when a keyed or non-keyed recycle strategy was used in combination.

Enable pool (keyed or non-keyed):

constview=newMikado(tpl,{recycle:true,pool:true});

Mikado will auto-balance pools automatically.

Flush Pools

You can delete pool contents at any time by:

view.flush();

Hydration

Hydration is a concept where the server is sending some basic HTML structure (or the whole App/Page) and the client consumes those contents into its own rendering system. This will improve several performance aspects of page loading (e.g. the Lighthouse test) but also it enables you to have server-side-rendered content by also providing a full PWA (aka "Single-Page-Application") experience at the same time.

Mikado uses hydration strategy, where components are hydrated progressively right before a render task will be performed.

Assume the server was sending this HTML structure as initial:

<html><body><main><section><title>Title</title><tweets><tweet><!-- ... --></tweet><tweet><!-- ... --></tweet><tweet><!-- ... --></tweet></tweets></section></main></body></html>

Your template looks like:

<section><title>{{ data.title }}</title><tweetsforeach="data.tweets"><tweet><h1>{{ data.title }}</h1><title>Comments:</title><divforeach="data.comments"><comment><!-- ... --></comment></div></tweet></tweets></section>

When a mounted template matches the same DOM structure like the component which should be hydrated, the initialization of the template will boot up faster because the factory is derived instead of created. You can use Mikados SSR feature to provide client-compatible structures on the server-side.

WhenDEBUG is enabled (or by using one of the debug builds) you'll get a message in the console when hydration falls back into factory construction because of an incompatible DOM structure.

You can hydrate the existing structure when creating instance (prefetch):

constroot=document.querySelector("main");constview=newMikado(tpl,{mount:root,hydrate:true});

You can also do this just right before mounting by passing the 2nd parameter:

constview=newMikado(tpl);// ... somewhat later in the runtimeview.mount(document.querySelector("main"),/* hydrate? */true);

When a hydration breaks because it isn't compatible for some reason, it fully skips this process silently (logs a message when DEBUG was enabled) and falls back to a construction of a factory instead.

Web Components (Shadow DOM)

When using shadow DOM to build web components the compiler needs to apply a different strategy.Therefore, you will need 2 additional template tags:

  1. <component/> as the outer root will enable rendering on a shadow root
  2. <template/> will identify your template from the rest of markup
<component><!-- optional styles/scripts/etc. --><linkhref="css/component.css"rel="stylesheet"><scriptsrc="js/component.js"></script><style>#user-list{width:100%; }</style><script>window.username="John";</script><!-- you can include anything here ... --><!-- components requires the template tag --><template><!-- templates has single outer root element: --><tableid="user-list"><tr><td>User:</td><td>{{ window.username }}</td></tr><tr><td>Tweets:</td><td>{{ data.tweets.length }}</td></tr></table></template></component>

You can't use any template expressions outside<template/>.

You can also render any normal template (non-components) to a plain dedicated shadow root by using theshadow: true option (also supported by the light bundle):

constview=newMikado(tpl,{shadow:true});

Theoretically you can put the<link/>,<style/> and<script/> inside a normal non-component template by also using theshadow: true option.But there is one important difference. Within a normal template those tags could be re-rendered and this might end in re-initializing of all those assets.Within a web component there is a top level scope, which is created once and will stay for all your further template tasks.The template will render on a new "hidden" element<root/> which is part of the top level scope.That is because the view needs to be mounted to an element, and the top level scope of shadow root couldn't be mounted because of mixed content.Don't rely on the existence of<root/>, when using static templates orview.once() it might not exist.

Assume when mounted a web component template to an element<main>, the DOM structure looks like:

<main>  #shadow-root    <link/>    <style/>    <script/>    <root>      #template      #template      #template      ...    </root>

Full Template Example

Use this almost complete template example to check if you know everything about the template mechanism:

<maincache="true"id="{{ data.view }}"><table><thead><tr><th>Index</th><th>Title</th><th>Media</th><th>Category</th><th>Comment</th><th>Date</th><thinclude="pager"></th></tr></thead><tbodyforeach="data.entries"><script>{{@constdatestr=newDate(data.date).toLocaleString()}}</script><trkey="data.id"data-id="{{ data.id }}"><td>{{ index + 1 }}</td><td>{{= data.title }}</td><td>{{# data.media }}</td><td>{{? data.category }}</td><td>{{! data.comment }}</td><td>{{ datestr }}</td><tdstyle="opacity: {{ state.selected === data.id ? '1' : '0.5' }}"><selectchange="select-active:root"><optionvalue="on"selected="{{ data.mode === 'on' }}">Enabled</option><optionvalue="off"selected="{{ data.mode === 'off' }}">Disabled</option></select></td></tr></tbody><tfootif="!data.entries.length"><tr><tdcolspan="7">No entries found.</td></tr></tfoot></table></main>

A proper definition and call for this template could look like this:

// the named include "pager" needs to be registered before useMikado.register(tpl_pager);// define route "select-active"view.route("select-active",function(target,event){constid=Number(target.dataset.id);view.state.selected=id;});view.render({view:"video",entries:[{id:1,date:"2023-12-01T14:00:00",title:"A simple title 1",media:"<img src='img1.jpg'>",category:null,comment:"Some <script>untrusted</script> content",mode:"off"},{id:2,date:"2023-12-02T15:00:00",title:"A simple title 2",media:"<video src='mov2.mp4'>",category:null,comment:"Some <script>untrusted</script> content",mode:"on"},{id:3,date:"2023-12-03T16:00:00",title:"A simple title 3",media:"<img src='img3.jpg'>",category:null,comment:"Some <script>untrusted</script> content",mode:"off"}]});

Each template part explained:

  • cache="true" let the compiler prebuilt the cache strategy, you can't switch it to off when creating an instance
  • id="{{ data.view }}" simple expression for inserting dynamic content
  • if="!data.entries.length" the if-directive checks the condition and will render everything nested as a new template (inline definition or extern by using "include"), the nested template needs to have one outer element as the root
  • foreach="data.entries" the foreach-directive loops the rendering of array items by everything nested as a new template (inline definition or extern by using "include"), the nested template needs to have one outer element as the root
  • {{@ ... }} an expression to include pure javascript syntax (access limited by the scope of the template), wrapped into a<script/> tag just for runtime compiler support.
  • key="data.id" extract the key value from the data, a given key is limiting the recycling of already rendered components by a keyed strategy
  • data-id="{{ data.id }}" root exports "data.id" as an attribute, also define "root" as the event target for the listener "select-active", pretty useful when multiple routes on different elements needs the same data attributes
  • {{ index + 1 }} uses the builtin keyword "index" which refers to the current index of looped data
  • {{= data.title }} uses reactive approach by binding the html node to the data field, so when changing the datadata.title ="another title" the node contents will also change accordingly
  • {{# data.media }} allows to include html syntax (this is unsafe, don't pass user inputs, you will need to prevent XSS by yourself)
  • {{? data.category }} only prints a "truthy" value including 0 (skips undefined, null, NaN, false)
  • {{! data.comment }} escape the value before print out (SSR only)
  • {{ datestr }} access the variable which was created by inline syntax before
  • style="opacity: {{ state.selected === data.id '1' ? '0.5' }}" example of dynamic attribute value
  • change="select-active:root" assign the route named "select-active" and forward the event to the element which has the given attribute name assigned to it or in this case "root" points to the components root (so the target inside the root function becomes the forwarded element)
  • selected="data.active === 'yes'" when dynamic attribute values results to boolean "false" (not string) it will be removed from the element, because some attributes enables just by their existence (consider an option element having selected="false" will end up also as a truthy selection state)

Concept of Shared Components

Mikado heavily makes use of runtime optimization. Since it is not possible to predict the recycle state of the next render task, Mikado uses a technique calledprogressive enhancement on which optimizations will apply iteratively. Recycle enhancements growth as needed.

The most benchmarks you will find ends at the point where Mikado starts to shine. Rendering a simple table isn't really a complex task. Real applications have bigger structures including partials, includes, conditionals, etc. The concept of shared components was the basic idea of this library. It is the "ultimate" upgrade of the recycle paradigm and when properly used, it is one of the biggest optimization improvement you can unlock.


Mikado Shared Components (Concept)

Mikado will take away every complexity you might expect of such a system. You just need to structure your HTML templates and use.render(data), that's it!

Custom Builds

Thesrc folder of this repository requires some compilation to resolve the build flags. Those are your options:

  • Closure Compiler (Simple or Advanced, used by this library,example)
  • Babel + Pluginbabel-plugin-conditional-compile (used by this libraryhere)

As far as I know you can't resolve build flags with:

  • Webpack
  • esbuild
  • rollup
  • Terser

Please let me know when you have some additions. As long as you will see flags likeif(DEBUG) (could be minified) in your build you shouldn't use that.

These are some of the basic builds located in thedist folder:

npm run build:bundlenpm run build:lightnpm run build:modulenpm run build:es5

Perform a custom build (UMD bundle) by passing build flags:

npm run build:custom SUPPORT_CACHE=true SUPPORT_POOLS=true LANGUAGE_OUT=ECMASCRIPT5 POLYFILL=true

Perform a custom build in ESM module format:

npm run build:custom RELEASE=custom.module SUPPORT_CACHE=true SUPPORT_POOLS=true

Perform a debug build:

npm run build:custom DEBUG=true SUPPORT_CACHE=true SUPPORT_POOLS=true

On custom builds each build flag will be set tofalse by default when not passed.

The custom build will be saved todist/mikado.custom.xxxx.min.js or when format is module todist/mikado.custom.module.xxxx.min.js (the "xxxx" is a hash based on the used build flags).

Supported Build Flags
FlagValuesInfo
DEBUGtrue,falseOutput debug information to the console (default: false)
SUPPORT_CACHEtrue, falseDOM State Cache
SUPPORT_EVENTStrue, falseRouting & Event Delegation (template event bindings)
SUPPORT_KEYEDtrue, falseSupport for keyed recycling (reconciliation)
SUPPORT_WEB_COMPONENTStrue, falseSupport for web components (Shadow DOM)
SUPPORT_DOM_HELPERStrue, falseDOM Manipulation Helpers
SUPPORT_CACHE_HELPERStrue, falseDOM Cache Helpers
SUPPORT_ASYNCtrue, falseAsynchronous Rendering (support Promises)
SUPPORT_POOLStrue, falseSupport component pools for keyed and non-keyed recycle strategies
SUPPORT_REACTIVEtrue, falseUse reactive data binding
REACTIVE_ONLYtrue,falseUse a full reactive approach for all views, exclude.render() and dependencies from build (default: false)
SUPPORT_CALLBACKStrue, falseUse callbacks for specific render tasks
SUPPORT_COMPACT_TEMPLATEtrue, falseTurn on when templates are compiled with thecompact ordefault strategy
SUPPORT_COMPILEtrue, falseUse the runtime compiler

Compiler Flags
RELEASE




custom
custom.module
bundle
bundle.module
es5
light
Output debug information to the console (default: false)
POLYFILLtrue,falseInclude Polyfills (based on LANGUAGE_OUT)
PROFILERtrue,falseJust used for automatic performance tests
LANGUAGE_OUT










ECMASCRIPT3
ECMASCRIPT5
ECMASCRIPT_2015
ECMASCRIPT_2016
ECMASCRIPT_2017
ECMASCRIPT_2018
ECMASCRIPT_2019
ECMASCRIPT_2020
ECMASCRIPT_2021
ECMASCRIPT_2022
ECMASCRIPT_NEXT
STABLE
Target language

Copyright 2019-2024 Nextapps GmbH
Released under theApache 2.0 License

Packages

No packages published

Contributors9


[8]ページ先頭

©2009-2025 Movatter.jp