Components
The anatomy of a .pzl file (template, script, styles) and the view lifecycle.
Everything you render in Puzzle is a .pzl file. A .pzl bundles a template, its logic, and optional styles into one component you can read top to bottom. There are three flavors, distinguished only by where they live and how you use them:
- Views (
app/views/*.pzl): page components a route renders. - Layouts (
app/layouts/*.pzl): shells that wrap a view via<Slot/>. - Components (
app/components/**/*.pzl): reusable UI used inside other files.
They're all the same class under the hood: every one extends PuzzleView.
File anatomy
A .pzl file can contain up to four top-level blocks:
<puzzle-view>
<div class="my-component">
<!-- markup + template directives -->
</div>
</puzzle-view>
<puzzle-skeleton>
<div><!-- optional loading placeholder --></div>
</puzzle-skeleton>
<script>
import { PuzzleView } from '@magic-spells/puzzle';
export default class MyComponent extends PuzzleView {
// component logic
}
</script>
<style>
/* optional CSS */
</style>Only <puzzle-view> is required.
<puzzle-view>is the template root. It holds normal HTML plus Puzzle directives ({ }interpolation,{#if},{#for},@event, and so on). See Templates for the full grammar.<puzzle-skeleton>is an optional loading placeholder shown while the firstdata()is pending. Covered below.<script>holds a class extendingPuzzleView. Imports, including other.pzlfiles, live here.<style>is optional CSS. It's global by default; add a barescopedattribute to confine it to this component.
Views and layouts vs. components
Views and layouts compile to a real <puzzle-view> DOM element that carries the tag's attributes. Reusable components render inline, with no wrapper element, so nested components never stack extra wrappers.
That has one practical consequence: in a reusable component, <puzzle-view> is only a template delimiter. It must carry no attributes (that's a compile error) and wrap a single root element. Put your class, id, and data attributes on that root element instead:
<!-- components/Button.pzl -->
<puzzle-view>
<button class="btn btn--{ variant }" type={ type } disabled={ disabled } @click={ handleClick }>
<Children/>
</button>
</puzzle-view>
<script>
import { PuzzleView } from '@magic-spells/puzzle';
export default class Button extends PuzzleView {
data(params, props) {
return { variant: props.variant ?? 'primary', type: props.type ?? 'button', disabled: props.disabled ?? false };
}
events = {
handleClick: (event) => this.props.press?.(event),
};
}
</script>A component doesn't need a <script> at all. Without one, its template reads its props by name, so a presentational component can be template-only:
<!-- components/Chip.pzl: no <script> -->
<puzzle-view>
<span class="chip chip--{ tone }">{ label }</span>
</puzzle-view>
<!-- call site -->
<Chip tone="warn" label="Draft" />The <script> block
The contents of <script> must parse as standard JavaScript, with no custom dialect. The compiler hands the block to esbuild untouched, so your editor, ESLint, and Prettier all work with zero special tooling. Two rules follow from that:
eventsandanimationsare class fields (events = { ... };), not object-literal members.- There are no commas between class members.
Because esbuild owns module resolution, import config from './config.json' just works. For TypeScript, write <script lang="ts">: types are stripped at build time, and puzzle check type-checks scripts and template expressions with the TypeScript compiler your app installs (see CLI).
Importing with the @/ alias
Imports may be relative, or use the built-in @/ alias for your app/ directory. @/components/Icon.pzl resolves to the same file from any depth, which beats counting ../ segments once your views live in nested folders.
// from app/views/docs/components/ButtonDoc.pzl import Button from '../../../components/ui/Button.pzl'; // the same import, from any file at any depth import Button from '@/components/ui/Button.pzl';
- Always on. There's no opt-in and no config key;
app/is already the fixed source root. - It applies wherever esbuild resolves a specifier:
<script>blocks, your app entry, routes, models, and JSON imports, in the dev server, the normal build, and the prerender pass of a static build. - Relative paths still work. The alias is additive, not a replacement.
- Scoped packages are untouched.
@magic-spells/puzzleand every other scoped package resolve normally. - Module resolution only. It doesn't apply to
{#svg 'icons/heart.svg'}asset paths or to CSS imports, which use different resolvers.
Your editor needs a matching path mapping to follow @/ imports; see Installation.
Class members
The class you export extends PuzzleView and can define:
| Member | Purpose |
|---|---|
data(params, props) | Returns the component's model. May be async. Runs on mount and whenever its inputs change. |
events | Class field: an object of arrow-function handlers. See Events. |
animations | Class field: declarative enter/leave animations. See Animations. |
| Lifecycle hooks | created, mounted, beforeUpdate, afterUpdate, destroyed, plus the show/hide hooks around animations. |
| Your own methods | Ordinary helpers called from handlers or lifecycle hooks. |
PuzzleView owns some member names, so don't reuse them for helpers: getData, setData, refresh, memo, ctx, refs, element, loaded, params, props, route, mount, destroy, and the compiler's own double-underscore names (__h, __lists, __c, and their siblings). Binding one of the module-level compiler names, such as __l or __L0, in a <script> is a compile error.
The data() method
data(params, props) is the heart of a component. It returns a plain object that becomes the component's model: the data the template reads.
It re-runs automatically when:
- The component mounts (the initial call).
- Props passed from a parent change.
- Route params or the query string change (for views).
- Store data queried inside it changes.
data(params, props) {
const todos = this.ctx.store.findMany('todo'); // auto-subscribes to 'todo' changes
return {
todos,
remaining: todos.filter((t) => !t.completed).length,
};
}Any store query made inside data() auto-subscribes the component: when those records change, data() re-runs and the view re-renders. When the app has server sync enabled, the same queries also fetch whatever the store is missing, and the view commits once every read has settled; see Data & Models. Either way, data() can run several times per navigation, so keep it a pure derivation with no side effects.
data() may be async. A routed view's navigation waits for it before the new view commits, unless the view declares a skeleton.
Local state: setData and refresh
this.setData(key, value) (or setData(objectMap)) updates local component state and re-renders, but it does not re-run data(). That keeps small updates cheap.
The catch: a value derived inside data() won't recompute from a setData alone. When a filtered list or computed field depends on local state, set the input and then call this.refresh() to re-run data():
created() {
this.setData({ activeTag: null });
}
data(params, props) {
const { activeTag } = this.getData();
const posts = this.ctx.store.findMany('post');
return {
activeTag,
posts: activeTag ? posts.filter((p) => p.tags.includes(activeTag)) : posts,
};
}
events = {
setTag: (tag) => {
this.setData('activeTag', tag); // local UI state; doesn't re-run data()
this.refresh(); // re-run data() so the filtered list updates
},
};State lives in two layers. Each object returned by data() replaces the model layer wholesale, so an omitted key disappears unless the local layer holds it. setData writes that persistent local layer. A later model commit wins for keys it returns; a later local write wins until the next model commit. A component that mixes local state with store data should read its local values back inside data() (via this.getData()), as above. A two-way bound input on a bare key does the setData plus refresh() for you.
Runtime context: this.ctx
Every view and component gets a runtime context on this.ctx:
this.ctx.store: the data store for querying and mutating records. Read it throughthis.ctxindata(); that per-view handle is what subscribes the view and, with server sync, fetches.this.ctx.router: the router, for navigation (this.ctx.router.push('/home')).this.ctx.formatters: the template function library, the standard functions plus the ones your app registers (rarely needed directly).this.ctx.i18n: present only when the app configures translations.this.ctx.idle(): the app's idle method, which resolvestrueonce the app is quiet andfalseon timeout.
That's the context surface, intentionally minimal.
Lifecycle hooks
Hooks run in this order, each with this bound to the instance:
created(): once, after construction but before the first render. Seed local state here withsetData.mounted(): after the DOM is first rendered. Do browser-only setup here: attachwindowlisteners, start intervals, reach into the DOM, boot a third-party library.beforeUpdate()/afterUpdate(): around subsequent re-renders.destroyed(): when the instance is torn down. Clean up here: removewindowlisteners and clear intervals you started inmounted(). Components really do unmount on navigation, so a leaked listener is a real bug.
export default class Clock extends PuzzleView {
created() {
this.setData({ now: Date.now() });
}
mounted() {
this._timer = setInterval(() => {
this.setData('now', Date.now());
}, 1000);
}
destroyed() {
clearInterval(this._timer);
}
data(params, props) {
return { now: this.getData().now };
}
}Props
Parents pass props as tag attributes; braces make them dynamic, and any template expression works there, function calls included:
<UserProfile userId={ selectedUserId } />
<Card title={ truncate(post.title, 60) } />Props are reactive: when a parent changes a prop, the child's data(params, props) re-runs with the new value. Props are compared shallowly, so string, number, and boolean props just work, and callback props that don't capture render data are cached, so they compare equal across parent renders.
Record props refresh their child. Store records mutate in place, so the reference never changes; instead each record carries a revision, and <TodoItem todo={ todo }/> re-renders when todo.update(…) or any other store path changes that record. Assigning a field directly (todo.title = 'x') notifies nothing, so it never refreshes the child. A related record's fields or a computed getter's inputs aren't covered by that revision, so when a child shows those, pass the id and re-query in the child's own data().
A plain object or array prop compares by reference: if data() builds a fresh object every run, the child sees a "changed" prop on every unrelated update. Keep the reference stable with this.memo(key, deps, factory):
data(params, props) {
const { effect = 'carousel' } = this.getData();
return {
// Same object reference until `effect` changes.
carouselOptions: this.memo('opts', [effect], () => ({
effect,
loop: true,
slidesPerView: 2,
})),
};
}deps is an array compared positionally; when any entry differs, the factory runs once and the result is cached. It's purely about identity, with no reactivity of its own.
Slots
Composition markers are capitalized, and written either self-closing or paired with a body. A layout marks the router outlet with <Slot/>, and a reusable component marks where its call site's content lands with <Children/>:
<!-- layouts/Default.pzl --> <puzzle-view class="shell"> <header>…</header> <main><Slot/></main> <footer>…</footer> </puzzle-view> <!-- components/Button.pzl --> <puzzle-view> <button class="btn"><Children/></button> </puzzle-view>
Children written at a component's call site (<Button>Save</Button>) render at its <Children/>. For multi-region components, declare named slots with <Slot name="…"/> and target them from the call site with a static slot="…" attribute on a direct child. A paired marker's body is fallback content, shown only while nothing fills the position. Content counts only when it renders something, so a call-site {#if} that's false or a {#for} over an empty list shows the fallback, which makes it a ready-made empty state:
<!-- components/Card.pzl -->
<puzzle-view>
<div class="card">
<header><Slot name="header"><h2>Untitled</h2></Slot></header>
<div class="body"><Children/></div>
<footer><Slot name="footer"><button class="btn">OK</button></Slot></footer>
</div>
</puzzle-view>
<!-- call site: header is filled, footer falls back to the OK button -->
<Card>
<h2 slot="header">{ post.title }</h2>
<p>{ post.excerpt }</p>
</Card>When a component needs to stamp caller-supplied markup once per item, reach for a snippet. Templates has the full rules, including when a position counts as filled.
Styles
<style> blocks are emitted as global CSS by default, applied as-is. Add a bare scoped attribute and the block is confined to this component's rendered subtree:
<puzzle-view><article class="card"><h2>{ title }</h2></article></puzzle-view>
<style scoped>
h2 { color: rebeccapurple; }
</style>scoped is the only attribute <style> accepts, and there's at most one <style> block per file. Scoping uses native CSS @scope; scoped rules still cascade into nested child components like ordinary CSS.
Skeleton loading states
A view's first data() can be pending: it's async, or its store reads are still fetching from the server. Declare a <puzzle-skeleton> section, a sibling of <puzzle-view> rather than a tag inside it, and its content renders until the first data() commits, then swaps for the real template. There's no loading flag to manage:
<puzzle-view class="post-list">
{#for post in posts}
<PostCard post={ post } />
{/for}
</puzzle-view>
<puzzle-skeleton min-duration="300">
{#for 1...3}
<div class="card animate-pulse">
<div class="bg-skeleton h-5 w-full mb-2"></div>
<div class="bg-skeleton h-4 w-4/5"></div>
</div>
{/for}
</puzzle-skeleton>
<script>
import { PuzzleView } from '@magic-spells/puzzle';
import PostCard from '@/components/PostCard.pzl';
export default class PostList extends PuzzleView {
data(params, props) {
// With server sync, a cold store fetches here; the skeleton covers it.
return { posts: this.ctx.store.findMany('post') };
}
}
</script>Notes:
- At most one skeleton per file. Its only optional attribute is
min-duration(milliseconds, a static number), a floor on how long the skeleton stays up once shown, so fast loads don't flash the placeholder for a few frames. - The skeleton body supports the full template grammar, but only
created()-seeded state is readable during it, sincedata()hasn't committed yet. In a component, the skeleton needs a single plain root element. - Every round of server fetching counts as one load, so the skeleton shows once and holds until the view commits. A
data()that resolves right away never shows it, and later refreshes keep the current content on screen: it's a first-load affordance, not a spinner. - A routed view with a skeleton doesn't hold the navigation for its data: the view mounts showing its skeleton and the real content patches in.
Error handling
Two optional app-config keys cover failures the framework contains: a view or component whose data(), render, or mount throws, and failed navigations. onError hears every one, and errorView names one ordinary .pzl view that replaces a failed view or component in place:
// app.js
import AppErrorView from '@/views/AppError.pzl';
const app = new PuzzleApp({
target: '#app',
routes,
errorView: AppErrorView,
onError(error, info) {
reportToMonitoring(error, info.phase); // your own error reporting
},
});<!-- views/AppError.pzl -->
<puzzle-view class="error-panel">
<p>Something went wrong: { message }</p>
<button @click={ tryAgain }>Try again</button>
</puzzle-view>
<script>
import { PuzzleView } from '@magic-spells/puzzle';
export default class AppError extends PuzzleView {
data(params, props) {
return { message: props.error?.message ?? 'Unknown error' };
}
events = {
tryAgain: () => this.props.retry(),
};
}
</script>onError(error, info)receivesinfo = { phase, view, route }, with phases such asmount,refresh,navigation, andbind. Without a hook, failures log to the console.- The error view is a fresh instance mounted at the failed position; the parent, siblings, and surrounding layout keep their state. It receives the props
error,info, andretry. retry()rebuilds through the position's normal owner: a same-location navigation for a routed view, the parent's refresh for a component. Nothing retries automatically.- Event handlers are not caught; browser events sit outside the boundary, so they throw as ordinary JavaScript. A template function or method that throws during render fails that view like any other render throw, and the error view takes over. There is no per-view error hook: write error UI as normal template markup in the error view.
Next
- Templates: the full template grammar.
- Events & Binding: handlers, forms, and callbacks.
- Data & Models: the store your
data()reads from.