hyperscript

repository·master·Indexed 25 days ago

https://github.com/bigskysoftware/_hyperscript

A web-focused scripting language inspired by HyperTalk that enables expressive, declarative behavior directly within HTML using a specialized `_` attribute. Version 0.9.93 features automatic reactivity via `live`, `when`, and `bind`, as well as an `eventsource` feature for Server-Sent Events (SSE) with support for custom HTTP methods and wildcard event matching. Includes a dedicated debugger extension and tooling for VS Code, JetBrains, Neovim, Vim, and Sublime Text.

Tokens
89K
Snippets
335
Records
619
Agent score
86%

What's inside hyperscript

  1. Hyperscript Syntax Basics

    master

    Hyperscript scripts are composed of three main building blocks:

    1. Features: Top-level elements (e.g., event handlers like on click).
    2. Commands: Statements often called within features (e.g., toggle).
    3. Expressions: Parts of commands (e.g., .red or me).

    Comments

    Comments start with -- followed by a whitespace character and continue to the end of the line.

    Separators

    • Use then to separate multiple commands on the same line (similar to a semicolon in JS).
    • Use end to terminate command bodies (like if) or features (like on click).
    • end can often be omitted if the script ends or another feature starts immediately after.
    -- this is a comment
    log "Yep, that was a comment"
    
    log "Hello" then log "World"
    
    if x > 10
      log "Greater than 10"
    end
  2. Understand Async-Transparency in Hyperscript

    master
    Hyperscript is async transparent, meaning the runtime automatically handles the resolution of asynchronous operations. You can mix synchronous and asynchronous code freely without using async or await keywords. The runtime manages the underlying Promises, allowing you to write linear, straightforward code that works with both synchronous values and asynchronous results.
  3. Use the HDB UI for inspection

    master

    The HDB UI provides three main views for debugging:

    • Evaluation panel: Enter any _hyperscript expression and press Enter (or click "Go") to see its evaluated value.
    • Code view: Displays the code currently executing. The active command is highlighted. Use the Step Over button to execute the current command and move to the next, or Continue to resume normal execution.
    • Context view: Displays local variables available in the current scope. Clicking a variable name logs it to the console.
  4. Use Hyperscript Features to define element behavior

    master

    Hyperscript programs are composed of top-level constructs called Features. Features define how an element handles events, manages state, and reacts to changes.

    Core Features

    • on: Creates an event listener (e.g., on click log "clicked!")
    • def: Defines a function.
    • init: Runs initialization logic when the code is first loaded.
    • set: Defines a new element-scoped variable.
    • behavior: Defines cross-cutting behaviors.
    • install: Installs a behavior onto the current element (e.g., install Draggable).
    • js: Embeds JavaScript code at the top level.
    • live: Declares reactive commands that re-run when dependencies change (e.g., live set $total to ($price * $qty)).
    • when: Reacts to value changes with side effects, async, or events (e.g., when $x changes ...).
    • bind: Creates a two-way sync between two values (e.g., bind .dark and #toggle's checked).
    on click log "clicked!"
    install Draggable
    live set $total to ($price * $qty)
  5. Understand Reactivity in hyperscript

    master

    Reactivity allows elements to update automatically when their dependencies change. Hyperscript tracks reads and writes of several types of values:

    • Global variables: $name
    • Element-scoped variables: :count
    • DOM-scoped variables: ^total
    • Attribute reads and writes
    • Mutations to collections: Changes to arrays, sets, and maps (e.g., via push, splice).

    Note: Regular local variables created with set x to ... are not reactive.

  6. Quickstart hyperscript in HTML

    master

    To use hyperscript in your HTML, include the script via unpkg. You can then use the _ attribute to define behaviors. For example, you can toggle classes or chain commands like call, wait, and remove.

    <script src="https://unpkg.com/hyperscript.org"></script>
    
    <button _="on click toggle .clicked">
      Toggle the "clicked" class on me
    </button>
    
    <button _="on click call alert('yep!') then wait 2s then remove me">
      Click me
    </button>
  7. Use the `morph` command to update DOM elements

    master

    The morph command updates an existing DOM element to match new content by only applying the differences. This approach preserves event listeners, focus state, and other DOM properties that are typically lost during a full element replacement.

    Syntax: morph <expression> to <expression>

    <button _="on click morph #greeting to '<h1>Hello World!</h1>'">
      Morph It
    </button>
    <div id="greeting"><h1>Hi!</h1></div>
  8. Use the `open` command to display elements

    master

    The open command is used to display or activate specific elements. It automatically detects the element type and invokes the appropriate Web API. If no target is specified, it defaults to me (the current element).

    Supported behaviors:

    • <dialog> elements: Calls showModal(). This places the dialog in the browser's top layer (providing a backdrop and focus trap).
      • Note: For non-modal dialogs that should follow standard DOM positioning (like dropdowns), use the show command instead.
    • <details> elements: Sets the open attribute.
    • Elements with a popover attribute: Calls showPopover().
    • fullscreen mode: Calls requestFullscreen() on the specified target. If no target is provided, it calls it on document.documentElement.
    • Fallback: For any other element type, it attempts to call the .open() method.
    <!-- Open a dialog -->
    <button _="on click open #my-dialog">Open Dialog</button>
    <dialog id="my-dialog">
      <p>Hello!</p>
      <button _="on click close #my-dialog">Close</button>
    </dialog>
    
    <!-- Open a details element -->
    <button _="on click open #info">Show Details</button>
    <details id="info"><summary>Info</summary><p>Details here</p></details>
    
    <!-- Enter fullscreen mode -->
    <button _="on click open fullscreen">Go Fullscreen</button>
    <button _="on click open fullscreen #video">Fullscreen Video</button>
  9. Use the `tell` command to target multiple elements

    master

    The tell command temporarily changes the default target for commands (such as add, remove, and toggle) within its block. This allows you to execute a sequence of commands against a specific set of elements defined by an expression.

    Inside a tell block, you can use the following keywords to refer to the specific element currently being acted on:

    • you
    • your
    • yourself
    <div _="on click tell <p/> in me
                       add .highlight
                       log your textContent
                     end">
      <p>Hyperscript is cool!</p>
    </div>
  10. Use the 'when' clause and result pattern for filtering

    master

    The when clause on add, remove, show, and hide evaluates a condition per element. After execution, the result contains an array of the elements that matched the condition. This is useful for search/filter UIs.

    on input
      hide #no-match
      show <li/> in #results when its textContent contains my value ignoring case
      show #no-match when the result is empty