
litejs-build
LiteJS build system — HTML attributes (cat, min, drop, inline), asset handling, build phases
Install
/plugin install litejs-build@litejs-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add litejs/skills.
Contents
Discovered from sourceSkills 5
LiteJS Build System
HTML-driven build tool. Declare minification rules as attributes on <link> and <script> elements — no extra config files.
Commands
lj build --out=index.html dev.html # full form
lj b --out=ui/index.html ui/dev.html # shorthand
lj b # uses package.json#litejs/build
CLI Options
| Option | Default | Effect |
|---|---|---|
--assets | "{h}.{ext}" | URL template for assets copied to output dir. Placeholders: {h} git hash, {ext} extension, {name} original name |
--banner | "" | Add commented banner to output |
--cat | true | Build src files |
--fetch | true | Fetch remote resources |
--jsmin | "" | JS minification command (default: uglifyjs). Custom commands read stdin without -- |
--min | "" | Minified output file |
--out | "" | Output file. For JS/UI output: only indent/remove empty lines. --min fully minimizes |
--readme | "" | Replace readme tags in file |
--ver | "" | Override version string |
--worker | "" | Update worker file |
Options can be set in package.json#litejs or .github/litejs.json.
HTML Attributes
Attributes on <link> and <script> elements control the build:
| Attribute | Effect |
|---|---|
cat="file.js" | Concatenate listed source files into this element's src. Comma/space-delimited |
cat-drop="flags" | Configuration flags applied during source build (cat phase only) |
min="target.js" | Minimize content to target file. {h} replaced with git hash |
min="" | Empty min appends to previous min target of same type |
drop="flags" | Configuration flags applied during minification (min phase only) |
inline | Embed file content directly into the HTML output |
exclude | Remove element from production output |
banner="text" | Add banner comment to the minified file |
if="expr" | Load condition for dynamic code loader |
integrity | Recalculate SHA-256 integrity hash |
rewrite="glob:target" | Rewrite file references with hashed names |
Path Expansion
+ and % in cat and min values expand relative to the previous path:
cat="@litejs/ui,+/pointer.js" → @litejs/ui, @litejs/ui/pointer.js
min="app.js?{h}" → app.js?<git-hash>
min="%.min.js" → app.min.js (replaces from last .)
Build Phases
The HTML build runs in strict order. Understanding this prevents ordering bugs.
Phase 1: Exclude
Remove elements with exclude attribute.
Phase 2: Cat (source build)
Process elements with cat attribute and their siblings (cat="").
- Reads source files, applies
cat-dropflags - Concatenates siblings into the cat element
- Writes result to inDir (source folder)
- Copies to outDir if different
Phase 3: Min (minification setup)
Process elements with min attribute and their siblings (min="").
- Groups elements by min target
- Reads source files, applies
dropflags .uiview files split:%css→ CSS element,%js→ JS element, template → UI element
Phase 4: Asset copy
Copy [src] and [href] elements to outDir (when building to different directory).
Phase 5: Pending writes
Minimize content and queue writes (not immediate — allows parseView appends).
Phase 6: Inline
Embed [inline] and remaining [min] elements into HTML.
- Handles
{loadFiles}and{loadRewrite}placeholders - Flushes pending writes after inline processing
Phase 7: Output
Serialize HTML. CSS is minified with @import resolution and URL rewriting.
Configuration Flags (drop / cat-drop)
Toggleable comment blocks that can be activated per build target:
/*** ie8 ***/
function legacyCode() {} // included in source
/*/
function legacyCode() {} // minimal stub for production
/**/
drop="ie8" on a min element flips the toggle — the first block is commented out, the second becomes active.
drop— applied during min phase onlycat-drop— applied during cat phase only- Multiple flags:
drop="ie8 debug"(space-separated)
Asset Handling
When building to a different output directory (--out=build/index.html dev.html):
- HTML assets —
<img src>,<link href>elements are copied viacpOut - CSS assets —
url()references are copied and renamed using--assetstemplate - View assets —
[src=...]in.uitemplates are copied and renamed (onlysrc, nothref— links are left untouched)
The {h} placeholder in min attribute and --assets uses abbreviated git object hashes from git ls-files --abbrev=1.
Skipped URLs:
- Scheme URLs (
data:,http:,mailto:, etc.) — detected by/^\w+:/ - Fragment-only references are preserved:
icons.svg#star→ copiesicons.svg, returnshash.svg#star
Example: Full dev.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<base href=/ >
<!-- Build CSS: concat base+theme, minimize to min.css -->
<link rel="stylesheet" href="app.css" min="min.css?{h}" cat="@litejs/ui/css/base.css,%.grid.css">
<link rel="stylesheet" href="theme.css" min>
<!-- Inline the loader for faster first paint -->
<script src="load.js" inline cat="@litejs/ui/load"></script>
</head>
<body>
<!-- Main app bundle -->
<script src="app.js" min="app.min.js?{h}" banner="MIT" cat="@litejs/ui,%/model">
</script>
<script src="polyfill.js" min="%.min.js" cat="@litejs/ui/polyfill/es5.js" if="!Function.prototype.bind"></script>
<!-- View templates -->
<script type="ui" src="views.ui" min="views.ui"></script>
<!-- Dev-only tools -->
<script src="debug.js" exclude></script>
</body>
</html>
Build: lj b --out=build/index.html ui/dev.html
Internals (lib/build.js)
Key functions for contributors:
| Function | Purpose |
|---|---|
build(opts) | Entry point, dispatches to html() or jsMin() |
html(opts, next) | HTML build pipeline |
clean(str) | Remove whitespace preserving strings and operators |
drop(el, content, attr) | Flip toggleable comments matching flags |
defMap(str) | Path expansion (+ append, % suffix replace) |
cssMin(str, urlFn) | Minify CSS via @litejs/dom CSS.minify() with optional URL callback |
parseView(content, extTo, lastMinEl, urlFn) | Split .ui into %css/%js/template, rewrite [src=] URLs |
viewMin(str, attrs) | Minify view template (join bindings, compact selectors) |
write(dir, name, content, el) | Write file, handle {h} hash replacement |
Exported for testing
var build = require("./lib/build.js")
build.clean(str)
build.drop(el, content, attr)
build.defMap(str)
build.cssMin(str, urlFn)
build.parseView(content, extTo, lastMinEl, urlFn)
JS/UI Build (non-HTML)
Build directly to .js or .ui output without an HTML file:
# Build JS bundle from mixed inputs (.js, .css, .ui/.view files)
lj b --min=app.min.js src/app.js src/style.css src/views.ui
# Build .ui output (unminified JS/CSS, indented sections)
lj b --out=app.ui src/app.js src/style.css src/views.ui
# Build .ui output (minified JS/CSS/UI)
lj b --min=app.min.ui src/app.js src/style.css src/views.ui
Input file transforms:
.ui/.view→ split into%css/%js/template sections (JS output:xhr.css()/xhr.ui()calls).css→ JS output: wrapped inxhr.css(), UI output:%csssection.js→ JS output: concatenated, UI output:%jssection
Consecutive xhr.css() calls are merged in JS output.
Custom JS minifier
# Use esbuild instead of uglifyjs
lj b --jsmin="esbuild --minify --loader=js" --min=app.min.js app.js
# Use terser
lj b --jsmin="terser -c -m" --min=app.min.js app.js
Can be set in .github/litejs.json:
{
"build": {
"jsmin": "esbuild --minify --loader=js"
}
}
Common Patterns
Cat without min — build source file only, no minification:
<script src="app.js" cat="src/a.js,src/b.js"></script>
Min without cat — minify existing file:
<script src="app.js" min="app.min.js"></script>
Inline view with separate min — views inlined in HTML, also written to file:
<script type="ui" src="views.ui" min="views.min.ui"></script>
Hash-based cache busting:
<script src="app.js" min="app-{h}.js"></script>
<link rel="stylesheet" href="app.css" min="app-{h}.css">
Different drop flags for cat vs min:
<script src="app.js" cat="src/*.js" cat-drop="dev" min="app.min.js" drop="ie8"></script>
LiteJS Release Helper
Automates package releases: version bump, changelog, commit, tag, and publish instructions.
Command
lj release [version] # full form
lj r [version] # shorthand
What It Does (in order)
git fetch+ verify upstream is ancestor of HEADrm -rf node_modules && npm installlj lintnpm outdated(local deps)npm outdated -g(global deps, if configured)- Bump version in configured files (date-based
YY.MM.0or increment last segment) - Verify git tag
v<version>does not exist lj buildlj test --brief test/index.js- Generate changelog from commits, grouped into categories
- Open
$EDITOR(default: vim) for review git commit -a+git tag -a v<version>- Print version and
npm publishcommand
Options
| Flag | Default | Effect |
|---|---|---|
--no-build | build | Skip build step |
--no-install | install | Skip node_modules reinstall |
--no-lint | lint | Skip linting |
--no-test | test | Skip tests |
--no-update | update | Skip outdated check |
--no-upstream | upstream | Skip upstream check |
--no-global | global="" | Skip global outdated check |
--rewrite | false | Amend the last release tag instead of creating new |
--set-version | ["package.json#version"] | Files to update version in. file#path notation, supports JSON (dot path) and TOML ([section].key) |
Options can also be set in package.json#litejs or .github/litejs.json.
Version Files
By default, only package.json#version is updated. Use --set-version to update additional files:
lj r --set-version="package.json#version" --set-version="tree-sitter.toml#package.version"
Or in .github/litejs.json:
{
"release": {
"setVersion": ["package.json#version", "tree-sitter.toml#package.version"]
}
}
Supported formats:
- JSON — dot-separated path:
manifest.json#metadata.version - TOML — section + key:
config.toml#package.versionmatchesversionunder[package]
Version Bumping
- If current month/year is newer than last version: bumps to
YY.MM.0(e.g.26.2.0) - Otherwise: increments last segment (e.g.
26.1.0->26.1.1) - Explicit version:
lj r 1.2.3overrides auto-calculation - Pre-release versions (4+ dot-segments like
1.2.3-beta.1) always increment last segment
Changelog Categories
Commits since last tag are grouped by subject line matching:
| Category | Pattern |
|---|---|
| New Features | /\badd\b/i |
| Removed Features | /\b(remove|drop)\b/i |
| API Changes | /\bapi\b/i |
| Breaking Changes | /\bbreak[ei]/i |
| Fixes | /fix\b/i |
| Enhancements | catch-all |
The generated message looks like:
Release v26.2.0
New Features:
- Add foo support (Author Name)
Fixes:
- Fix bar edge case (Author Name)
After Release
After the command completes it prints:
VERSION: 26.2.0
PUBLISH: npm publish
For pre-release versions it prints npm publish --tag next.
Full release cycle
lj r # creates commit + tag locally
git push && git push --tags # triggers CI
# CI runs tests, verifies tag signature, creates GitHub release, publishes to npm
Rewrite Mode
lj r --rewrite amends the last release — rebases onto previous tag, cherry-picks, then git commit --amend and git tag -f.
CI Integration
LiteJS repos use a shared GitHub Actions workflow (litejs/.github/.github/workflows/release.yml) triggered by refs/tags/v*:
- Verify SSH signature on tag
- Create GitHub release from tag message
npm publish --provenance --access public(taggedlatestornext)
Requires: RELEASE_SIGNERS variable and NPM_TOKEN secret in GitHub repo settings.
Troubleshooting
Each step can fail independently. The error message tells you which --no-* flag to use to skip it:
fatal: dependencies can not be installed! Ignore with --no-install option.
Common quick release (skipping slow steps):
lj r --no-install --no-update --no-global
LiteJS Style Guide
Coding conventions for LiteJS projects. These diverge from standard JS/CSS defaults — follow them exactly.
JavaScript
No Semicolons
Do NOT add semicolons at end of lines. Use a semicolon ONLY before [, ( or / at the beginning of a line:
var arr = [1, 2]
;[3, 4].forEach(fn)
;(function() {})()
Comma-First Declarations
Uninitialized variables first on one line, then comma-first for initialized:
var foo, bar
, MAX_AGE = 120
, baz = "baz"
, quux = 123
Leading Dot for Chains
person
.be("confused")
.do("makeup")
Switch/Case Same Level
switch (sex) {
case "male":
person.wear("bow tie")
break
default:
person.be("confused")
}
Functions
- Prefer declarations over expressions:
function a() {}notvar a = function() {} - Don't use
thatfor outerthis— use lowercased constructor name:var person = this - Pass scope instead of binding:
arr.map(fn, scope)notarr.map(fn.bind(scope)) - Accept optional scope argument in functions with callbacks
Naming
| Convention | Use |
|---|---|
lowerCamelCase | methods, variables |
UpperCamelCase | constructors |
CAPITAL_SNAKE_CASE | symbolic constants |
_prefix | private methods/properties |
Spacing
- One space before
{, after;in for loops, around binary operators1 + 2 - No space between unary operator and variable:
i++ - Braces on same line as statement
General
- Tabs for indentation, spaces for alignment within a line
- Max 80 character lines (don't break greppable strings like log messages)
- Double quotes; single only to avoid escaping
- UNIX newlines, newline at end of file
- No trailing whitespace, no indented empty lines
- Hyphens instead of spaces in file/directory names
CSS
- One selector per line, one rule per line
- SUIT CSS naming:
[<namespace>-]<ComponentName>[-descendentName][--modifierName] .is-modifiers only combined with a component (.Btn.is-error, never.is-erroralone)- No ID selectors, no preprocessor, no media queries
- Align vendor-prefixed properties with spaces
- Shorthand properties where possible
.Icon {
width: 16px;
height: 16px;
-webkit-transition: all 4s ease;
-moz-transition: all 4s ease;
transition: all 4s ease;
}
.Icon--person { background-position: -16px 0 ; }
.Icon--files { background-position: 0 -16px; }
Commits
Format: scope: Capitalized summary up to 50 chars
- Imperative present tense: Add, Fix, Update, Remove, Refactor, Document, Test
- Optional scope narrows area: build, ci, docs, style, test, ui/form
!prefix for breaking changes:! Rewrite public api- No period at end of subject
- One commit = one thing
- Fix bug = write regression test
Common AI Mistakes
| AI default | Correct LiteJS style |
|---|---|
var x = 1; | var x = 1 (no semicolon) |
var x = 1, y = 2 | Comma-first (see above) |
case "a": indented | case "a": same level as switch |
.bind(this) | Pass scope argument |
var that = this | var person = this (constructor name) |
const fn = () => {} | function fn() {} (declaration) |
'single quotes' | "double quotes" |
| Semicolons everywhere | Only before [, (, / at line start |
LiteJS Testing Framework
Zero-dependency test framework. ES5 compatible. Runs in Node.js and browsers.
Running Tests
npm i -g @litejs/cli
lj test # run test/*.js (default glob)
lj t # shorthand
lj t test/foo.js # specific file
lj t test/foo.js 5 # run only test case #5 (file required)
lj t --tap # TAP output
lj t --brief # failures only
lj t --watch # re-run on file change
lj t --up # update snapshots
lj t --seed=123 # deterministic Math.random
lj t --timeout=5000 # default test timeout ms
lj t --no-color # disable ANSI colors
lj t --tz=UTC # set timezone
# direct invocation without @litejs/cli globally installed
node -r @litejs/cli/test.js test/foo.js
# direct invocation only in @litejs/cli repo
node -r ./test.js test/foo.js
Test Structure
describe("Suite", function() {
test("case", function(assert) {
assert.ok(true)
assert.end()
})
it("returns promise", function(assert) {
return Promise.resolve() // auto-ends on resolve/reject
})
it("with mock", function(assert, mock) {
// mock available when fn has 2+ params
assert.plan(2) // auto-ends after 2 assertions
assert.ok(1).ok(1)
})
it("pending test") // no fn = pending/skipped
it("skipped", false, fn) // data=false = skipped
})
Variants: describe (suite), test/it (case, "it" prefixes output), should (prefixes "it should").
Chaining: describe(...).test(...).it(...) — all return describe.
Object suites: describe("Name", { "case": fn, "nested": { "sub": fn } })
Assert Methods
All chainable, return assert. The assert param is itself callable: assert(value, msg, actual, expected).
| Method | Check |
|---|---|
ok(value) | truthy |
notOk(value) | falsy |
equal(actual, expected) | deep equal (handles NaN, Date, RegExp, circular) |
notEqual(actual, expected) | not deep equal |
strictEqual(actual, expected) | === |
notStrictEqual(actual, expected) | !== |
own(actual, expected) | actual has all properties of expected (subset match) |
notOwn(actual, expected) | inverse of own |
throws(fn) | fn must throw |
type(value, name) | describe.type(value) === name |
anyOf(value, array) | value in array |
has / hasNot | aliases of own / notOwn |
skip(...) | no-op, keeps the chain |
Control: assert.end(), assert.plan(n), assert.setTimeout(ms)
Data-Driven Tests
it("adds {0} + {1}", [
[1, 2, 3],
[4, 5, 9]
], function(a, b, expected, assert) {
assert.equal(a + b, expected).end()
})
// Suite-level tables
describe("env {0}", [["dev"], ["prod"]], function(env) {
it("case {0}", [[1], [2]], function(val, assert) {
assert.end()
})
})
{0}, {1} in name are replaced from each row; {0.key} reads a property of a row item.
Data args come before assert, mock params. A non-array row is wrapped: [1, 2] equals [[1], [2]].
All rows must have the same length, and the test fn may declare at most row length + 2
parameters (assert, mock) — otherwise the runner throws Invalid data for: <name>.
Mock
Available as second parameter when test function has 2+ args. Auto-restored after assert.end().
mock.fn([behavior])
var spy = mock.fn() // returns undefined
var wrap = mock.fn(originalFn) // wraps, tracks calls
var cycle = mock.fn(["a", "b", "c"]) // cycles return values
var map = mock.fn({
'"1",2': 'fn called with one string and number',
'*': 'default'
}) // maps serialized args to result
var val = mock.fn(42) // always returns 42
var async = mock.fn(originalFn, true) // returns Promise
var cb = mock.fn(originalFn, 0) // calls args[0](err, result)
spy.called // call count
spy.calls // [{scope, args, error, result}, ...]
spy.errors // error count
spy.results // [returnVal, ...]
A wrapped function's throw is caught, not rethrown: the call records error,
spy.errors increments, and the spy returns undefined (a rejected Promise with behavior: true).
mock.spy / mock.swap
mock.spy(obj, "method") // wrap with spy
mock.spy(obj, "method", stubFn) // replace with spy
// spy() returns nothing — read stats from the swapped member: obj.method.called
mock.swap(obj, "key", newValue) // replace value, returns the previous value
mock.swap(obj, {a: 1, b: 2}) // replace multiple
mock.restore() // manual restore (auto on end)
mock.time / mock.tick
Replaces Date, setTimeout, setInterval, setImmediate, clearTimeout, clearInterval, clearImmediate, process.nextTick, process.hrtime.
mock.time() // freeze at current time
mock.time("2024-01-15T10:30:00Z") // freeze at specific time
mock.time(1705312200000) // freeze at epoch ms
mock.tick(100) // advance 100ms, run timers
mock.tick() // advance to next timer
mock.rand
mock.rand() // deterministic random using conf.seed
mock.rand(12345) // specific seed
// Math.random() now returns reproducible sequence
Snapshots
Requires require("../snapshot.js") in test file.
assert.matchSnapshot("file.js", actual) // compare to file.snap.js
assert.matchSnapshot("file.js", transformFn) // transformFn(fileContents)
assert.cmdSnapshot("lj build f.js", "f.js") // run cmd, compare stdout
assert.cmdSnapshot("cmd", "f.js", { expectFail: true }) // non-zero exit ok
Update all snapshots: lj t --up
Browser Testing
Create an HTML file that loads test.js runner and test files via script tags:
<pre id=out></pre>
<script src="litejs-full.js"></script>
<script src="test.js"></script>
<script src="ui-test.js"></script>
<script>
describe.onend = function() {
out.textContent = describe.output
}
</script>
<script src="my-tests.js"></script>
Output is collected in describe.output and rendered in onend callback.
Run with lj ui-test:
lj ui-test # default: test/index.html on :8091
lj ui-test my-page.html # custom URL path
lj ui-test --port=3000 --budget=10000 # custom port and timeout
Starts a local server, finds Chrome/Chromium, runs headless, exits 0/1. Port auto-increments if in use.
UI Test Assertions (ui-test.js)
ui-test.js extends the test framework with browser assertions for LiteJS UI apps.
All methods are chainable and poll the DOM until conditions are met or timeout is reached.
Navigation:
assert.open(url[, replace])— Navigate viaLiteJS.go().assert.waitView(route[, options])— Poll untilLiteJS.ui.routematches.assert.waitSelector(sel[, options])— Poll until selector is in DOM.
DOM Assertions:
assert.hasText(sel, expected[, options])— Poll until element text matches.assert.hasElements(sel, expected[, options])— Poll until element count matches.assert.fill(sel, value[, options])— Set input value.assert.click(sel[, options])— Poll until element found, then dispatch click.
Async Control:
assert.wait()— Queue subsequent calls. Returnsresumefunction.assert.waitFor(fn[, options])— Pollfnevery 50ms until truthy.
Layout:
assert.resizeTo(width, height)— Resize viewport and emit resize event.assert.isVisible(el)— Assert element has non-zero dimensions.
Coverage:
assert.collectCssUsage([options])— Track CSS selector matches on view show.describe.unusedCss()— Return array of unused selectors (for build tools).assert.assertCssUsage()— Assert no unused selectors remain.assert.collectViewsUsage()— Track view show events.describe.unusedViews()— Return array of unused view routes (for build tools).assert.assertViewsUsage()— Assert all defined views were shown.
Example:
describe("app", function() {
it("should render home", function(assert) {
assert
.open("")
.waitView("home")
.hasText("h2", "Welcome")
.end()
})
it("should navigate", function(assert) {
assert
.click('a[href="#about"]')
.waitView("about")
.hasText("h2", "About")
.hasElements("ul > li", 3)
.end()
})
})
LiteJS UI Engine
Dependency-free ES5 UI engine (~25kB). Templates, routing, data binding, i18n, touch gestures — no transpiling/bundling.
Although written in ES5, LiteJS works seamlessly in ESM projects — just include the scripts and start building.
Template Syntax (.ui files)
Indentation-based hierarchy using CSS selectors. Indent = child, dedent = sibling.
h1 My list
ul.green.star
li
a[href="#a"] Item A
li > a[href="#b"] Item B
footer
button:disabled My button
Becomes <h1>My list</h1><ul class="green star"><li><a href="#a">Item A</a></li>....
Selectors: tag#id.class1.class2[attr=value]. Omitting tag defaults to div.
Child combinator: li > a[href="#b"] Item B — inline child.
Text content: bare text after selector becomes element text via i18n: _(text).
Raw text: = text content — direct text node insertion, no i18n.
Comments: / comment text — lines starting with /.
Plugins (% prefix)
| Plugin | Usage | Purpose |
|---|---|---|
%view name [parent] | %view home #public | Define routed view |
%el name | %el Dialog | Define reusable custom element |
%slot [name] | %slot footer | Content placeholder in custom elements |
%def routes files | %def users/{id} users.js,%.css | Define route with file dependencies |
%css | %css + indented CSS block | Inject inline CSS |
%js | %js + indented JS block | Inline JavaScript handlers |
%each items | %each ["a","b"] | Replicate template block |
%svg name | %svg icon | Define SVG custom element (alias for %el) |
%start | %start | Trigger app initialization (start routing) |
View names: A leading # (e.g. #public, #login) makes a view a non-routable structural container — used as a parent / %slot host, or shown programmatically (app.show("#login") / $ui("#login").show()), but not reachable via an href. Routable views have no leading #; href="#home" navigates to the route home (the # is the URL fragment marker, not part of the view name — so href="#login" does not reach a view named #login).
Custom elements: After %el Dialog, use Dialog as a selector in templates.
Loading Templates
Templates are loaded from <script type="ui"> tags in HTML:
<script type="ui">
%view home #
h1 Hello
%start
</script>
<script src="https://litejs.com/litejs.full.min.js"></script>
External .ui files: <script type="ui" src="views.ui"></script>
Bindings (; prefix)
Bindings connect data to DOM. Suffix ! = execute once, don't update.
| Binding | Syntax | Effect |
|---|---|---|
;txt | ;txt expression | Set text content |
;cls | ;cls "active", condition | Add/remove CSS class |
;css | ;css "color", value | Set inline style |
;set | ;set "data-id", id | Set attribute |
;val | ;val formField | Two-way form value binding |
;if | ;if condition | Conditional render (removes/restores element) |
;each | ;each! "item", array | List iteration, creates subscope per item |
;el | ;el tagName | Dynamic element type |
;ref | ;ref myRef | Store element reference in scope |
;name | ;name fieldName | Set form element name |
;view | ;view url | Set href for view navigation |
;on | ;on "event", handler | Attach event listener |
;one | ;one "event", handler | One-time event listener |
;is | ;is value, "a,10=b,20=c" | Threshold-based class switching |
;d | ;d text | Render block-level document markup |
;t | ;t text | Render inline markup |
;xlink | ;xlink "#route" | SVG namespace href (xlink:href) |
$s | ;$s | Initialize scope with element attributes |
Once modifier: ;txt! value — bind at render, never re-evaluate.
Default binding: Bare text h1 Hello becomes ;txt _("Hello",$s) — auto i18n lookup.
Unknown bindings fall through to ;set (attribute setter). E.g., ;href! url sets the href attribute.
Separator: : works the same as space: ;txt:value equals ;txt value.
View-level bindings: Inside %view, bindings set view properties. ;f "file.js" sets file dependencies loaded on navigation.
Event Shorthand (@ prefix)
@click handler → ;on! "click", handler
@click! handler → ;one! "click", handler
@keyup "navigate", param → ;on! "keyup", "navigate", param
Event handlers can be strings (emitted on View) or function references.
Important: Outside of %view blocks, @click handler resolves handler from the scope chain. Since the scope is $d (global scope), the handler function must be on $d:
%js
// WRONG — function declaration not accessible from template scope
function doSomething() { ... }
// RIGHT — attach to $d so template bindings can find it
$d.doSomething = function() { ... }
;val Binding Details
;val is designed for form-level two-way binding. Put ;val data on a form element and use name attributes on inputs:
form
;val data
input[name=email][type=email]
textarea[name=notes][rows=4]
This syncs form values into $d.data = {email: "...", notes: "..."}.
Gotcha: Using ;val field on a standalone input/textarea (outside a form with ;val) does not reliably sync user input back to the scope variable. For standalone elements, either wrap in a form or read the DOM value directly:
var el = document.getElementById("myInput")
var value = el.value
Views and Routes
Initialization
var app = LiteJS()
Options only needed when changing defaults:
| Option | Default | Effect |
|---|---|---|
home | "home" | Default view name |
root | document.body | Root element for views |
breakpoints | — | Responsive breakpoints, e.g. "sm,601=md,1025=lg" |
locales | — | Locale definitions, e.g. {en: "en"} |
globals | — | Default translations |
Returns View constructor. Available as $ui in templates, use chosen variable name (app) in plain JavaScript.
Defining Views
In .ui templates:
%view #public #
.app
nav
a[href="#home"] Home
%slot
%view home #public
p Welcome
%view user/{userId} #public
p User {params.userId}
#public is a structural container (no route, hosts %slot); home and
user/{userId} are routable. a[href="#home"] navigates to the route home.
A #-prefixed view has no href route — reach it with app.show("#name") /
$ui("#name").show(), or nest routable children under it.
In JavaScript:
app.def("route file.js,file.css\nuser/{id} user.js")
app.show("home")
app.get(url, params)
app.param(["user"], function(value, name, view, params) { /* resolve */ })
View Lifecycle
Navigation: app.show(url) → route match → ping (each view, async-friendly with this.wait()) → render → open → show.
| Event | When |
|---|---|
ping | Before render, fetch data here. Call this.wait() for async. |
pong | After render |
open | View becomes active |
close | View deactivated |
nav | Navigation started |
show | Navigation complete |
resize | Viewport resized |
Scope Variables
| Variable | Contains |
|---|---|
$s | Current scope |
$el | Current element |
$ui | View router (in templates; use chosen var name in plain JS) |
$d | Global scope |
$up | Parent scope |
$i | Loop index (inside ;each) |
$len | Loop length (inside ;each) |
_() | i18n format function |
params | URL parameters |
El API
El(selector) — Create DOM element from CSS selector string.
El("div#id.class1.class2[data-x=1]") // Create element
Static Methods
| Method | Purpose |
|---|---|
El.append(parent, child) | Append, handles slots |
El.render(el) | Process bindings on element tree |
El.scope(el, parent) | Get/create scope for element |
El.cls(el, name, add, sel, delay) | Add/remove/toggle class (transfer mode: add as DOM element removes class from that element and adds to el; auto-revert after delay ms) |
El.flip(el, sel, fn, opts) | FLIP animation (snapshot, mutate, animate) |
El.get(el, attr) | Get attribute |
El.val(el, val) | Get/set form value (handles nested forms, selects, checkboxes) |
El.kill(el, transition) | Remove element (with optional CSS transition) |
El.empty(el) | Remove all children |
El.replace(old, new) | Replace element |
El.closest(el, sel) | Find closest ancestor matching selector |
El.matches(el, sel) | Test if element matches selector |
El.nearest(el, sel) | Find nearest element |
El.rate(fn, ms) | Throttle function calls |
El.stop(event) | Stop event propagation |
El.addKb(map, killEl) | Push keyboard shortcut map |
El.rmKb(map) | Remove keyboard shortcut map |
El.asEmitter(obj) | Add .on/.off/.one/.emit to object |
El.$b | Bindings object |
El.$d | Global scope |
El.T | Text attribute name (textContent or innerText) |
Emitter Pattern
El.asEmitter(MyProto.prototype)
var obj = new MyProto()
obj.on("event", handler, scope) // Listen
obj.one("event", handler, scope) // Listen once
obj.off("event", handler, scope) // Remove
obj.emit("event", data) // Returns listener count
i18n Format Functions
_("key") — translate. _{format, data} — format with substitution.
| Format | Symbol | Example |
|---|---|---|
date | @ | _{@D, timestamp} |
num | # | _{#.01, 3.14159} |
plural | * | _{*item, count} |
pick | ? | _{?gender, value} |
pattern | ~ | _{~phone, "+1234567"} |
map | map | _{map items, template} |
lo | lo | lowercase |
up | up | UPPERCASE |
Keyboard Shortcuts
El.addKb({
h: goHome,
"shift+s": goSettings,
"mod+h": goHome, // cmd on Mac, ctrl on PC
bubble: true, // bubble to previous map
input: true // capture in inputs
})
El.rmKb(map)
In templates (preferred — automatically added/removed when the view opens/closes). String values navigate to the view, function values are called directly:
%view home #public
@kb {h: "home", u: "users", "ctrl+s": save}
El.addKb/El.rmKb can be used directly in JavaScript but requires manual cleanup. The template version is preferred as it binds to the view lifecycle.
Touch/Pointer Events
Built-in gesture recognition via event system:
| Event | Fires when |
|---|---|
pan | Single-pointer drag |
pinch | Two-pointer distance change |
rotate | Two-pointer angle change |
tap | Quick touch |
hold | Long press |
Event properties on pan/hold events:
| Property | Contains |
|---|---|
e.el | The element that initiated the gesture |
e.mode | Gesture mode ("pan" or "hold") — set on panstart/holdstart event object |
e.x0, e.y0 | Pointer start position (clientX/Y at pointerdown) |
e.dx, e.dy | Delta from start |
e.ex, e.ey | Current position offset (dx + element's CSS left/top) |
El.flip — FLIP Animations
El.flip(el, sel, fn, opts) — Animate DOM mutations using the FLIP technique.
// Snapshot positions, mutate DOM, animate the difference
El.flip(container, ".item", function() {
container.appendChild(someItem)
})
// Snapshot only (no animation) — returns position array
var positions = El.flip(container, ".item")
Options:
| Option | Default | Effect |
|---|---|---|
anim | "anim" | CSS class for transition |
enter | "op0" | CSS class for entering elements |
leave | "op0" | CSS class/style for leaving elements |
skip | — | Element to exclude from move animation |
Returns: Flat array of [el, rect, el, rect, ...] pairs.
CSS Framework
Modular CSS in css/ directory. Key files:
| File | Utilities |
|---|---|
grid.css | .grid, .row, .col — CSS Grid |
grid-1of.css | .w1-.w12 — fraction widths |
spacing-4.css | .p1-.p4, .m1-.m4 — padding/margin |
form.css | .btn, .field, .group, .input |
anim.css | .anim — transition classes |
accessible.css | Focus, skip links |
prefers.css | @media prefers-color-scheme |
Responsive prefixes: sm-, md-, lg- (e.g., .md-w6).
Orientation: .port, .land.
Inject dynamically: xhr.css(text) or %css in templates.
Custom Bindings
Register custom bindings on El.$b:
El.$b.sticky = function(el, opts) {
// `this` is the scope, `el` is the DOM element
new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
El.cls(entry.target, "is-stuck", entry.intersectionRatio < 1)
})
}, { threshold: 1 }).observe(el)
}
Use in templates: ;sticky! or ;sticky! options.
Asset Loading
xhr(method, url, callback) // Make HTTP request
xhr.load(["file.js", "file.css"], callback) // Load files once (cached, won't reload)
xhr.css(cssText) // Inject stylesheet
xhr.ui(templateSource) // Register .ui template source
JSON handler pattern — define xhr.json to handle loaded .json files:
xhr.json = function(str, url) {
$d[url.split(".")[0]] = JSON.parse(str)
}
Built-in Elements (el/ directory)
| Element | File | Purpose |
|---|---|---|
Dialog | el/dialog.ui | Modal dialog with actions, numpad, keyboard |
Modal | el/dialog.ui | Overlay container with blur effect |
Form-* | el/form.ui | Form field elements (text, boolean, enum, list, array) |
Slider | el/Slider.ui | Range slider |
Sortable | el/sortable.ui | Drag-to-reorder list using El.flip |
Pie | el/Pie.tpl | SVG pie chart |
Segment7 | el/Segment7.tpl | 7-segment display |
Modal usage: $ui.emit("modal", title, opts, callback)
opts.actions: Array of{action, title, key}or stringsopts.code: Numpad PIN lengthopts.vibrate,opts.sound: Notification feedback
Project Structure
ui.js Core engine (templates, bindings, views, events, i18n)
shim.js ES5 polyfills for IE5.5+ (~8kB)
load.js XHR asset loader, theme detection
require.js CommonJS-like module loader
extract-lang.js Language extraction utility
el/ Reusable UI elements (.ui, .tpl)
binding/ Extra bindings (persist.js, svg.js)
css/ Modular stylesheets
bin/ CLI tools (lj-extract-lang)
Markup Syntax (;t and ;d bindings)
Inline markup (_;t) and block markup (;d) use bracket-based syntax:
Inline formatting: [op content op] — e.g., [*bold*], [/italic/], [-deleted-], [_underline_], [code], [^super^], [,sub,], [:mark:], [;span;], [~strike~], [+inserted+]
Links: [text <url>] or [<url>] — e.g., [Click here <https://example.com>]
Images: [alt !src!] or [!src!] — e.g., [sunset !photo.jpg!.right]
Embeds: [!protocol:id!] — e.g., [!youtube:dQw4w9!]. Register handlers via El.$b.d.embed:
El.$b.d.embed.youtube = function(id, text, extra) {
return "<iframe src=\"https://youtube.com/embed/" + id + "\"" + extra + "></iframe>"
}
Abbreviations: [Full Name ?ABBR?] defines, [?ABBR?] reuses — e.g., [HyperText Markup Language ?HTML?]
Time: [@2024-07-12@] or [label @2024-07-12@]
CSS classes: Append .class — e.g., [*bold*.red], [<url>.tip]
Block markup (;d only): Headings = text / == text, lists - item, ordered lists 1. item, blockquotes > text, --- for <hr>.
Common Patterns
Conditional rendering:
.panel
;if user.loggedIn
p Welcome {user.name}
List rendering:
ul
li
;each! "item", items
span {item.name}
Form with two-way binding:
form
;val data
input[name=email][type=email]
input[name=password][type=password]
button[type=submit] Submit
@click handleSubmit
Custom element with slots:
%el card
.card
h3 > %slot title
.card-body > %slot
%view home #public
card
span[slot=title] My Card
p Card body content
View with async data loading (from test/html/routed.html):
%view blog/{blogFile} #pub
main
article ;d!blogFile
%js
var blogCache = {}
$ui.param("blogFile", function(value, name, view, params) {
if (blogCache[value]) return $d[name] = blogCache[value]
var cb = view.wait()
xhr("GET", value + ".text", function(err, body) {
$d[name] = blogCache[value] = body || "Error"
cb()
}).send()
})
View with file dependencies (from test/html/routed.html):
%view about #pub
;f "contacts.json"
main
h2 About
ul
li ;each!"row", contacts
a ;txt row.title;href!row.link
Inline markup (;t binding):
dd ;t 'Contribute on [[*GitHub*] <https://github.com/litejs/>].'
Full SVG SPA (from test/html/svg-spa.html):
%js
El.cache["a"] = document.createElementNS("http://www.w3.org/2000/svg", "a")
%view main #
svg[viewBox="0 0 200 100"]
a.Menu-item ;xlink: "#home"
text[x=10][y=40] Home
svg[x=60][y=30]
%slot
%view home main
text[x=5][y=15] Main page
%start
Sponsors
Details
- Marketplace
- litejs/skills
- Category
- Community