### Directive Setup (setup) Source: https://mizu.sh/coverage/internal/engine/directive.ts.html The `setup` callback is executed during `Renderer.render()` before any `execute` calls. It can update the rendering state and eligibility. ```APIDOC ## Directive Setup (setup) ### Description The `setup` callback is executed during `Renderer.render()` before any `Directive.execute()` calls. A partial object can be returned to update the rendering `State`, and the eligibility. If `false` is returned, the entire rendering process for this node is halted. > [!IMPORTANT] > This method is executed regardless of the directive's presence on the node. ### Request Example ```ts const foo = { name: "*foo", phase: Phase.UNKNOWN, async setup(renderer, element, { cache, context, state }) { if ((!renderer.isHtmlElement(element)) || (element.hasAttribute("no-render"))) { return false as const } }, } as const satisfies Directive ``` ``` -------------------------------- ### Server-side Setup Source: https://mizu.sh/ Instructions for setting up Mizu.js in a server environment. ```APIDOC ## Server-side Setup Install Mizu.js locally to set up in a server environment. ### Usage Notes - Rendering is implicit; the `*mizu` attribute is not required. - Reactivity is disabled; context changes do not trigger re-renders. ``` -------------------------------- ### Setup a Directive Source: https://mizu.sh/coverage/internal/engine/directive.ts.html The setup callback runs before execution and can halt rendering by returning false. ```typescript const foo = { name: "*foo", phase: Phase.UNKNOWN, async setup(renderer, element, { cache, context, state }) { if ((!renderer.isHtmlElement(element)) || (element.hasAttribute("no-render"))) { return false as const } }, } as const satisfies Directive ``` -------------------------------- ### Client-side Setup Source: https://mizu.sh/ Instructions for setting up Mizu.js in a browser environment using IIFE or ESM. ```APIDOC ## Client-side Setup ### IIFE (.js) This setup automatically starts rendering the page once the script is loaded. ```html ``` ### ESM (.mjs) This setup requires manual import and start of Mizu.js, allowing customization. ```html ``` ### Usage Notes - Rendering is explicit, requiring the `*mizu` attribute. - Reactivity is enabled, triggering re-renders on context changes. ``` -------------------------------- ### Installation Commands Source: https://mizu.sh/ Commands to add the Mizu render package to different runtimes. ```bash deno add jsr:@mizu/render ``` ```bash npx jsr add @mizu/render ``` ```bash bunx jsr add @mizu/render ``` -------------------------------- ### Client.render Source: https://mizu.sh/ Starts the rendering process for subtrees marked with the *mizu attribute. ```APIDOC ## Client.render(element: T, options?: ClientRenderOptions) ### Description Starts rendering all subtrees marked with the *mizu attribute. ### Parameters #### Request Body - **element** (T) - Required - The root element to start rendering from. - **options** (ClientRenderOptions) - Optional - Rendering configuration options. ### Response #### Success Response (200) - **Promise** - Returns a promise that resolves to the rendered element. ### Request Example const mizu = new Client({ context: { foo: "bar" } }) await mizu.render() ``` -------------------------------- ### Add Mizu.js to Deno Project Source: https://mizu.sh/ Install Mizu.js using the Deno CLI for project integration. ```bash deno add jsr:@mizu/render ``` -------------------------------- ### Client-side Integration Source: https://mizu.sh/ Examples of using Mizu on the client side via IIFE or ESM modules. ```html IIFE
{{ foo }}
``` ```html ESM
{{ foo }}
``` -------------------------------- ### Mizu Server Generate Method Example Source: https://mizu.sh/coverage/render/server/server.ts.html Demonstrates how to use the `generate` method with different source types: strings, glob patterns, callbacks, and URLs. Includes options for rendering and file system operations. ```typescript const mizu = new Server({ directives: ["@mizu/test"], generate: { output: "/fake/output" } }) await mizu.generate( [ // Copy content from strings [ "

foo

", "string.html" ], [ "

", "string_render.html", { render: { context: { foo: "bar" } } } ], // Copy content from local files [ "**\/*", "public", { directory: "/fake/static" } ], [ "*.html", "public", { directory: "/fake/partials", render: { context: { foo: "bar " } } } ], // Copy content from callback return [ () => JSON.stringify({ foo: "bar" }), "callback.json" ], [ () => `

`, "callback.html", { render: { context: { foo: "bar" } } } ], // Copy content from URL [ new URL(`data:text/html,

foobar

`), "url.html" ], [ new URL(`data:text/html,

`), "url_render.html", { render: { context: { foo: "bar" } } } ], ], // No-op: do not actually write files and directories { fs: { readdir: () => Promise.resolve([] as string[]), mkdir: () => null as any, write: () => null as any } }, ) ``` -------------------------------- ### Add Mizu.js to Bun Project Source: https://mizu.sh/ Install Mizu.js using `bunx` for Bun projects via the JSR npm compatibility layer. ```bash # Bun bunx jsr add @mizu/render ``` -------------------------------- ### Import Mizu.js in Node.js/Bun Source: https://mizu.sh/ Import the server module after installation for use in Node.js or Bun projects. ```typescript import Mizu from "@mizu/render/server" await Mizu.render(`
`, { context: { foo: "🌊 Yaa, mizu!" } }) ``` -------------------------------- ### Include Mizu.js Client-side (ESM) Source: https://mizu.sh/ Set up Mizu.js client-side using an EcmaScript Module (ESM). This requires manual import and starting the rendering process, allowing for customization of the initial context. ```javascript import Mizu from "https://mizu.sh/client.mjs" await Mizu.render(document.body, { context: { foo: "🌊 Yaa, mizu!" } }) ``` -------------------------------- ### Add Mizu.js to Node.js Project Source: https://mizu.sh/ Install Mizu.js using `npx` for Node.js projects via the JSR npm compatibility layer. ```bash # NodeJS npx jsr add @mizu/render ``` -------------------------------- ### Retrieve and use directive-specific cache Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Demonstrates how to initialize and access a WeakSet cache within a directive's setup phase. ```ts import { Window } from "@mizu/internal/vdom" const directive = { name: "*foo", phase: Phase.TESTING, init(renderer) { if (!renderer.cache(this.name)) { renderer.cache>(this.name, new WeakSet()) } }, setup(renderer, element, { cache }) { console.assert(cache instanceof WeakSet) console.assert(renderer.cache(directive.name) instanceof WeakSet) cache.add(element) } } as const satisfies Directive<{ Cache: WeakSet }> const renderer = await new Renderer(new Window(), { directives: [directive] }).ready const element = renderer.createElement("div", { attributes: { "*foo": "" } }) await renderer.render(element) console.assert(renderer.cache>(directive.name).has(element)) ``` -------------------------------- ### Attribute Parsing Examples Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Demonstrates parsing attributes with and without modifiers, and with a custom prefix. Ensure the 'attribute' variable is defined in your scope. ```javascript const typings = { type: Boolean, modifiers: { bar: { type: String } } } parsed = renderer.parseAttribute(attribute, typings, { modifiers: true }) console.assert(parsed.name === "*foo") console.assert(parsed.value === true) console.assert(parsed.modifiers.bar === "baz") parsed = renderer.parseAttribute(attribute, typings, { modifiers: false, prefix: "*" }) console.assert(parsed.name === "foo") console.assert(parsed.value === true) console.assert(!("modifiers" in parsed)) ``` -------------------------------- ### Attribute Parsing Example Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Illustrates parsing a complex attribute string with a prefix, tag, and modifier. This example is useful for testing or demonstrating the attribute parsing logic. ```typescript import { Window } from "@mizu/internal/vdom" const renderer = await new Renderer(new Window()).ready const element = renderer.createElement("div", { attributes: { "*foo.bar[baz]": "true" } }) const [attribute] = Array.from(element.attributes) let parsed ``` -------------------------------- ### GET /internal Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Generates or retrieves internal identifiers. ```APIDOC ## GET /internal ### Description Generates a prefixed internal identifier to avoid naming collisions with user-defined variables, or returns the base internal prefix. ### Parameters #### Query Parameters - **name** (string) - Optional - The specific name to prefix with the internal identifier. ``` -------------------------------- ### Initialize and Render with Client API Source: https://mizu.sh/ Create a new Client instance with an initial context and trigger the rendering process. ```javascript const mizu = new Client({ context: { foo: "bar" } }) await mizu.render() ``` -------------------------------- ### Define a Directive with Typings Source: https://mizu.sh/coverage/internal/engine/directive.ts.html Example of defining a directive with custom typings configuration. ```typescript const foo = { name: "*foo", phase: Phase.UNKNOWN, typings, async execute(renderer, element, { attributes: [ attribute ], ...options }) { console.log(renderer.parseAttribute(attribute, this.typings, { modifiers: true })) } } as const satisfies Directive<{ Typings: typeof typings}> ``` -------------------------------- ### Client.constructor Source: https://mizu.sh/ Initializes a new instance of the mizu.js Client. ```APIDOC ## Client.constructor(options?: ClientOptions) ### Description Creates a new Client instance. Default options are merged with the provided options. ### Parameters #### Request Body - **options** (ClientOptions) - Optional - Configuration object for the client instance. ``` -------------------------------- ### Initialize Mizu Client Source: https://mizu.sh/coverage/render/client/client.ts.html Instantiate the Client with custom options, merging them with defaults. Ensure to provide necessary configurations for directives, context, and logging. ```typescript import type { Arg, Directive, RendererOptions, RendererRenderOptions } from "@mizu/internal/engine" import { Context, Renderer } from "@mizu/internal/engine" import defaults from "./defaults.ts" export type * from "@mizu/internal/engine" /** * Client side renderer. * @module */ export class Client { /** * Default options for {@linkcode Client}. * * These default options are merged with the provided options when creating a new {@linkcode Client} instance. */ static defaults = { window: globalThis.window, directives: defaults, // @ts-expect-error: custom builder context: globalThis.MIZU_CUSTOM_DEFAULTS_CONTEXT ?? {}, // @ts-expect-error: custom builder // deno-lint-ignore no-console warn: globalThis.MIZU_CUSTOM_DEFAULTS_WARN ?? console.warn, // @ts-expect-error: custom builder debug: globalThis.MIZU_CUSTOM_DEFAULTS_DEBUG ?? false, } as unknown as Required /** {@linkcode Client} constructor. */ constructor(options?: ClientOptions) { const { directives, window, warn, debug, context } = { ...Client.defaults, ...options } this.#renderer = new Renderer(window, { directives, warn, debug }) // deno-lint-ignore no-explicit-any this.#context = new Context(context) } /** Linked {@linkcode Renderer}. */ readonly #renderer /** Linked {@linkcode Context}. */ readonly #context /** * Rendering context. * * All properties assigned to this object are available during rendering. * * Changes to this object are reactive and will trigger a re-render of related elements. * This is achieved using {@linkcode Context}, which leverages {@linkcode https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy | Proxy} handlers. * * > [!NOTE] * > You cannot reassign this property directly to ensure reactivity is maintained. * > To achieve a similar effect, use {@linkcode https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign | Object.assign()}. */ // deno-lint-ignore no-explicit-any get context(): Record { return this.#context.target } /** * Start rendering all subtrees marked with the {@linkcode https://mizu.sh/#mizu | *mizu} attribute. * * ```ts ignore * const mizu = new Client({ context: { foo: "bar" } }) * await mizu.render() * ``` */ render>(element = this.#renderer.document.documentElement as T, options?: ClientRenderOptions): Promise { let context = this.#context if (options?.context) { context = context.with(options.context) } return this.#renderer.render(element, { implicit: false, reactive: true, ...options, context, state: { $renderer: "client", ...options?.state } }) } /** Flush the reactive render queue of {@linkcode Renderer}. */ flush(): Promise { return this.#renderer.flushReactiveRenderQueue() } /** Default {@linkcode Client} instance. */ static readonly default = new Client() as Client } /** {@linkcode Client} options. */ export type ClientOptions = Pick & { /** Default directives. */ directives?: Array | string> /** * Initial rendering {@linkcode Context}. * * It can be modified later using the {@linkcode Client.context} property. */ context?: ConstructorParameters[0] /** Window object. */ window?: Renderer["window"] } /** {@linkcode Client.render} options. */ export type ClientRenderOptions = Pick & { /** * Rendering context. * * Values from {@linkcode Client.context} are inherited. */ context?: Arg /** * Initial state. * * It is populated with `$renderer: "client"` by default. */ state?: Arg["state"] } ``` -------------------------------- ### GET /cache Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Retrieves or sets data in the renderer's cache for a specific directive. ```APIDOC ## GET /cache ### Description Retrieves data from the cache for a given directive name, or optionally sets it if provided. Special handling exists for the '*' directive to return a WeakMap. ### Parameters #### Request Body - **directive** (string) - Required - The name of the directive or '*' for the global cache. - **cache** (any) - Optional - The data to store in the cache for the specified directive. ``` -------------------------------- ### Server Constructor Source: https://mizu.sh/coverage/render/server/server.ts.html Initializes a new Server instance, merging default options with provided options. It also sets up the internal context for rendering. ```typescript constructor(options?: ServerOptions) { this.#options = { ...Server.defaults, ...options } this.#options.generate = { ...Server.defaults.generate, ...options?.generate } this.#options.generate.fs = { ...Server.defaults.generate.fs, ...options?.generate?.fs } // deno-lint-ignore no-explicit-any this.#context = new Context(this.#options.context) } ``` -------------------------------- ### Render HTML with Mizu Server Source: https://mizu.sh/ Initializes a server instance with a custom context and renders an HTML string. ```javascript const mizu = new Server({ context: { foo: "bar" } }) await mizu.render(``) ``` -------------------------------- ### Matcha.css Integration Source: https://mizu.sh/ Instructions for integrating Matcha.css for theming. ```APIDOC ## Matcha.css Integration Link the Matcha.css stylesheet to theme your web page. ```html ``` ``` -------------------------------- ### capture(string, offset) Source: https://mizu.sh/coverage/mustache/capture.ts.html Parses a string to find the first mustache expression starting at the provided offset. ```APIDOC ## capture(string, offset) ### Description Extracts content between mustache delimiters ({{ }} or {{{ }}}). It handles nested brackets and quoted strings to ensure the correct closing delimiter is identified. ### Parameters - **string** (string) - Required - The input string to parse. - **offset** (number) - Optional - The starting index for the search. Defaults to 0. ### Response Returns an object containing the match details or null if no expression is found. - **a** (number) - Start index of the match. - **b** (number) - End index of the match. - **match** (string) - The full matched string including delimiters. - **captured** (string) - The trimmed content inside the delimiters. - **triple** (boolean) - True if triple braces ({{{ }}}) were used. ### Response Example { "a": 4, "b": 13, "match": "{{ bar }}", "captured": "bar", "triple": false } ``` -------------------------------- ### Initialize Renderer and Access Cache Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Demonstrates how to initialize the Renderer and assert the type of its cache. ```typescript import { Window } from "@mizu/internal/vdom" const renderer = await new Renderer(new Window()).ready console.assert(renderer.cache("*") instanceof WeakMap) ``` -------------------------------- ### Define `#slot` Directive Source: https://mizu.sh/coverage/custom-element/mod.ts.html Defines the `#slot` directive used for meta-phase processing. It matches names starting with '#'. ```typescript /** `#slot` directive. */ export const _slot = { name: /^#(?)/, prefix: "#", phase: Phase.META, } as const satisfies Directive<{ Name: RegExp }> ``` -------------------------------- ### Custom Build Creation Source: https://mizu.sh/build Instructions and information on how to create a custom build of mizu.js. ```APIDOC ## Custom Build Creation This section details how to create a custom build of mizu.js for client-side rendering. ### Process 1. **Choose Format**: Select the desired output format for your build. - `iife`: The mizu.js renderer starts automatically when the script is loaded. - `esm`: The mizu.js renderer needs to be imported as a module and started manually. 2. **Logging Options**: Configure logging for warnings and debug messages. - Log warnings using `console.warn()`. - Log debug messages using `console.debug()`. 3. **Build Generation**: Click the button to initiate the build process. This action calls a serverless function. ### Considerations - The build generation process may be subject to time-limits or rate-limits. - Successful builds will open in a new tab. - Errors during the build process will display an error message. ``` -------------------------------- ### Client Rendering API Source: https://mizu.sh/coverage/render/client/client.ts.html Methods for initializing the Mizu client, rendering DOM elements, and managing the reactive render queue. ```APIDOC ## Client.render ### Description Starts rendering all subtrees marked with the mizu attribute. This method processes the provided element and its children based on the configured directives and reactive context. ### Parameters #### Path Parameters - **element** (Arg) - Optional - The DOM element to render. Defaults to the document root. #### Request Body - **options** (ClientRenderOptions) - Optional - Configuration for the render process, including context overrides and state. ### Response #### Success Response (200) - **Promise** - A promise that resolves with the rendered element. --- ## Client.flush ### Description Flushes the reactive render queue of the underlying Renderer, ensuring all pending reactive updates are applied to the DOM. ### Response #### Success Response (200) - **Promise** - A promise that resolves when the queue has been flushed. ``` -------------------------------- ### Implement the *once directive Source: https://mizu.sh/coverage/once/mod.ts.html Defines the *once directive structure, including its initialization, setup logic to check the cache, and cleanup logic to handle element replacement. ```typescript // Imports import { type Cache, type Directive, Phase } from "@mizu/internal/engine" export type * from "@mizu/internal/engine" /** `*once` typings. */ export const typings = { modifiers: { flat: { type: Boolean }, }, } as const /** `*once` directive. */ export const _once = { name: "*once", phase: Phase.POSTPROCESSING, typings, init(renderer) { renderer.cache>(this.name, new WeakSet()) }, setup(_, element, { cache }) { if (cache.has(element)) { return false } }, cleanup(renderer, element, { cache }) { let target = element if ((renderer.isComment(element)) && (renderer.cache("*").has(element))) { target = renderer.cache("*").get(element)! } const attribute = renderer.getAttributes(target, this.name, { first: true }) if (!attribute) { return } const parsed = renderer.parseAttribute(attribute, this.typings, { modifiers: true }) if ((renderer.isHtmlElement(element)) && (parsed.modifiers.flat)) { renderer.replaceElementWithChildNodes(element, element).forEach((element) => cache.add(element)) } cache.add(element) }, } as const satisfies Directive<{ Cache: WeakSet Typings: typeof typings }> /** Default exports. */ export default _once ``` -------------------------------- ### POST /load Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Loads additional directives into the renderer instance. ```APIDOC ## POST /load ### Description Registers new directives. If a directive is passed as a string, it is dynamically imported. Directives must have a valid name and phase. ### Parameters #### Request Body - **directives** (Array) - Required - An array of directive objects or module paths (strings) to load. ``` -------------------------------- ### Filter Function API Source: https://mizu.sh/coverage/internal/testing/filter.ts.html This section details the `filter` function, which is the primary entry point for filtering HTML elements. It explains its parameters, return value, and provides an example of its usage. ```APIDOC ## filter Function API ### Description Recursively filters an `Element` and its subtree and returns the `Element.innerHTML`. This function can be used to compare two HTML documents. Elements with a `filter-remove` attribute are filtered out. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `filter` function: - **renderer** (Renderer) - Required - The renderer instance. - **node** (Nullable) - Required - The HTML element to filter. - **options** (FilterOptions) - Optional - An object containing filtering options: - **format** (boolean) - Optional - Whether to format the output. Defaults to `true`. - **comments** (boolean) - Optional - Whether to include comments. Defaults to `true`. - **directives** (Array) - Optional - Directives to keep. Defaults to `["*warn", "*id"]`. - **clean** (string) - Optional - Pattern used to clean attributes. Defaults to `""`. ### Request Example ```typescript import { expect } from "@libs/testing" import { Window } from "@mizu/internal/vdom" import { Renderer } from "@mizu/internal/engine" const renderer = await new Renderer(new Window()).ready await using a = new Window(`foo`) await using b = new Window(`foo`) expect(filter(renderer, a.document.documentElement)).toBe(filter(renderer, b.document.documentElement)) ``` ### Response #### Success Response (200) - **string** - The filtered HTML string. ``` -------------------------------- ### Attribute Modifier Parsing Example Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Demonstrates how attribute modifiers are parsed and how default values are applied or enforced for boolean attributes. Use this to understand default value behavior and the `enforce` option. ```typescript import { Window } from "@mizu/internal/vdom" const renderer = await new Renderer(new Window()).ready const modifier = (attribute: Attr, typing: AttrBoolean) => renderer.parseAttribute(attribute, { modifiers: { value: typing } }, { modifiers: true }).modifiers const [a, b] = Array.from(renderer.createElement("div", { attributes: { "*a.value": "", "*b": "" } }).attributes) // `a.value === true` because it was defined, and the default for `AttrBoolean` is `true` console.assert(modifier(a, { type: Boolean }).value === true) // `a.value === false` because it was defined, and the default was set to `false` console.assert(modifier(a, { type: Boolean, default: false }).value === false) // `b.value === undefined` because it was not explicitly defined, despite the default for `AttrBoolean` being `true` console.assert(modifier(b, { type: Boolean }).value === undefined) // `b.value === true` because it was not explicitly defined, but the default was enforced console.assert(modifier(b, { type: Boolean, enforce: true }).value === true) // `b.value === false` because it was not explicitly defined, and the default was set to `false` and was enforced console.assert(modifier(b, { type: Boolean, default: false, enforce: true }).value === false) ``` -------------------------------- ### Server.render Source: https://mizu.sh/ Renders content using the Mizu server engine. ```APIDOC ## Server.render ### Description Renders the provided content into a string based on the specified options. ### Method N/A (Class Method) ### Parameters - **content** (string | Arg) - Required - The content to render. - **options** (ServerRenderOptions & Pick) - Optional - Configuration options for the rendering process. ### Response - **Promise** - Returns a promise that resolves to the rendered string. ``` -------------------------------- ### Directives - Rendering Source: https://mizu.sh/ Documentation for rendering directives in Mizu.js. ```APIDOC ## `*mizu` Directive ### Description This directive is related to the rendering process in Mizu.js. Its specific behavior is part of the rendering phase. ### Tag `*mizu` ``` -------------------------------- ### Create Virtual Window with JSDOM Source: https://mizu.sh/coverage/internal/vdom/jsdom.ts.html Instantiate a virtual window using JSDOM. Ensure to use `await using` for proper disposal of the window resources. ```typescript // Imports import type { VirtualWindow } from "../engine/mod.ts" import { JSDOM } from "jsdom" export type { VirtualWindow } /** * Virtual {@linkcode https://developer.mozilla.org/docs/Web/API/Window | Window} implementation based on {@link https://github.com/jsdom/jsdom | JSDOM}. * * ```ts * await using window = new Window("") * console.assert(window.document.documentElement.tagName === "HTML") * ``` */ const Window = (function (content: string) { const { window } = new JSDOM(content, { url: globalThis.location?.href, contentType: "text/html" }) window[Symbol.asyncDispose] = async () => { await window.close() } return window }) as unknown as (new (content?: string) => VirtualWindow) export { Window } ``` -------------------------------- ### Include Mizu.js Client-side (IIFE) Source: https://mizu.sh/ Include the Mizu.js client-side script using an Immediately Invoked Function Expression (IIFE). This method automatically starts rendering the page once the script is loaded. ```html ``` -------------------------------- ### Directive Initialization (init) Source: https://mizu.sh/coverage/internal/engine/directive.ts.html The `init` callback is executed once when the directive is loaded by `Renderer.load()`. It's used for setting up dependencies, caches, and other initialization tasks. ```APIDOC ## Directive Initialization (init) ### Description The `init` callback is executed once during when `Renderer.load()` loads the directive. It should be used to set up dependencies, instantiate directive-specific caches (via `Renderer.cache()`), and perform other initialization tasks. If a cache is instantiated, it is recommended to use the `Directive` generic type to ensure type safety when accessing it in `Directive.setup()`, `Directive.execute()`, and `Directive.cleanup()`. ### Request Example ```ts const foo = { name: "*foo", phase: Phase.UNKNOWN, async init(renderer) { renderer.cache(this.name, new WeakSet()) }, } as const satisfies Directive<{ Cache: WeakSet }> ``` ``` -------------------------------- ### Create Comment Node Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Creates a comment node and replaces the original element with it. It caches the original element for later retrieval. Use when you need to temporarily replace an element with a comment, for example, during conditional rendering. ```typescript comment(element: HTMLElement, { directive, expression }: { directive: string; expression: string }): Comment { const attributes = this.createNamedNodeMap() attributes.setNamedItem(this.createAttribute(directive, expression)) const comment = Object.assign(this.document.createComment(`[${directive}="${expression}"]`), { attributes }) this.cache("*").set(comment, element) this.#comments.set(element, comment) element.parentNode?.replaceChild(comment, element) return comment } ``` -------------------------------- ### Initialize a Directive Source: https://mizu.sh/coverage/internal/engine/directive.ts.html Use the init callback to set up dependencies or caches when the directive is loaded. ```typescript const foo = { name: "*foo", phase: Phase.UNKNOWN, async init(renderer) { renderer.cache(this.name, new WeakSet()) }, } as const satisfies Directive<{ Cache: WeakSet }> ``` -------------------------------- ### Renderer.render() Options Source: https://mizu.sh/coverage/internal/engine/renderer.ts.html Options for configuring the rendering process within the Renderer. ```APIDOC ## Renderer.render() Options ### Description Options for configuring the rendering process within the Renderer. ### Parameters #### Request Body - **context** (Context) - Optional - Context to use. - **state** (State) - Optional - State to use. - **implicit** (boolean) - Optional - Whether to render subtrees that do not possess the explicit rendering attribute. - **reactive** (boolean) - Optional - Whether to enable reactivity. - **select** (string) - Optional - CSS selector to query select the return. - **stringify** (boolean) - Optional - Whether to return the result as an HTML string. - **throw** (boolean) - Optional - Whether to throw on errors. ``` -------------------------------- ### Directives - Contextual Source: https://mizu.sh/ Documentation for contextual directives in Mizu.js. ```APIDOC ## `*set` and `*ref` Directives ### Description Contextual directives used for managing context and references within Mizu.js. ### `*set="context"` - **Description**: Sets a context value. - **Tag**: `*set` ### `*ref="name"` - **Description**: Creates a reference to an element or value. - **Tag**: `*ref` ``` -------------------------------- ### SSG with Node.js Source: https://mizu.sh/ Static site generation using Mizu in a Node.js environment. ```javascript // Static Site Generation (SSG) with Mizu import Mizu from "@mizu/render/server" await Mizu.generate([ // Copy content from strings [`
`, "index.html", { render: { context: { foo: "🌊 Yaa, mizu!" } } }], // Copy content from callback return [() => JSON.stringify(Date.now()), "timestamp.json"], // Copy content from local files ["**/*", "static", { directory: "/fake/path" }], // Copy content from URL [new URL("https://matcha.mizu.sh/matcha.css"), "styles.css"], ], { clean: true, output: "/tmp/output" }) ``` -------------------------------- ### Generate Static Files from Sources Source: https://mizu.sh/ Configures a server to generate static files from multiple source types, including strings, local files, callbacks, and URLs, with optional rendering context. ```javascript const mizu = new Server({ directives: ["@mizu/test"], generate: { output: "/fake/output" } }) await mizu.generate( [ // Copy content from strings [ "

foo

", "string.html" ], [ "

", "string_render.html", { render: { context: { foo: "bar" } } } ], // Copy content from local files [ "**\/*", "public", { directory: "/fake/static" } ], [ "*.html", "public", { directory: "/fake/partials", render: { context: { foo: "bar "} } } ], // Copy content from callback return [ () => JSON.stringify({ foo: "bar" }), "callback.json" ], [ () => `

`, "callback.html", { render: { context: { foo: "bar" } } } ], // Copy content from URL [ new URL(`data:text/html,

foobar

`), "url.html" ], [ new URL(`data:text/html,

`), "url_render.html", { render: { context: { foo: "bar" } } } ], ], // No-op: do not actually write files and directories { fs: { readdir: () => Promise.resolve([] as string[]), mkdir: () => null as any, write: () => null as any } }, ) ``` -------------------------------- ### Include matcha.css Source: https://mizu.sh/community Link to the matcha.css stylesheet to enable theming for your web page. ```html ``` -------------------------------- ### Server.render Source: https://mizu.sh/ Parses an HTML string and renders all subtrees based on the provided context and directives. ```APIDOC ## Server.render ### Description Parses an HTML string and renders all subtrees. The *mizu attribute is only required if implicit is set to false. ### Parameters #### Request Body - **content** (string | Arg) - Required - The HTML content to render. - **options** (ServerRenderOptions & Pick) - Optional - Rendering configuration options. ### Request Example const mizu = new Server({ context: { foo: "bar" } }) await mizu.render(``) ### Response #### Success Response (200) - **Promise** - The rendered HTML string. ``` -------------------------------- ### Client.context Source: https://mizu.sh/ Accesses the reactive rendering context. ```APIDOC ## Client.context ### Description Rendering context object. All properties assigned here are available during rendering. Changes are reactive and trigger re-renders. Note: Do not reassign this property directly; use Object.assign() to maintain reactivity. ### Response - **Record** - The current reactive context object. ``` -------------------------------- ### Directives - Testing Source: https://mizu.sh/ Documentation for testing directives in Mizu.js. ```APIDOC ## `~test` Directive ### Description Directive used for testing purposes. ### `~test="expression"` - **Description**: Evaluates an expression for testing. - **Tag**: `~test` ``` -------------------------------- ### Server-side API Source: https://mizu.sh/ Documentation for the server-side API of Mizu.js, including its constructor and default options. ```APIDOC ## Server-side API ### Description Provides methods for initializing Mizu.js on the server-side. ### Defaults Directives Default directives used by the server. ### Constructor `Server.constructor(options?: ServerOptions)` Initializes a new Server instance. ### Properties - `Server.defaults` (Required): The default options for the Server. - `Server.default` (Server): The default singleton Server instance. ``` -------------------------------- ### Directives - HTTP Source: https://mizu.sh/ Documentation for HTTP request directives in Mizu.js. ```APIDOC ## HTTP Directives (`%http`, `%header`, `%body`, `%response`, `%@event`) ### Description Directives for making HTTP requests and handling responses. ### `%http="url"` - **Description**: Specifies the URL for an HTTP request. - **Tag**: `%http` ### `%header[name]="value"` - **Description**: Sets a header for the HTTP request. - **Tag**: `%header` ### `%body="content"` - **Description**: Sets the request body for the HTTP request. - **Tag**: `%body` ### `%response="expression"` - **Description**: Specifies an expression to handle the HTTP response. - **Tag**: `%response` ### `%@event="listener"` - **Description**: Handles events related to the HTTP request. - **Tag**: `%@event` ``` -------------------------------- ### Initialize and Configure HTML Formatter Source: https://mizu.sh/coverage/internal/testing/format.ts.html Initializes the HTML formatter from a WASM buffer and sets its configuration. Ensure the WASM file is correctly located. ```typescript // Imports import { createFromBuffer } from "@dprint/formatter" import { fromFileUrl } from "@std/path" // deno-lint-ignore no-external-import import { readFileSync } from "node:fs" /** HTML formatter. */ const formatter = createFromBuffer(readFileSync(fromFileUrl(import.meta.resolve("./fixtures/markup_fmt-v0.13.1.wasm")))) formatter.setConfig({}, { printWidth: 120, closingBracketSameLine: true, closingTagLineBreakForEmpty: "never", preferAttrsSingleLine: true, whitespaceSensitivity: "ignore" }) ``` -------------------------------- ### Client-side API Source: https://mizu.sh/ Documentation for the client-side API of Mizu.js, including its constructor, default options, context, and rendering methods. ```APIDOC ## Client-side API ### Description Provides methods for initializing and rendering Mizu.js on the client-side. ### Defaults Directives Default directives used by the client. ### Constructor `Client.constructor(options?: ClientOptions)` Initializes a new Client instance. ### Properties - `Client.defaults` (Required): The default options for the Client. - `Client.default` (Client): The default singleton Client instance. - `Client.context` (Record): The global context available to all components. ### Methods - `Client.render(element: T, options?: ClientRenderOptions) => Promise`: Renders Mizu.js directives within a specified element. - `Client.flush() => Promise`: Flushes any pending updates or operations. ``` -------------------------------- ### Server Render Method Source: https://mizu.sh/coverage/render/server/server.ts.html Parses an HTML string and renders all subtrees using the configured renderer and context. The `*mizu` attribute is only required if `implicit` is set to `false`. ```typescript async render(content: string | Arg, options?: ServerRenderOptions & Pick): Promise { await using window = new Window(typeof content === "string" ? content : `${content.outerHTML}`) const { directives, warn, debug, context: _context } = { ...this.#options, ...options } const renderer = await new Renderer(window, { directives, warn, debug }).ready let context = this.#context if (_context) { context = context.with(_context) } return await renderer.render(renderer.document.documentElement, { implicit: true, ...options, context, state: { $renderer: "server", ...options?.state }, stringify: true }) } ``` -------------------------------- ### SSR with Bun Source: https://mizu.sh/ Server-side rendering using Bun's built-in serve API. ```javascript // Server-Side Rendering (SSR) with Mizu import Mizu from "@mizu/render/server" Bun.serve({ port: 8000, async fetch() { const headers = new Headers({ "Content-Type": "text/html; charset=utf-8" }) const body = await Mizu.render(`
`, { context: { foo: "🌊 Yaa, mizu!" } }) return new Response(body, { headers }) }, }) console.log("Server is listening") ``` -------------------------------- ### Directives - Binding Source: https://mizu.sh/ Documentation for attribute and class binding directives in Mizu.js. ```APIDOC ## Binding Directives (`:attribute`, `:class`, `:style`) ### Description Directives for binding attributes, classes, and styles to dynamic values. ### `:attribute="value"` - **Description**: Binds a dynamic value to an element's attribute. - **Tag**: `:attribute` - **Note**: Binding directives are not officially supported and are considered undefined behavior. Future versions may introduce official support. ### `:class="value"` - **Description**: Binds a dynamic value to the element's class list. - **Tag**: `:class` ### `:style="value"` - **Description**: Binds a dynamic value to the element's style properties. - **Tag**: `:style` ``` -------------------------------- ### SSG with Deno Source: https://mizu.sh/ Static site generation using Deno, supporting various content sources like strings, callbacks, files, and URLs. ```typescript #!/usr/bin/env -S deno run --allow-read --allow-env --allow-net --allow-write=/tmp/output // Static Site Generation (SSG) with Mizu import Mizu from "@mizu/render/server" await Mizu.generate([ // Copy content from strings [`
`, "index.html", { render: { context: { foo: "🌊 Yaa, mizu!" } } }], // Copy content from callback return [() => JSON.stringify(Date.now()), "timestamp.json"], // Copy content from local files ["**/*", "static", { directory: "/fake/path" }], // Copy content from URL [new URL("https://matcha.mizu.sh/matcha.css"), "styles.css"], ], { clean: true, output: "/tmp/output" }) ``` -------------------------------- ### POST /server/generate Source: https://mizu.sh/coverage/render/server/server.ts.html Generates content from a list of sources and writes them to the output directory. ```APIDOC ## POST /server/generate ### Description Generates content from an array of sources (StringSource, GlobSource, CallbackSource, URLSource) and writes the output based on the provided options. ### Method POST ### Parameters #### Request Body - **sources** (Array) - Required - An array of source definitions (StringSource, GlobSource, CallbackSource, or URLSource). - **options** (ServerGenerateOptions) - Optional - Configuration for output directory, cleaning, and file system overrides. ```