html

Parse HTML and CSS, lay out and paint documents.

v1.0.0Desktopbundledimport "html";
Overview Installation Documentation Examples

Overview

HolyHTML: an HTML/CSS engine written in HolyPHP, for HolyPHP. It parses a document, computes styles, lays the boxes out, paints them onto a canvas and routes input back to the nodes. That is the whole of what a browser does for a desktop UI — without shipping a browser engine.

stdlib — embedded HTML parser CSS cascade block / inline / flex events as data

One window, one document

The window holds a single canvas. Everything inside it is a box the engine laid out; the script only reacts to the events the view hands back.

import "html";
import "ui";

$win = ui_window("Hello, HolyHTML", -1, -1, 640, 360);
$cv  = ui_add($win, 18, "", 0, 0, 640, 360);      // 18 = canvas

$view = new HtmlView($cv, 640, 360, html_theme_dark());
$view->load(
    "
Hello, HolyHTML
", ".card { padding: 16px; background-color: #252526; color: #ffffff; }"); $view->paint(); ui_run_main();

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install html

This adds the library to hphp.yaml, installs it into .hphp/packages/html/ and pins the exact version in hphp.lock:

require:
  html: "^1.0"

Use it

import "html";

html is bundled with the compiler, so import "html"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install html          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install html
Packagehtml
Version1.0.0 (follows the compiler)
Entry filehtml.hphp
Sourcepackages/lib/html ↗

Documentation

One window, one document

The window holds a single canvas. Everything inside it is a box the engine laid out; the script only reacts to the events the view hands back.

import "html";
import "ui";

$win = ui_window("Hello, HolyHTML", -1, -1, 640, 360);
$cv  = ui_add($win, 18, "", 0, 0, 640, 360);      // 18 = canvas

$view = new HtmlView($cv, 640, 360, html_theme_dark());
$view->load(
    "
Hello, HolyHTML
", ".card { padding: 16px; background-color: #252526; color: #ffffff; }"); $view->paint(); ui_run_main();

The layers

Each layer is a file, each file is testable on its own, and nothing below view knows that a canvas exists.

FileResponsibility
html/dom.hphpthe document tree and a tolerant parser (html_parse, html_set_text)
html/css.hphpselectors, specificity, the cascade (css_parse, css_add)
html/style.hphpcomputed style: colours as ints, lengths as unresolved Dim, the default stylesheet
html/layout.hphpblock, inline and flex layout, text wrapping (HtmlLayout)
html/paint.hphpthe box tree as canvas draw calls, clipping, scrolling
html/view.hphpthe facade: mount, hit-test, events, repaint (HtmlView)

Trees, selectors, and text

import "html";

$view = new HtmlView(0, 640, 360, html_theme_dark());   // 0 = headless
$view->load(
    "
one
" . "
two
", ".row { height: 24px; }"); $view->ensure(); $b = $view->find("#b"); // by id $view->set_text($b, "second"); // text is data, not a callback $rows = $view->find_all(".row"); // every match, in document order echo count($rows); // 2

The parser is deliberately forgiving: unclosed tags, stray close tags, attributes without quotes and void elements all parse. A missing </div> is not worth failing a window over.

Layout

Events are data

mouse() and key() do the bookkeeping — hover, focus, caret, scroll — and return an HtmlEvent naming the node under the pointer. The application decides what that means, which is what keeps the whole input path testable without a window.

import "html";

$view = new HtmlView(0, 400, 200, html_theme_dark());
$view->load("
open me
", ".row { height: 22px; }"); $view->ensure(); $ev = $view->mouse("click", 10, 10, 1, 0); if ($ev->node != null) { $view->add_class($ev->node, "active"); echo "clicked " . $ev->node->id; // a }

Painting, and testing the paint

Painter has a dry run: with $dry set it records every draw call as a string instead of ink. A layout can be wrong and every state test still pass; a draw list (or a pixel read back from the canvas, as examples/holyhtml_demo.hphp does) cannot.

import "html";

$view = new HtmlView(0, 320, 160, html_theme_dark());
$view->load("
x
", ".box { width: 100px; height: 40px; background-color: #007acc; }"); $view->ensure(); $paint = new Painter(0, true); $paint->paint($view->root, $view->th->bg); // second argument: the clear colour echo count($paint->log) . " draw calls";

Theming

An HtmlTheme carries the colours, the font families and the base metrics the default stylesheet uses. html_theme_dark() and html_theme_light() are the two starting points; copy one and change the fields you care about.

import "html";

$th = html_theme_light();
$th->accent = 0xd13438;
$th->fontPx = 14;

$view = new HtmlView(0, 400, 200, $th);
$view->load("
red accent
", ".card { padding: 8px; }");

Naming: the layout engine is HtmlLayout, not Layout — the ui library has a Layout of its own (the box a widget stacks in), and a HolyPHP program has one namespace. An HTML view inside a desktop window imports both.

Examples

5 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.

01Parse a page and query it with CSS selectors

A headless HtmlView (canvas handle 0, no window) parses markup into a tree of HNodes and answers real CSS selectors through find() and find_all(): classes, ids, descendants and attributes. This program reads a small shop page, prints its element outline, then pulls out the products, their prices and the links.

01-parse-and-query.hphp
<?php
import "html";

$page = "<div class='shop'>
  <h1 id='top'>Today's offers</h1>
  <ul class='products'>
    <li class='product' data-sale='yes'><span class='name'>Teapot</span> <span class='price'>24.00</span></li>
    <li class='product'><span class='name'>Mug</span> <span class='price'>8.50</span></li>
    <li class='product' data-sale='yes'><span class='name'>Kettle</span> <span class='price'>39.90</span></li>
  </ul>
  <p>See <a href='/about'>about us</a> or <a href='/contact'>contact</a>.</p>
</div>";

// Print every element, indented by its depth in the tree.
function outline(HNode $node, int $depth) {
    if ($node->isText()) {
        return;
    }
    $label = $node->tag;
    if ($node->id != "") {
        $label = $label . "#" . $node->id;
    }
    foreach ($node->classes as $class) {
        $label = $label . "." . $class;
    }
    echo str_repeat("  ", $depth) . $label;
    for ($i = 0; $i < count($node->kids); $i++) {
        outline($node->kids[$i], $depth + 1);
    }
}

// A headless view: no window, just the document and its selectors.
$view = new HtmlView(0, 800, 600, html_theme_light());
$view->load($page, "");

// The tree. The parser wraps a fragment in an implicit <html> root.
echo "heading: " . html_text_of($view->find("#top"));
outline($view->doc->root, 0);

// Descendant selectors: the name and price inside each product.
// (Typed node lists are walked with an index loop.)
$names = $view->find_all(".product .name");
$prices = $view->find_all(".product .price");
for ($i = 0; $i < count($names); $i++) {
    echo str_pad(html_text_of($names[$i]), 8) . " " . html_text_of($prices[$i]);
}

// Attribute selectors and attribute values.
echo "on sale: " . count($view->find_all("li[data-sale=yes]")) . " products";
$links = $view->find_all("a");
for ($i = 0; $i < count($links); $i++) {
    echo "link: " . $links[$i]->attr("href") . " (" . html_text_of($links[$i]) . ")";
}
Try it
hphp run 01-parse-and-query.hphp

02Lay out a page and measure the boxes

The layout engine works without a window: ensure() runs style and layout, and box_of() returns the Box the engine placed for a node, with its position and size in pixels. This page uses a flex column for header / body / footer and a flex row for sidebar / content; resizing the view shows the fixed sidebar keeping its width while flex: 1 and percentages absorb the change.

02-layout-boxes.hphp
<?php
import "html";

$html = "<div class='page'>
  <div class='header'>My App</div>
  <div class='body'>
    <div class='sidebar'>Menu</div>
    <div class='content'><div class='banner'>Half as wide as the content</div></div>
  </div>
  <div class='footer'>status</div>
</div>";

$css = "
.page    { display: flex; flex-direction: column; height: 100%; }
.header  { height: 48px; padding: 0 16px; }
.body    { display: flex; flex: 1; gap: 8px; }
.sidebar { width: 180px; flex: none; }
.content { flex: 1; padding: 12px; }
.banner  { width: 50%; height: 40px; }
.footer  { height: 24px; flex: none; }
";

// Print x, y, width and height of each interesting box.
function report(HtmlView $view, string $title) {
    echo "== $title";
    $selectors = [".header", ".sidebar", ".content", ".banner", ".footer"];
    foreach ($selectors as $selector) {
        $box = $view->box_of($view->find($selector));
        echo str_pad($selector, 10) . " x=" . $box->x . " y=" . $box->y
            . "  " . $box->w . " x " . $box->h;
    }
}

// Lay the page out at 800 x 500 ...
$view = new HtmlView(0, 800, 500, html_theme_dark());
$view->load($html, $css);
$view->ensure();
report($view, "800 x 500");

// ... and again in a bigger window. Only the flexible boxes grow.
$view->resize(1200, 700);
$view->ensure();
report($view, "1200 x 700");
Try it
hphp run 02-layout-boxes.hphp

03Render a styled page in a window

The window holds a single canvas control (ui_add type 18), and an HtmlView paints the whole page into it: backgrounds, borders, rounded corners, flex rows and wrapped text all come from the stylesheet. This is a small weather dashboard; change the CSS and run it again to restyle it.

03-render-a-page.hphp
<?php
import "html";

$width = 560;
$height = 340;

$html = "<div class='app'>
  <div class='title'>Weather in Zurich</div>
  <div class='now'>
    <div class='temp'>18 C</div>
    <div class='desc'>Partly cloudy. A light breeze from the west, dry until the evening.</div>
  </div>
  <div class='days'>
    <div class='day'><div class='name'>Tue</div><div class='hi'>21 C</div></div>
    <div class='day'><div class='name'>Wed</div><div class='hi'>17 C</div></div>
    <div class='day today'><div class='name'>Thu</div><div class='hi'>23 C</div></div>
    <div class='day'><div class='name'>Fri</div><div class='hi'>19 C</div></div>
  </div>
</div>";

$css = "
.app   { padding: 20px; }
.title { font-size: 20px; font-weight: bold; color: #ffffff; height: 32px; }
.now   { display: flex; gap: 16px; align-items: center; margin-bottom: 16px; }
.temp  { font-size: 48px; color: #4ec9b0; width: 110px; flex: none; }
.desc  { flex: 1; color: #b8b8b8; }
.days  { display: flex; gap: 10px; }
.day   { flex: 1; padding: 10px; border-radius: 8px;
         background-color: #252526; border: 1px solid #3c3c3c; }
.day.today { border: 1px solid #007acc; }
.name  { color: #8b8b8b; font-size: 11px; height: 18px; }
.hi    { color: #ffffff; font-size: 18px; height: 26px; }
";

// A window with one canvas filling it.
$window = ui_window("HolyHTML weather", -1, -1, $width, $height);
$canvas = ui_add($window, 18, "", 0, 0, $width, $height);

// Parse, style, lay out and paint the page onto the canvas.
$view = new HtmlView($canvas, $width, $height, html_theme_dark());
$view->load($html, $css);
$view->paint();

ui_run_main();
Try it
hphp run 03-render-a-page.hphp

04Clickable tabs: events are data

HolyHTML does not attach callbacks to elements. Instead the canvas events are handed to mouse(), which updates hover and focus and returns an HtmlEvent naming the node under the pointer - the program decides what a click means. Here a click on a tab moves the active class with add_class() / remove_class() and swaps the panel text with set_text(). Hover colours come from :hover in the CSS alone.

04-clickable-tabs.hphp
<?php
import "html";

$html = "<div class='tabs'>
  <div class='tab active' id='home'>Home</div>
  <div class='tab' id='files'>Files</div>
  <div class='tab' id='help'>Help</div>
</div>
<div class='panel' id='panel'>Welcome home.</div>";

$css = "
.tabs { display: flex; background-color: #252526; height: 34px; }
.tab  { padding: 0 18px; height: 34px; color: #969696; border-bottom: 2px solid #252526; }
.tab:hover  { color: #ffffff; }
.tab.active { color: #ffffff; border-bottom: 2px solid #007acc; }
.panel { padding: 20px; color: #cccccc; }
";

$texts = ["home" => "Welcome home.", "files" => "No files yet.", "help" => "Click a tab to switch."];

$window = ui_window("Tabs", -1, -1, 480, 240);
$canvas = ui_add($window, 18, "", 0, 0, 480, 240);
$view = new HtmlView($canvas, 480, 240, html_theme_dark());
$view->load($html, $css);

// Pointer moved (canvas event 8): repaint only if the hover changed.
ui_on($canvas, 8, function($x, $y, $button) use ($view) {
    $event = $view->mouse("move", $x, $y, 0, 0);
    if ($event->state) {
        $view->paint();
    }
});

// Button released (canvas event 7): find the tab that was clicked.
ui_on($canvas, 7, function($x, $y, $button) use ($view, $texts) {
    $event = $view->mouse("up", $x, $y, $button, 0);
    $node = $event->node;
    while ($node != null && !$node->hasClass("tab")) {
        $node = $node->up;
    }
    if ($node == null) {
        return;
    }

    // Move the "active" class to the clicked tab and update the panel.
    $view->remove_class($view->find(".tab.active"), "active");
    $view->add_class($node, "active");
    $view->set_text($view->find("#panel"), $texts[$node->id]);
    $view->paint();
});

$view->paint();
ui_run_main();
Try it
hphp run 04-clickable-tabs.hphp

05Testing a UI without a window

Because events are data, a whole interaction can be driven headless: lay the page out, ask box_of() where an element is, feed mouse() a click at that spot and assert on the result. draw_list() records what would be painted as plain strings, so even the paint step can be checked. This is how you would unit-test a checklist widget in CI.

05-test-without-a-window.hphp
<?php
import "html";

$html = "<div class='list'>
  <div class='item' id='milk'>Buy milk</div>
  <div class='item' id='bread'>Buy bread</div>
  <div class='item' id='eggs'>Buy eggs</div>
</div>";
$css = ".item { height: 24px; padding: 0 8px; } .item.done { color: #6a9955; }";

$view = new HtmlView(0, 300, 120, html_theme_dark());
$view->load($html, $css);
$view->ensure();

// The application logic under test: a click toggles "done" on an item.
function click_item(HtmlView $view, int $x, int $y) {
    $node = $view->mouse("up", $x, $y, 1, 0)->node;
    while ($node != null && !$node->hasClass("item")) {
        $node = $node->up;
    }
    if ($node == null) {
        return;
    }
    if ($node->hasClass("done")) {
        $view->remove_class($node, "done");
    } else {
        $view->add_class($node, "done");
    }
}

// Click the middle of an element, wherever the layout put it.
function click_on(HtmlView $view, string $selector) {
    $box = $view->box_of($view->find($selector));
    click_item($view, $box->x + intdiv($box->w, 2), $box->y + intdiv($box->h, 2));
}

function expect(string $what, bool $ok) {
    echo ($ok ? "PASS  " : "FAIL  ") . $what;
}

// The tests.
click_on($view, "#bread");
expect("clicking an item marks it done", $view->find("#bread")->hasClass("done"));
expect("other items are untouched", !$view->find("#milk")->hasClass("done"));

click_on($view, "#bread");
expect("a second click un-marks it", !$view->find("#bread")->hasClass("done"));

click_on($view, "#milk");
click_on($view, "#eggs");
expect("two items done", count($view->find_all(".item.done")) == 2);

$commands = $view->draw_list();
expect("the frame paints something (" . count($commands) . " draw calls)", count($commands) > 0);
Try it
hphp run 05-test-without-a-window.hphp