Introducing

PUZZLE

A SPA-first framework for single-file components, reactive data, and fast static output, compiled by Go into a small browser bundle.

v0.9.0 · 23.0 kB min+gzip

What’s in the box

Everything included

Single-file components

Templates, scripts, TypeScript, and scoped styles together in readable .pzl files.

Clean app structure

Views, layouts, components, and models each have a home. Any Puzzle app reads like the last one.

Static sites supported

Prerender content to HTML with small per-page modules, or choose hybrid output for SPA takeover.

Accessible by default

Route changes move focus to the new page and announce it. Nothing to hand-roll.

Testing built in

First-class mount and app harnesses plus schema-driven fixtures and a mock adapter.

TypeScript ready

Write components in TypeScript with zero config. The compiler strips types at build time.

Translations built in

One JSON file per locale, printed with the t() function and each language’s plural rules. Apps without translations ship none of it.

Incremental rendering

List rows and static markup are cached between renders, so editing one record re-renders its row, not the whole list.

Small by default

About 23 kB gzipped, and the build leaves out any part of the framework your app never uses.

Quick start

Start in under a minute

Install the CLI and build your first app.

terminal

# install the CLI

$ npm install -g @magic-spells/puzzle

# create a new app

$ puzzle init my-app

$ cd my-app && npm install

$ npm run dev

App

Every Puzzle app has the same simple layout: views, components, models and routes, each in its own folder. Click a file to see what goes in it.

my-app

  • app

  • components

  • ui

  • layouts

  • models

  • public

  • styles

  • views

  • dist

The route table

One array: path, view, layout, and optional authentication guards, meta and child routes. Routes match in order, so the catch-all goes last.

app/routes.js
import HomeView from './views/Home.pzl';
import PostView from './views/Post.pzl';
import NotFoundView from './views/NotFound.pzl';
import DefaultLayout from './layouts/Default.pzl';

export default [
  { path: '/', view: HomeView, layout: DefaultLayout,
    meta: { title: 'Home' } },
  { path: '/posts/:id', view: PostView, layout: DefaultLayout },
  { path: '*', view: NotFoundView, layout: DefaultLayout,
    meta: { title: 'Not found' } },
];
More in Router
Read about app structure

Router

Routes, layouts and authentication guards in one table.

Child routes render at their parent’s <Slot/>, a layout stays mounted while the views inside it change, and an authentication guard can send a signed-out visitor to your login page before anything renders.

Nested routes
Children render at the parent view’s <Slot/>, and route params merge down the chain.
Authentication guards
Guard a route and every route under it is covered. Redirect signed-out visitors to your login page, or return false to stay put.
Query state
this.route.query arrives parsed, and router.replace() updates it without a new history entry.
Read the routing docs
app/routes.js
import AppShell from './layouts/AppShell.pzl';
import Home from './views/Home.pzl';
import Projects from './views/Projects.pzl';
import ProjectList from './views/ProjectList.pzl';
import Project from './views/Project.pzl';
import Settings from './views/Settings.pzl';
import Login from './views/Login.pzl';
import NotFound from './views/NotFound.pzl';
import { signedIn } from './lib/session.js';

export default [
  { path: '/', view: Home, layout: AppShell },
  { path: '/projects', view: Projects, layout: AppShell,
    children: [
      { path: '', view: ProjectList },
      { path: ':id', view: Project },
    ] },
  // Signed-out visitors go to /login, then come back here.
  { path: '/settings', view: Settings, layout: AppShell,
    guard: ({ to }) =>
      signedIn() || '/login?redirect=' + encodeURIComponent(to.path) },
  { path: '/login', view: Login, layout: AppShell },
  { path: '*', view: NotFound, layout: AppShell },
];

Datastore

One store, every view in sync.

A model declares the shape of your data and where it lives on your API. Views read from the store and write to records: anything missing is fetched before the view renders, and save() sends a change back to the API.

REST from one line
endpoint: '/api/posts' generates the calls to list, read, create, update and delete. Override only the ones your API does differently.
Views write to records
A view updates a record and every view reading it re-renders. save() syncs the change; the view never touches the API.
null means not found
A 404 becomes a committed null, never a spinner, so there are no loaded flags to keep.
One request per record
Concurrent misses share one request, and a fetched collection is read locally after that.
Read the data layer docs
app/models/post.js
import { PuzzleModel, Puzzle } from '@magic-spells/puzzle';

export default class Post extends PuzzleModel {
  static schema = {
    id: Puzzle.string().primary(),
    title: Puzzle.string().required(),
    body: Puzzle.string(),
    published: Puzzle.boolean().default(false),
  };

  // One endpoint wires the model to your API: GET /api/posts,
  // GET /api/posts/:id, POST, PUT /api/posts/:id and DELETE.
  static adapter = { endpoint: '/api/posts' };
}
app/views/Post.pzl
<puzzle-view>
  {#if post}
    <h1>{ post.title }</h1>
    <p>{ post.body }</p>
    <button @click={ publish(post) }>Publish</button>
  {:else}
    <p>Post not found.</p>
  {/if}
</puzzle-view>

<script>
import { PuzzleView } from '@magic-spells/puzzle';

export default class PostView extends PuzzleView {
  // Not in the store yet? GET /api/posts/:id first, then render.
  data(params, props) {
    return { post: this.ctx.store.findOne('post', params.id) };
  }

  events = {
    // The view changes the record, and save() syncs it: PUT /api/posts/:id.
    publish: (post) => post.update({ published: true }).save(),
  };
}
</script>

Views

Markup, script and style live together in one .pzl file. Inputs bind themselves, and lists animate when they reorder.

Songs

  • DWGlass HorizonLumen
  • EKindlingRiverbend
  • HHalcyonLumen
  • NCNeon CoastNovaline
  • BHBlue HourKoto Kudo
  • CDCassette DaysTapebloom
components/Songs.pzl
<puzzle-view>
  <div>
    <input type="search" value={ query }/>
    <ul>
      {#for track in tracks}
        <li key={ track.id } flip>{ track.title } · { track.artist }</li>
      {/for}
    </ul>
  </div>
</puzzle-view>

<script>
import { PuzzleView } from '@magic-spells/puzzle';

export default class Songs extends PuzzleView {
  data(params, props) {
    const query = this.getData()?.query ?? '';
    const q = query.toLowerCase();
    const tracks = props.tracks.filter((t) =>
      t.title.toLowerCase().includes(q));
    return { query, tracks };
  }
}
</script>
Two-way binding
value={ query } on an input writes as you type and re-runs data(). No handler to write.
FLIP
Keyed rows slide to their new places when a list is sorted or filtered.
Loading skeletons
Add a <puzzle-skeleton> to a file and it shows until the view’s data arrives.
Morph transitions
Give two elements the same morph id and one grows into the other across a navigation.
Read the template syntax

CLI

It scaffolds, serves, compiles, prerenders and checks your app, and it installs pieces and themes. Pick a command to see what it prints.

~/my-appzsh

$ puzzle init my-app

puzzle init · default template

✓ created my-app · 14 files

Next steps

$ cd my-app

$ npm install

$ npm run dev

Scaffolds a working app: routes, a layout, two views, a component and Tailwind, ready for npm install.

Output recorded from Puzzle 0.9.0 on a new app

puzzle check
Type-checks .pzl scripts and template expressions with your app’s TypeScript.
puzzle preview
Serves dist/ the way a production host would, real 404s included.
--fixtures
Seeds fake records from your model schemas. Without the flag, fixtures never reach a build.
puzzle add skills
Installs a skill that teaches your coding agent how Puzzle apps are built.
Read the CLI docs

Components

Everything in one file.

Each component is a single .pzl file: its markup, logic and styles together. Drop it into a page like an HTML tag, pass it data as attributes, and nest content inside it.

Pass anything as a prop
Strings, numbers, whole records. When a record changes, every component showing it re-renders.
Callbacks, not events
Pass a function with @select and the child calls this.props.select(). No emit, no event bus.
Children and slots
Content written inside the tag renders wherever the component puts <Children/>. Named slots place each part separately.
Read the components docs
app/components/TrackRow.pzl
<puzzle-view>
  <div class="track-row">
    <AlbumArt album={ album }/>
    <a class="track-row__text" href={ track.url }>
      <h3>{ track.title }</h3>
      <p>{ track.artist } · { album.title }</p>
    </a>
    <LikeButton track={ track }/>
  </div>
</puzzle-view>

<script>
import { PuzzleView } from '@magic-spells/puzzle';
import AlbumArt from './AlbumArt.pzl';
import LikeButton from './LikeButton.pzl';

export default class TrackRow extends PuzzleView {
  data(params, props) {
    return { track: props.track, album: props.album };
  }
}
</script>
app/views/Album.pzl
<puzzle-view>
  {#if album}
    <h1>{ album.title }</h1>
    <p>{ pluralize(album.tracks.length, 'track') }</p>
    {#for track in album.tracks}
      <TrackRow key={ track.id } track={ track } album={ album }/>
    {/for}
  {:else}
    <p>Album not found.</p>
  {/if}
</puzzle-view>

<script>
import { PuzzleView } from '@magic-spells/puzzle';
import TrackRow from '../components/TrackRow.pzl';

export default class AlbumView extends PuzzleView {
  data(params, props) {
    return { album: this.ctx.store.findOne('album', params.id) };
  }
}
</script>

Static

Set output to static and every eligible static route builds to HTML that search engines and link previews can read. Each page loads only the code it needs.

puzzle.config.js
export default {
  styles: {
    use: ['tailwindcss'],
  },
  output: 'static',
};
$ puzzle build --static
  • dist/index.htmlprerendered
  • dist/404.htmlprerendered
  • dist/_puzzle/index.js736 B gzip
  • dist/_puzzle/404.js548 B gzip
  • dist/_puzzle/chunks/…shared code
  • dist/styles.css2.8 KB gzip
Head tags
Titles, descriptions, canonical and social tags are written into each page at build time.
Search-ready
Prerendered pages can be indexed by Pagefind, which is how this site’s docs search works.
A real 404
The catch-all route renders to 404.html, served with a real 404 status.
Islands
Set prerender: false on one route and it renders in the browser instead.
Read about static builds

Animations

Motion built in.

Animations run on the Web Animations API, with no library to add. Declare them on a view or component and Puzzle plays them at the right moment, and skips them for anyone who prefers reduced motion.

In and out
Give any view or component an in and out animation. It plays as the element appears and leaves, including between routes.
Reveal on scroll
Add trigger: 'visible' and the in animation waits until the element scrolls into view.
FLIP
Put flip on a keyed row and the rows slide to their new places when the list is sorted or filtered.
Morph transitions
Import the morph engine to add morph transitions between views. Give two elements the same morph id and one flies into the other.
Read the animations docs
app/components/Toast.pzl
<puzzle-view>
  <div class="toast">{ message }</div>
</puzzle-view>

<script>
import { PuzzleView } from '@magic-spells/puzzle';

export default class Toast extends PuzzleView {
  data(params, props) {
    return { message: props.message };
  }

  animations = {
    in: {
      from: { opacity: 0, transform: 'translateY(12px)' },
      to:   { opacity: 1, transform: 'translateY(0)' },
      duration: 250,
      easing: 'ease-out',
    },
    out: {
      from: { opacity: 1 },
      to:   { opacity: 0 },
      duration: 150,
    },
  };
}
</script>
app/views/Albums.pzl
<puzzle-view>
  <ul>
    {#for album in albums}
      <li key={ album.id } flip>
        <a href={ link('/albums/' + album.id) }>
          <img src={ album.cover } alt=""
               data-puzzle-morph={ 'album-' + album.id }>
        </a>
      </li>
    {/for}
  </ul>
</puzzle-view>

<script>
import { PuzzleView } from '@magic-spells/puzzle';

export default class Albums extends PuzzleView {
  data(params, props) {
    return { albums: this.ctx.store.findMany('album') };
  }
}
</script>

Built with Puzzle

Check out our music demo app

Puzzle Sounds is a full music library and player: router, layouts, view transitions and the animation system. The songs on this page are cut from it.

Puzzle Pieces

Over 100 components available

Accessible dialogs, tables, date pickers, charts, and more, built for Puzzle. Each piece is copied into your app as readable source. It becomes your code: restyle it and rewire it. Some pieces wrap npm packages; the CLI prints the dependencies to install.

$ puzzle add piece button

Button.pzl → app/components/ui/

Explore Puzzle Pieces
button
date-picker
rating
switch
badge
Newv1.2
avatar-group
ALGHAT+2
progress
Uploading62%
kbd
Press⌘K
progress-ring
slider
meter
Memory26 GB / 32 GB
toggle-group
checkbox
input-otp
sparkline
spinner
Deploying…

FAQs

The docs go deeper on every answer here, with working examples.

More from Magic Spells: explore the ecosystem

What is a .pzl file?

A single-file component. The template markup comes first, then a <script> whose class extends PuzzleView, then an optional <style> block that can be scoped. The Go CLI compiles each file to JavaScript.

Do I need to learn another framework first?

No. Puzzle is its own framework with its own template syntax. Braces hold JavaScript-shaped expressions from a closed table: the operators, a set of string and array methods, arrow functions as arguments, and a library of display functions such as currency() and date(). {#if} and {#for} blocks and components used as capitalized tags do the rest. If you can read HTML and a JavaScript class, you can read a .pzl file.

Is Puzzle an SPA framework or a static site generator?

Both. The default build is a single-page app. Set output to static and eligible static routes are prerendered to HTML, with a small module per page for the interactive parts. Hybrid prerenders the first paint, then the full app takes over. This site is a static Puzzle build.

Can I write components in TypeScript?

Yes. Use <script lang="ts"> with no extra config and the compiler strips the types at build time. Run puzzle check to type-check your scripts and template expressions.

Can I translate a Puzzle app?

Yes. List your locales in puzzle.config.js, keep one JSON file of strings per locale, and print them with the t() function. Plural forms follow each language’s rules, and the browser fetches only the active locale. An app that configures no translations ships none of it.

How does Puzzle talk to my API?

Through the model. Pass the adapter capability from @magic-spells/puzzle/adapter to PuzzleApp, then give a model an endpoint and Puzzle generates the REST calls, or write your own functions for the verbs your API does differently. A view reads the store in data(), and anything the store is missing is fetched before the view renders.

How do I style an app?

Tailwind v4 is the supported pipeline: puzzle add tailwind wires it in. Components can also carry scoped <style> blocks, and the build folds everything into one styles.css.

How do I test a Puzzle app?

Puzzle ships its own test utilities. mountView mounts one component, createTestApp boots the real app with an in-memory router, and fixtures generate fake records from your model schemas. The mock adapter works the same in the dev server and in Vitest.

Is Puzzle free to use?

Yes. Puzzle and Puzzle Pieces are open source under the MIT license, on GitHub and npm.