### uhtml Fragment Rendering Example
Source: https://github.com/webreflection/uhtml/blob/main/README.md
Shows how uhtml handles rendering multiple sibling elements directly within a template literal without requiring a wrapper fragment like JSX's `<>...>`. This demonstrates a key difference and simplification offered by uhtml's syntax.
```javascript
// uhtml fragment example
html`
first element
...
last element
`
```
--------------------------------
### Loading uhtml from CDN
Source: https://github.com/webreflection/uhtml/blob/main/README.md
Provides examples of how to load the uhtml library from a Content Delivery Network (CDN) using various import paths for production, development, and automatic version selection. It highlights the benefit of using CDN URLs for automatic debug mode switching.
```javascript
// implicit production version
import { render, html } from 'https://esm.run/uhtml';
// https://cdn.jsdelivr.net/npm/uhtml/dist/prod/dom.js
// explicit production version
import { render, html } from 'https://esm.run/uhtml/prod';
// https://cdn.jsdelivr.net/npm/uhtml/dist/prod/dom.js
// explicit developer/debugging version
import { render, html } from 'https://esm.run/uhtml/dev';
import { render, html } from 'https://esm.run/uhtml/debug';
// https://cdn.jsdelivr.net/npm/uhtml/dist/dev/dom.js
// automatic prod/dev version on ?dev or ?debug
import { render, html } from 'https://esm.run/uhtml/auto';
import { render, html } from 'https://esm.run/uhtml/cdn';
// https://cdn.jsdelivr.net/npm/uhtml/dist/prod/cdn.js
```
--------------------------------
### Rollup Configuration for Minifying uhtml Templates
Source: https://github.com/webreflection/uhtml/blob/main/README.md
An example Rollup configuration using rollup-plugin-minify-template-literals and @rollup/plugin-terser to optimize JavaScript and uhtml templates for production. It highlights specific options for template minification.
```js
import terser from "@rollup/plugin-terser";
import templateMinifier from "rollup-plugin-minify-template-literals";
import { nodeResolve } from "@rollup/plugin-node-resolve";
export default {
input: "src/your-component.js",
plugins: [
templateMinifier({
options: {
minifyOptions: {
// allow only explicit
ignoreCustomComments: [/^!/],
keepClosingSlash: true,
caseSensitive: true,
},
},
}),
nodeResolve(),
terser(),
],
output: {
esModule: true,
file: "dist/your-component.js",
},
};
```
--------------------------------
### Create and Render a Reactive Counter with uhtml
Source: https://github.com/webreflection/uhtml/blob/main/test/counter.html
This snippet defines a Counter component that uses a signal to track its state. The component renders a button that increments the count when clicked. The component is then appended to the document body.
```javascript
import { html, signal } from '../dist/dev/dom.js';
function Counter() {
const count = signal(0);
return html` `;
}
document.body.append( html`<${Counter} />` );
```
--------------------------------
### Creating a Reactive Counter Component with uhtml Signals
Source: https://github.com/webreflection/uhtml/blob/main/README.md
Illustrates how to create a reusable 'Counter' component using uhtml's `signal` for state management. The component features a button that increments a counter, and the displayed count updates reactively. This example also uses `esm.run` for module import.
```javascript
import { html, signal } from 'https://esm.run/uhtml';
function Counter() {
const count = signal(0);
return html`
`;
}
document.body.append(
html`<${Counter} />`
);
```
--------------------------------
### Special Attributes in uhtml - Events, Bindings, and More
Source: https://context7.com/webreflection/uhtml/llms.txt
Explains uhtml's special attribute syntax for handling events (@event, on), property binding (.property), boolean attributes (?attribute), ARIA attributes, and data attributes. Shows examples of direct property access and conditional attributes.
```javascript
import { html, signal } from 'uhtml';
// Event handlers with @event or onevent syntax
const handleClick = (e) => console.log('Clicked!', e);
const button1 = html``;
const button2 = html``;
// Event with options (array syntax)
const buttonWithOptions = html`
`;
// Direct property access with .property
const inputValue = signal("initial");
const input = html`
inputValue.value = e.target.value} />
`;
// Boolean attributes with ?attribute
const isDisabled = signal(false);
const isHidden = signal(true);
const element = html`
Secret content
`;
// Aria attributes for accessibility
const ariaButton = html`
`;
// Data attributes
const dataElement = html`
Element with data-* attributes
`;
document.body.append(button1, button2, buttonWithOptions, input, element, ariaButton, dataElement);
```
--------------------------------
### Using Import Maps with uhtml in HTML
Source: https://github.com/webreflection/uhtml/blob/main/README.md
Demonstrates how to use an import map to include uhtml from a CDN and then import and use it within a module script. This approach enhances portability and allows exclusion from bundlers.
```html
```
--------------------------------
### Basic HTML Rendering with uhtml
Source: https://github.com/webreflection/uhtml/blob/main/README.md
Demonstrates the fundamental usage of the `html` tag from the uhtml library to render a simple HTML heading into the document's body. This requires importing the `html` function from 'uhtml' via esm.run.
```html
```
--------------------------------
### CDN Usage and Browser Import Maps with uhtml
Source: https://context7.com/webreflection/uhtml/llms.txt
Shows how to load uhtml directly from a CDN using browser import maps. This allows for easy integration without a build process and supports automatic production/development mode switching.
```html
```
--------------------------------
### Spread Props on Elements and Components with uhtml
Source: https://context7.com/webreflection/uhtml/llms.txt
Demonstrates how to use object spread syntax to spread props onto HTML elements and uhtml components. This feature simplifies passing multiple attributes or properties to elements and components, reducing boilerplate code.
```javascript
import { html } from 'uhtml';
// Spread attributes on elements
const buttonProps = {
class: 'btn btn-primary',
type: 'submit',
disabled: false
};
const button = html``;
// Spread props on components
function Button({ class: className, children, ...rest }) {
return html`
`;
}
const componentProps = {
type: 'button',
onclick: () => console.log('clicked'),
'aria-label': 'Action button'
};
document.body.append(
html`<${Button} class="custom" ...${{...componentProps}}>Click Me>`
);
```
--------------------------------
### Render Dynamic Lists with uhtml
Source: https://github.com/webreflection/uhtml/blob/main/test/index.html
Demonstrates rendering an unordered list (`
`) with dynamically generated list items (`
`) using uhtml. The order of items is changed after 3 and 4 seconds, showcasing list re-rendering.
```javascript
import { render, html } from '../dist/dev/dom.js';
function LI(entries) {
return entries.map(key => html`
Rando ${key}
`);
}
function UL(keys) {
return html`
${LI(keys)}
`;
}
setTimeout((...args) => {
render(document.body, () => UL([1, 2, 3]));
}, 3000, document.body, comp);
setTimeout((...args) => {
render(document.body, () => UL([3, 2, 1]));
}, 4000, document.body, comp);
```
--------------------------------
### Function-Based Components in uhtml
Source: https://context7.com/webreflection/uhtml/llms.txt
Demonstrates creating React-like function components in uhtml. Components can accept props and utilize signals for internal state management. Supports rendering nested components and children.
```javascript
import { html, signal, render } from 'uhtml';
// Simple component with props
function Greeting({ name, age }) {
return html`
Hello, ${name}! You are ${age} years old.
`;
}
document.body.append(
html`<${Greeting} name="Alice" age=${30} />`
);
// Component with children
function Card({ title, children }) {
return html`
`);
```
--------------------------------
### Key Attribute for Efficient List Updates in uhtml
Source: https://context7.com/webreflection/uhtml/llms.txt
Explains the `key` attribute in uhtml, which provides a unique identity for list items to enable efficient updates and reordering. Demonstrates how uhtml reuses keyed elements when the list data changes.
```javascript
import { html, signal, render } from 'uhtml';
const items = signal([
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
]);
function ItemList() {
return html`
${items.value.map(item => html`
${item.name}
`)}
`;
}
render(document.body, ItemList);
// When items change, keyed elements are reused efficiently
items.value = [
{ id: 2, name: 'Banana' }, // Reused
{ id: 1, name: 'Apple' }, // Reused, just moved
{ id: 4, name: 'Date' } // New element created
];
```
--------------------------------
### Create DOM Fragments with fragment
Source: https://context7.com/webreflection/uhtml/llms.txt
The `fragment` utility simplifies the creation of DOM `DocumentFragment` objects from HTML or SVG strings. It acts as a convenient wrapper around the standard template element parsing, making it easier to work with DOM fragments.
```javascript
import { fragment } from 'uhtml';
// Create HTML fragment
const htmlFragment = fragment('
Hello
World');
document.body.append(htmlFragment);
// Create SVG fragment (pass true as second argument)
const svgFragment = fragment('', true);
```
--------------------------------
### uhtml Core Exports and Usage
Source: https://github.com/webreflection/uhtml/blob/main/README.md
Imports and explains the core functionalities of the uhtml library, including rendering functions (render, html, svg), unsafe content injection, and signal-based reactivity utilities. It also mentions internal classes and helper functions.
```javascript
import {
// DOM manipulation
render, html, svg, unsafe,
// Preact like signals, based on alien-signals library
signal, computed, effect, untracked, batch,
// extras
Hole, fragment,
} from 'https://esm.run/uhtml';
```
--------------------------------
### Define and Render a Button Component with uhtml
Source: https://github.com/webreflection/uhtml/blob/main/test/index.html
Defines a reusable Button component that accepts text and children props. It then renders this component, initially with 'hello world'. The text is updated after 2 seconds.
```javascript
import { render, html, signal, unsafe } from '../dist/dev/dom.js';
let hello = 'hello';
const comp = () => html`<${Button} text=${hello}>world>`;
function Button(props) {
return html``;
}
document.body.appendChild(comp());
setTimeout((...args) => {
hello = 'ahoi';
render(...args);
}, 2000, document.body, comp);
```
--------------------------------
### Render Content and Manage Reactivity with uhtml's render Function
Source: https://context7.com/webreflection/uhtml/llms.txt
The `render` function in uhtml mounts content to a specified DOM element and supports reactive updates. When provided with a function, it creates a scoped effect that re-renders automatically when reactive dependencies change.
```javascript
import { render, html, signal } from 'uhtml';
// Simple one-time render
render(document.getElementById('app'), html`
Static Content
`);
// Reactive render with a function
const count = signal(0);
render(document.body, () => html`
Count: ${count.value}
`);
// The DOM automatically updates when count.value changes
// Clicking the button triggers a re-render of just the changed parts
```
--------------------------------
### Using Special Attributes in uhtml
Source: https://github.com/webreflection/uhtml/blob/main/README.md
Demonstrates the usage of special attributes provided by uhtml for enhanced functionality. This includes simplifying ARIA attributes with `aria`, handling dataset with `data`, managing generic events with `@event`, direct event handling with `on...`, direct property updates with `.direct`, and boolean attributes with `?toggle`.
```javascript
* `aria` attribute to simplify *a11y*, such as ``
* `data` attribute to simplify *dataset* handling, such as ``
* `@event` attribute for generic events handling, accepting an array when *options* are meant to be passed, such as `