Hasty

A SwiftUI-inspired static site generator for Dart. Compose HTML pages using typed, composable functions — no raw strings, no templates, no fuss.

Installation

Add to your pubspec.yaml:

dependencies:
  hasty: ^0.0.4

Then run:

dart pub get

Quick Start

import 'package:hasty/hasty.dart';

void main() async {
  final page = container(
    maxWidth: 800,
    padding: 24,
    child: vStack(
      id: 'app',
      style: const Style(fontFamily: 'sans-serif', gap: 16),
      children: [
        h1('Hello, Hasty!', style: const Style(color: Colors.indigo)),
        p('A page built entirely in Dart.'),
      ],
    ),
  );

  await emit(page, title: 'Hello Hasty'); // writes build/index.html
}

Concepts

Nodes & Rich Inline Content

Everything is a Node — a lightweight representation of an HTML element. Tag functions like div, h1, and p return nodes that you compose into a tree.

Text elements (p, li, span, strong, em, h1–h6, button) accept plain strings, a single Node, or a List<Node> mixed with txt(...):

p([
  txt('Built in '),
  strong('pure Dart'),
  txt(' — visit '),
  a(href: 'https://dart.dev', content: 'dart.dev'),
  txt(' to learn more.'),
])

Layout

Hasty provides SwiftUI / Flutter-style layout primitives that map cleanly to CSS Flexbox and CSS Grid:

grid(
  minChildWidth: 240, // responsive auto-fit columns — no media query needed!
  gap: 16,
  children: [
    card(children: [h3('Fast'), p('Zero runtime overhead.')]),
    card(children: [h3('Typed'), p('Catch mistakes at compile time.')]),
    card(children: [h3('Composable'), p('Everything is just a Dart function.')]),
  ],
)
Function HTML / CSS output Description
vStack <div> (flex column) Vertical stack
hStack <div> (flex row) Horizontal stack
zStack <div> (relative) Layered stack (children use Position.absolute)
grid <div> (CSS grid) Fixed columns or responsive minChildWidth grid
wrap <div> (flex-wrap row) Wraps chips/buttons onto multiple lines automatically
container <div> (margin: 0 auto) Horizontally centered max-width wrapper
expanded <div> (flex: n) Expands proportionally inside hStack / vStack
spacer <div> (flex: 1 or fixed px) Flexible or fixed-size space (spacer(size: 24))
padding <div> Wraps a child with configurable padding
center <div> (flex center) Centers a child horizontally and vertically
divider <div role="separator"> Horizontal or vertical (Axis.vertical) separator
fragment Fragment (no wrapper tag) Groups sibling nodes without extra DOM wrappers

Both hStack and vStack accept MainAxisAlignment and CrossAxisAlignment to control child alignment.

Styles & StyleSheets

Use the Style class for type-safe inline CSS — and compose reusable styles with .merge(...) or +:

const baseCard = Style(padding: 16, borderRadius: 8, boxShadow: Shadows.sm);
final highlighted = baseCard + Style(border: '1px solid ${Colors.indigo}');

Colors — Colors.black, Colors.white, Colors.offWhite, Colors.red, Colors.rose, Colors.orange, Colors.amber, Colors.yellow, Colors.green, Colors.emerald, Colors.teal, Colors.cyan, Colors.blue, Colors.indigo, Colors.purple, Colors.pink, Colors.gray, Colors.lightGray, Colors.darkGray, Colors.slate, Colors.transparent

Custom & alpha colors: Color.hex('#ff6600'), Color.rgb(255, 102, 0), Color.rgba(255, 102, 0, 0.5), Color.hsl(210, 80, 50), Color.cssVar('accent'), and Colors.indigo.withOpacity(0.15).

Shadows — Shadows.none, Shadows.sm, Shadows.md, Shadows.lg, Shadows.xl, Shadows.inner

FontWeight — thin, light, normal, medium, semibold, bold, extrabold

Enums — FontStyle, TextAlign, TextDecoration, TextTransform, WhiteSpace, Position, Display, Float, FlexWrap, AlignSelf, Cursor, BorderStyle, BoxSizing, ObjectFit

Pseudo-Selectors & Responsive CSS (StyleSheet)

For :hover states, :root CSS variables, box-sizing resets, and @media breakpoints, build a typed StyleSheet:

final styles = StyleSheet(
  includeReset: true,
  variables: {'accent': '#6366f1'},
  rules: [
    const CssRule('a:hover', Style(opacity: 0.85, cursor: Cursor.pointer)),
  ],
  mediaQueries: [
    const MediaQuery(
      maxWidth: 768,
      rules: [CssRule('.sidebar', Style(display: Display.none))],
    ),
  ],
);

Pass styleSheet: styles to emit(...) / renderDocument(...), or write a standalone CSS file with emitCss(styles).

Built-In Markdown

Convert Markdown prose directly into safe, composable Hasty Nodes — zero extra dependencies required:

final post = markdown('''
# Release Notes

Write **bold**, _italic_, `inline code`, and [links](https://dart.dev).

```dart
void main() => print('Hello!');

''');


Headings automatically receive URL-friendly `id` slugs, and raw HTML in untrusted Markdown is escaped by default.

### Tags

#### Headings & Prose
`h1`–`h6` `text` `p` `span` `strong` `em` `small` `mark` `del` `ins` `sub` `sup` `code` `pre` `kbd` `abbr` `time` `blockquote` `txt` `comment`

#### Containers & Disclosure
`div` `section` `article` `aside` `main_` `header` `footer` `nav` `figure` `figcaption` `details` `summary` `dialog`

#### Lists & Description Lists
`ul` `ol` `li` `dl` `dt` `dd`

#### Links & Buttons
```dart
a(href: 'https://example.com', content: 'Visit', target: '_blank')

// pre-styled variants: primary, secondary, floating, outline, danger, ghost
button('Save', variant: ButtonVariant.primary)
button('Cancel', variant: ButtonVariant.outline)
button('Delete', variant: ButtonVariant.danger, data: {'confirm': 'true'})

Media & Head

img video audio source picture iframe progress meter hr br meta linkTag script

Forms & Tables

Full support for form, input, textarea, select, option, optgroup, fieldset, legend, label, and table, caption, thead, tbody, tfoot, tr, th (Scope), td, colgroup, col.

Raw HTML

For trusted content only — bypasses escaping: raw('<svg>...</svg>').

Components

High-level pre-styled components for common UI patterns:

  • navBar / navLink — horizontal navigation bar and link items
  • breadcrumb / BreadcrumbItem — accessible <nav aria-label="Breadcrumb"> trail
  • heroSection — headline, subtitle, optional eyebrow badge, and CTA actions
  • card — padded surface container with configurable backgroundColor and style
  • badge — pill chip with BadgeVariant.solid, subtle, and outline
  • statCard — compound metric card with icon, bold value, and caption
  • alert — contextual banner (AlertVariant.info, success, warning, error)
  • accordion / accordionItem — zero-JS collapsible panels via <details> / <summary>
  • avatar — circular image or initials badge
  • progressBar — accessible horizontal progress track with optional label & percentage
  • codeBlock — dark terminal/code card with optional filename or language header

Emitting Single Pages & Multi-Page Sites

// Single page -> build/index.html
await emit(
  page,
  title: 'My Site',
  description: 'Built with Hasty in Dart.',
  favicon: '/favicon.ico',
  styleSheet: styles,
  minify: false,
);

// Render HTML fragment or full <!DOCTYPE html> string in memory
final fragment = renderHtml(page);
final document = renderDocument(page, title: 'My Site');

// Multi-page static site with shared layout, CSS, pretty URLs, and sitemap.xml
await emitSite(
  [
    SitePage(path: 'index', title: 'Home', body: homeView()),
    SitePage(path: 'blog/hello', title: 'Hello', body: markdown(postMd)),
  ],
  outputDir: 'build',
  sharedStyleSheet: styles,
  layout: (content, page) => container(children: [siteNav(), content]),
  prettyUrls: true,
  generateSitemap: true,
  baseUrl: 'https://example.com',
);

CLI Argument Parsing

Hasty includes a lightweight typed argument parser with aliases, defaults, and help formatting:

import 'dart:io';
import 'package:hasty/hasty.dart';

void main(List<String> args) async {
  final parser = Parser()
    ..register(
      '--output',
      'Output directory',
      type: String,
      defaultsTo: 'build',
      aliases: ['-o', 'output'],
    )
    ..register('--minify', 'Minify HTML and CSS', aliases: ['-m']);

  try {
    parser.parse(args);
  } catch (e) {
    print(e);
    parser.printFlags();
    exit(1);
  }

  await emit(
    page,
    outputDir: parser.option<String>('--output')!,
    minify: parser.flag('--minify'),
  );
}

CLI Executable

Compile the hasty CLI runner into a standalone binary (or run via dart pub global activate):

dart compile exe bin/hasty.dart -o bin/hasty.exe

# Build a target site/page script (forwarding any flags to the target)
./bin/hasty.exe example/hasty_example.dart
./bin/hasty.exe example/hasty_example.dart --output dist --minify

# Preview the generated static directory over a local HTTP server
./bin/hasty.exe serve build --port 8080

Full Example

See example/hasty_example.dart for a complete multi-page showcase demonstrating layout grids, StyleSheet, markdown, high-level components, forms, tables, and CLI argument parsing.

Libraries

hasty