### Initialize Hyperapp State and Fetch Data on App Start Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Configures the `init` property of a Hyperapp application to immediately fetch initial data upon startup. It sets an initial empty state and dispatches the `jsonFetcher` effect to retrieve user names, which will then be processed by the `GotNames` action. ```javascript [ {names: [], highlight: [], selected: null, bio: "", ids: []}, jsonFetcher("https://jsonplaceholder.typicode.com/users", GotNames) ] ``` -------------------------------- ### Generic Hyperapp Subscriber Function Structure Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Illustrates the fundamental structure of a Hyperapp subscriber function. A subscriber takes `dispatch` and `options` as arguments, defines logic to start listening to an event, and crucially returns a cleanup function to stop listening, ensuring proper resource management. ```javascript const mySubscriber = (dispatch, options) => { /* how to start listening to something */ return () => { /* how to stop listening to the same thing */ } } ``` -------------------------------- ### Update Hyperapp Initial State with Names and Highlight Values Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet shows how to extend the initial state object in a Hyperapp application to include `names` (an array of strings) and `highlight` (an array of booleans). This setup allows for managing multiple distinct items and their individual highlight states within the application. ```js { names: [ "Leanne Graham", "Ervin Howell", "Clementine Bauch", "Patricia Lebsack", "Chelsey Dietrich", ], highlight: [ false, true, false, false, false, ], } ``` -------------------------------- ### Hyperapp Tutorial CSS Styles Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Defines CSS rules for styling the Hyperapp tutorial example. It imports `water.css` for basic styling and customizes elements like `main`, `.person` (including `highlight` and `selected` states), `input[type=checkbox]`, `p`, and `.bio` to create a visually distinct UI for displaying person information. ```css @import url('https://cdn.jsdelivr.net/npm/water.css@2/out/light.css'); :root { --box-width: 200px; } main { position: relative;} .person { box-sizing: border-box; width: var(--box-width); padding: 10px 10px 10px 40px; position: relative; border: 1px #ddd solid; border-radius: 5px; margin-bottom: 10px; cursor: pointer; } .person.highlight { background-color: #fd9; } .person.selected { border-width: 3px; border-color: #55c; padding-top: 8px; padding-bottom: 8px; } .person input[type=checkbox] { position: absolute; cursor: default; top: 10px; left: 7px; } .person.selected input[type=checkbox] { left: 5px; top: 8px; } .person p { margin: 0; margin-left: 2px; } .person.selected p { margin-left: 0; } .bio { position: absolute; left: calc(var(--box-width) + 2rem); top: 60px; color: #55c; font-style: italic; font-size: 2rem; text-indent: -1rem; } .bio:before {content: '"';} .bio:after {content: '"';} ``` -------------------------------- ### Basic Hyperapp Application Initialization (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/app.md Demonstrates a minimal Hyperapp application setup, initializing state, defining a simple view, and mounting it to a DOM element with the `app` function. ```JavaScript import { app, h, text } from "hyperapp" app({ init: { message: "Hello World!" }, view: (state) => h("p", {}, text(state.message)), node: document.getElementById("app"), }) ``` -------------------------------- ### Implementing Separate Highlight Selection in Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This Hyperapp example demonstrates how to manage a separate highlight or selection state for items within a list. It utilizes Hyperapp's state and actions to update the currently selected item when clicked, and the view dynamically applies a distinct background style to the selected element, providing clear visual feedback. ```JavaScript import { app, h } from 'hyperapp'; const state = { items: ['Item 1', 'Item 2', 'Item 3', 'Item 4'], selectedItem: null }; const actions = { selectItem: item => state => ({ selectedItem: item === state.selectedItem ? null : item }) }; const view = (state, actions) => h('div', {}, [ h('h1', {}, 'Select an Item'), h('ul', {}, state.items.map(item => h('li', { style: { cursor: 'pointer', backgroundColor: state.selectedItem === item ? '#add8e6' : 'transparent' }, onclick: () => actions.selectItem(item) }, item ) ) ), state.selectedItem && h('p', {}, `Selected: ${state.selectedItem}`) ]); app({ state, actions, view, node: document.getElementById('app') }); ``` -------------------------------- ### Hyperapp State Initialization Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Illustrates how to initialize the application state in Hyperapp using the `init` property within the `app` configuration. This snippet sets an initial state object with `name` and `highlight` properties, which can then be used by the view to render dynamic content. ```javascript app({ init: { name: "Leanne Graham", highlight: true }, ... }) ``` -------------------------------- ### Conditional UI Rendering in Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This Hyperapp example illustrates how to conditionally render different parts of the user interface based on the application's current state. It uses a boolean flag within the state to toggle the visibility of a content block, showcasing a common and efficient pattern for creating dynamic and responsive UIs where elements appear or disappear as needed. ```JavaScript import { app, h } from 'hyperapp'; const state = { isVisible: true }; const actions = { toggleVisibility: () => state => ({ isVisible: !state.isVisible }) }; const view = (state, actions) => h('div', {}, [ h('h1', {}, 'Conditional Rendering Example'), h('button', { onclick: actions.toggleVisibility }, state.isVisible ? 'Hide Content' : 'Show Content' ), state.isVisible && h('div', { style: { marginTop: '20px', padding: '10px', border: '1px solid #ccc' } }, h('p', {}, 'This content is conditionally rendered.') ), !state.isVisible && h('p', { style: { color: 'gray' } }, 'Content is hidden.') ]); app({ state, actions, view, node: document.getElementById('app') }); ``` -------------------------------- ### Create `onKeyDown` Subscription Creator in Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Defines `onKeyDown` as a convenient subscription creator for Hyperapp. This function simplifies the usage of the `keydownSubscriber` by abstracting away the `[subscriber, options]` tuple, making it easier to define keyboard-driven subscriptions. ```javascript const onKeyDown = (key, action) => [keydownSubscriber, {key, action}] ``` -------------------------------- ### Hyperapp Basic Todo App Example Source: https://github.com/jorgebucaran/hyperapp/blob/main/README.md This example demonstrates a complete Hyperapp application for a simple to-do list. It initializes the application state, defines actions for updating the input value and adding new todos, and renders the user interface using Hyperapp's `h()` (hyperscript) and `text()` functions to construct the virtual DOM. The application updates the real DOM efficiently based on state changes. ```html ``` -------------------------------- ### Handle Fetched User Names in Hyperapp `GotNames` Action Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Implements the `GotNames` action in Hyperapp, responsible for processing data fetched from an API. It updates the application state with the first five user names and their corresponding IDs, and initializes a `highlight` array. ```javascript const GotNames = (state, data) => ({ ...state, names: data.slice(0, 5).map(x => x.name), ids: data.slice(0, 5).map(x => x.id), highlight: [false, false, false, false, false], }) ``` -------------------------------- ### Integrate Basic Keyboard Subscriptions into Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Demonstrates the initial integration of keyboard event subscriptions into a Hyperapp application's `subscriptions` property. It enables `ArrowUp` and `ArrowDown` keys to trigger `SelectUp` and `SelectDown` actions respectively, allowing basic selection navigation. ```javascript app({ ..., subscriptions: state => [ onKeyDown("ArrowUp", SelectUp), onKeyDown("ArrowDown", SelectDown), ] }) ``` -------------------------------- ### Hyperapp Hello World Application Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Demonstrates a basic 'Hello World' application using Hyperapp. It imports `h`, `text`, and `app` functions, defines a `view` that constructs a virtual DOM representing a `div` with a `p` tag displaying 'Hello world', and mounts the application to the HTML element with `id="app"`. ```javascript import {h, text, app} from "https://cdn.skypack.dev/hyperapp" app({ view: () => h("main", {}, [ h("div", {class: "person"}, [ h("p", {}, text("Hello world")), ]), ]), node: document.getElementById("app"), }) ``` -------------------------------- ### Install @hyperapp/events via npm Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/events/README.md Installs the @hyperapp/events package using npm, the Node.js package manager. This command adds the library to your project's dependencies. ```console npm install @hyperapp/events ``` -------------------------------- ### Install @hyperapp/html via npm Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/html/README.md This command installs the @hyperapp/html package into your project using npm, the Node.js package manager. It's the standard way to add this dependency for development. ```console npm install @hyperapp/html ``` -------------------------------- ### Install Hyperapp via npm Source: https://github.com/jorgebucaran/hyperapp/blob/main/README.md This command-line instruction shows how to install the Hyperapp library using npm, the Node.js package manager. This is the standard way to add Hyperapp as a dependency to a JavaScript project. ```console npm install hyperapp ``` -------------------------------- ### Install @hyperapp/time via npm Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/time/README.md This command installs the @hyperapp/time package using npm, the Node.js package manager. It makes the library available for use in your project's dependencies, typically for applications with a build step. ```console npm install @hyperapp/time ``` -------------------------------- ### Install @hyperapp/svg via npm Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/svg/README.md Instructions to install the `@hyperapp/svg` package using npm, a common package manager for JavaScript projects. This command adds the library as a dependency to your project. ```console npm install @hyperapp/svg ``` -------------------------------- ### Initial Hyperapp HTML Structure Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Provides the basic HTML boilerplate for a Hyperapp application. It includes a `meta` tag for character set, a link to an external CSS stylesheet, and a `script` tag with `type="module"` where Hyperapp JavaScript code will be embedded. The `main` element with `id="app"` serves as the mount point for the Hyperapp application. ```html
``` -------------------------------- ### Install @hyperapp/dom via npm Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/dom/README.md This command installs the `@hyperapp/dom` package using npm, making it available for use in Node.js projects or bundled web applications. It's the standard way to add the library to your project's dependencies. ```console npm install @hyperapp/dom ``` -------------------------------- ### Integrating Subscriptions with Hyperapp app() (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/subscriptions.md Demonstrates how to integrate subscriptions into a Hyperapp application using the `subscriptions:` property within the `app()` configuration. This example shows how to dispatch an action, `RequestResource`, at regular intervals defined by `delayInMilliseconds`. ```JavaScript import { onEvery } from "./time" // ... app({ init: { delayInMilliseconds: 1000 }, subscriptions: (state) => [ // Dispatch `RequestResource` every `delayInMilliseconds`. onEvery(state.delayInMilliseconds, RequestResource), ], }) ``` -------------------------------- ### Simplify Hyperapp `Select` Action with `jsonFetcher` Effect Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Demonstrates how to use the `jsonFetcher` effect creator within a Hyperapp action. The `Select` action updates the state and then triggers a side effect to fetch user biography data, dispatching the `GotBio` action upon completion. ```javascript const Select = (state, selected) => [ {...state, selected}, jsonFetcher("https://jsonplaceholder.typicode.com/users/" + state.ids[selected], GotBio), ] ``` -------------------------------- ### Describing Views with h() Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/views.md Demonstrates how to use the `h()` function to create a virtual DOM node. This example shows a button element with dynamic class binding based on state and an `onclick` event handler wired to an action. ```js const view = (state) => h( "button", { class: { "calling-acid-burn": state.beingFramed }, onclick: FindThatDisk, }, text("It's in that place where I put that thing that time.") ) ``` -------------------------------- ### Define Hyperapp Actions for Keyboard Selection Movement Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Defines `SelectUp` and `SelectDown` actions for a Hyperapp application, enabling navigation of a selection using keyboard input. These actions conditionally update the selected index and leverage an existing `Select` action to trigger associated side effects like fetching user bios. ```javascript const SelectUp = state => { if (state.selected === null) return state return [Select, state.selected - 1] } const SelectDown = state => { if (state.selected === null) return state return [Select, state.selected + 1] } ``` -------------------------------- ### Implement Hyperapp `keydownSubscriber` for Keyboard Events Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Provides an implementation for a Hyperapp subscriber that listens for `keydown` events. It dispatches a specified action when the pressed key matches a configured option, and includes a cleanup function to remove the event listener when the subscription is no longer active. ```javascript const keydownSubscriber = (dispatch, options) => { const handler = ev => { if (ev.key !== options.key) return dispatch(options.action) } addEventListener("keydown", handler) return () => removeEventListener("keydown", handler) } ``` -------------------------------- ### Hyperapp View with Dynamic State Rendering Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Shows how to modify the Hyperapp `view` function to consume and display values from the application state. It updates the `p` tag to display `state.name` and adds an `input` checkbox whose `checked` attribute is bound to `state.highlight`, demonstrating dynamic UI updates based on state. ```javascript state => h("main", {}, [ h("div", {class: "person"}, [ h("p", {}, text(state.name)), h("input", {type: "checkbox", checked: state.highlight}), ]), ]) ``` -------------------------------- ### Render List of Persons in Hyperapp View Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript code updates the Hyperapp view function to dynamically render a list of `person` components. It maps over the `state.names` array, passing each person's name, highlight status, and an `ontoggle` action with an `index` payload to the `person` component, enabling individual interaction. ```js state => h("main", {}, [ ...state.names.map((name, index) => person({ name, highlight: state.highlight[index], ontoggle: [ToggleHighlight, index], })), ]) ``` -------------------------------- ### Add IDs to Hyperapp State for Data Fetching Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet modifies the initial Hyperapp state by adding an `ids` array. These IDs are crucial for constructing URLs to fetch specific user data from an external API, preparing the application for side effects. ```JavaScript { ... selected: null, bio: "", ids: [1, 2, 3, 4, 5], // <--- } ``` -------------------------------- ### Hyperapp Actions: Wrapping and Chaining Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/actions.md Explains how Hyperapp actions can return other actions, enabling aliasing or preprocessing of payloads. It provides examples of an event adapter action to transform event data and a chain of actions for sequential payload adjustments. ```javascript // Action : () -> OtherAction const PlusOne = () => Increment ``` ```javascript // Action : (State, EventPayload) -> [OtherAction, Payload] const AddByValue = (state, event) => [AddBy, +event.target.value] ``` ```javascript h("input", { value: state, oninput: AddByValue }) ``` ```javascript const AddBy = (state, amount) => ({ ...state, value: state.value + amount }) const AddByMore = (_, amount) => [AddBy, amount + 5] const AddByEvenMore = (_, amount) => [AddByMore, amount + 10] ``` ```javascript h( "button", { onclick: [AddByEvenMore, 1] }, text("+16") ) ``` -------------------------------- ### Create a Basic Counter App with @hyperapp/html Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/html/README.md This example demonstrates building a simple counter application using Hyperapp and the @hyperapp/html library. It showcases how to define state, create view functions with HTML tag functions like 'main', 'h1', and 'button', and handle user interactions to update the state. ```html ``` -------------------------------- ### Hyperapp `view` Option: Defining the Top-Level View (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/app.md Provides an example of how to define the `view` function in Hyperapp, which maps the application state to the UI for rendering. This is the single top-level view for the application. ```JavaScript app({ // ... view: (state) => h("main", {}, [ outworld(state), netherrealm(state), ]), }) ``` -------------------------------- ### Use Hyperapp View Component in Main View Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet illustrates how to incorporate the previously defined `person` view component into a larger Hyperapp view. By calling the `person` function with specific state properties and the `ToggleHighlight` action, the main view becomes simpler and more organized, showcasing the benefits of component-based UI development. ```JavaScript state => h("main", {}, [ person({ name: state.name, highlight: state.highlight, ontoggle: ToggleHighlight, }), ]) ``` -------------------------------- ### Add Selected Property to Hyperapp Initial State Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet extends the Hyperapp initial state to include a `selected` property, initialized to `null`. This property is used to track the index of a currently selected person, allowing for single-selection functionality within the application. ```js { ... selected: null, } ``` -------------------------------- ### Implement Conditional Keyboard Subscriptions in Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Enhances Hyperapp subscriptions with conditional logic, ensuring keyboard navigation is only active when appropriate. It prevents `ArrowUp` and `ArrowDown` actions when the selection is at the top/bottom or when no item is selected, improving user experience and preventing invalid state changes. ```javascript app({ ..., subscriptions: state => [ state.selected !== null && state.selected > 0 && onKeyDown("ArrowUp", SelectUp), state.selected !== null && state.selected < (state.ids.length - 1) && onKeyDown("ArrowDown", SelectDown), ], }) ``` -------------------------------- ### Initialize Hyperapp State for Conditional Bio Display Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet shows how to add an initially empty `bio` property to the Hyperapp state in the `init` function. This property will later hold fetched user biography data, enabling conditional rendering of the bio section in the view. ```JavaScript { ..., selected: null, bio: "", // <--- } ``` -------------------------------- ### Initial Hyperapp Select Action with Direct Fetch (Problematic) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript snippet shows an initial attempt to perform a data fetch directly within a Hyperapp `Select` action. While the fetch operation executes and logs data, it highlights a common pitfall: Hyperapp actions are meant to be pure functions returning new state, not for running arbitrary side effects or asynchronous operations that need to update the state later. ```JavaScript const Select = (state, selected) => { fetch("https://jsonplaceholder.typicode.com/users/" + state.ids[selected]) .then(response => response.json()) .then(data => { console.log("Got data: ", data) /* now what ? */ }) return {...state, selected} } ``` -------------------------------- ### Hyperapp Application Example with memo() for View Optimization Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/memo.md A comprehensive Hyperapp application demonstrating the use of `memo()` to optimize view rendering. It shows how a memoized list view only updates when its specific data changes, unlike a regular view that re-renders with general state updates. ```js import { h, text, app, memo } from "hyperapp" const randomHex = () => "0123456789ABCDEF"[Math.floor(Math.random() * 16)] const randomColor = () => "#" + Array.from({ length: 6 }, randomHex).join("") const listView = (list) => h("p", { style: { backgroundColor: randomColor(), color: randomColor(), }, }, text(list)) const MoreItems = (state) => ({ ...state, list: [...state.list, randomHex()] }) const Increment = (state) => ({ ...state, counter: state.counter + 1 }) app({ init: { list: ["a", "b", "c"], counter: 0, }, view: (state) => h("main", {}, [ h("button", { onclick: MoreItems }, text("Grow list")), h("button", { onclick: Increment }, text("+1 to counter")), h("p", {}, text(`Counter: ${state.counter}`)), h("p", {}, text("Regular view showing list:")), listView(state.list), h("p", {}, text("Memoized view showing list:")), memo(listView, state.list), ]), node: document.querySelector("main"), }) ``` -------------------------------- ### JavaScript Standard Action Usage in HTML Helper Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/actions.md Continues the example of standard action usage, demonstrating how the previously defined actions (`FiftyFive`, `FiftyFiveAndLog`) are correctly integrated into Hyperapp's `h` helper for button click events. This is the valid and recommended way to trigger state changes. ```js h("button", { onclick: FiftyFive }, text("55")) h("button", { onclick: FiftyFiveAndLog }, text("55 and log")) ``` -------------------------------- ### Define `jsonFetcher` Effect Creator in Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Defines a utility function, `jsonFetcher`, that acts as an effect creator in Hyperapp. It takes a URL and an action, returning a tuple `[fetchJson, {url, action}]` which Hyperapp interprets as an effect to fetch JSON data and dispatch the specified action with the response. ```javascript const jsonFetcher = (url, action) => [fetchJson, {url, action}] ``` -------------------------------- ### Hyperapp Select Action Using Dispatch in Effecter Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript snippet refines the Hyperapp effecter pattern by introducing the `dispatch` function. The effecter now receives `dispatch` as its first argument, enabling it to call other actions (like `GotBio`) with fetched data. This allows asynchronous operations to update the application state in a controlled and Hyperapp-idiomatic way. ```JavaScript const Select = (state, selected) => [ {...state, selected}, dispatch => { // <--- fetch("https://jsonplaceholder.typicode.com/users/" + state.ids[selected]) .then(response => response.json()) .then(data => dispatch(GotBio, data)) // <--- } ] ``` -------------------------------- ### Define Hyperapp Action to Update Bio State Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript snippet defines the `GotBio` action in Hyperapp. It takes the current state and fetched data, then returns a new state object with the `bio` property updated from `data.company.bs`. This action is designed to be dispatched after successfully fetching user biography information. ```JavaScript const GotBio = (state, data) => ({...state, bio: data.company.bs}) ``` -------------------------------- ### Define Reusable Hyperapp `fetchJson` Effecter Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript snippet defines a generic `fetchJson` effecter for Hyperapp. It takes `dispatch` and an `options` object (containing `url` and `action`) as arguments. This promotes reusability by abstracting the common pattern of fetching JSON data and dispatching a specific action with the response, making it easier to manage multiple data fetching scenarios. ```JavaScript const fetchJson = (dispatch, options) => { fetch(options.url) .then(response => response.json()) .then(data => dispatch(options.action, data)) } ``` -------------------------------- ### Hyperapp Default Dispatch Initializer Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/dispatch.md Illustrates Hyperapp's default dispatch initializer, which simply returns the original dispatch function. This serves as the basic, unaugmented dispatch behavior and is the starting point for custom augmentations. ```javascript const boring = (dispatch) => dispatch ``` -------------------------------- ### Define Hyperapp View Component 'person' Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript code defines a reusable Hyperapp view component named `person`. It's a function that accepts `props` (properties) and returns a virtual DOM structure using Hyperapp's `h` function. This component encapsulates a person's name and a checkbox for highlighting, demonstrating how to create modular UI elements. ```JavaScript const person = props => h("div", { class: { person: true, highlight: props.highlight } }, [ h("p", {}, text(props.name)), h("input", { type: "checkbox", checked: props.highlight, onclick: props.ontoggle, }), ]) ``` -------------------------------- ### Define Hyperapp Action to Select a Person Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This concise JavaScript action, `Select`, updates the application state by setting the `selected` property to a new value. It receives the current `state` and the `selected` payload (which represents the index of the chosen person), returning a new state object with the updated selection. ```js const Select = (state, selected) => ({...state, selected}) ``` -------------------------------- ### Importing @hyperapp/svg functions Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/svg/README.md These snippets demonstrate how to import specific SVG functions (`svg`, `use`, `circle`) from the `@hyperapp/svg` library. The first example is for environments using module bundlers like Rollup or Webpack, while the second shows direct browser import via a script module tag. ```javascript import { svg, use, circle } from "@hyperapp/svg" ``` ```html ``` -------------------------------- ### Hyperapp Dynamic Class Assignment Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md Explains how to dynamically assign CSS classes to elements in Hyperapp using an object for the `class` property. When a key's value in the class object is truthy, the corresponding class name is applied, allowing for conditional styling based on application state, such as `state.highlight`. ```javascript h("div", {class: {person: true, highlight: state.highlight}}, [ ... ]) ``` -------------------------------- ### Hyperapp Middleware: Log Dispatched Actions Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/dispatch.md An example of an augmented dispatch middleware for Hyperapp that logs the name of each action as it is dispatched. This is particularly useful for debugging the flow and order of actions within an application without modifying individual action definitions. ```javascript const logActionsMiddleware = dispatch => (action, payload) => { if (typeof action === 'function') { console.log('DISPATCH: ', action.name || action) } //pass on to original dispatch dispatch(action, payload) } ``` -------------------------------- ### Define Hyperapp Action to Toggle Highlight Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript snippet defines a Hyperapp action named `ToggleHighlight`. It's a pure function that takes the current state, creates a new state object, and flips the boolean value of the `highlight` property, leaving other state properties unchanged. Actions describe transformations of the application's state. ```JavaScript const ToggleHighlight = state => ({ ...state, highlight: !state.highlight }) ``` -------------------------------- ### Assign Hyperapp Action to Checkbox Onclick Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet demonstrates how to integrate a Hyperapp action with a UI element. By assigning the `ToggleHighlight` action directly to the `onclick` property of an input checkbox, Hyperapp automatically dispatches this action when the checkbox is clicked, triggering a state update and subsequent DOM re-render. ```JavaScript h("input", { type: "checkbox", checked: state.highlight, onclick: ToggleHighlight, }) ``` -------------------------------- ### Implement Conditional Rendering of Bio in Hyperapp View Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This Hyperapp view snippet demonstrates conditional rendering using the logical `&&` operator. The `div` displaying `state.bio` will only be rendered if `state.bio` is a truthy value (i.e., not empty). This allows the UI to dynamically show or hide the bio section based on its presence in the state. ```JavaScript state => h("main", {}, [ ...state.names.map((name, index) => person({ name, highlight: state.highlight[index], ontoggle: [ToggleHighlight, index], selected: state.selected === index, onselect: [Select, index], })), state.bio && // <--- h("div", { class: "bio" }, text(state.bio)), // <--- ]) ``` -------------------------------- ### Using `text()` with Dynamic State Content Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/text.md Shows how `text()` can be effectively used to display dynamic content sourced from the application's current state. This example demonstrates embedding a message from `state.message` into a paragraph VNode, allowing for reactive UI updates. ```js h("p", {}, text(state.message)) ``` -------------------------------- ### Drawing SVG with Hyperapp and @hyperapp/svg Source: https://github.com/jorgebucaran/hyperapp/blob/main/packages/svg/README.md This example demonstrates how to use `@hyperapp/svg` to draw SVG elements like circles and reuse them with `use` tags within a Hyperapp application. It sets up a basic Hyperapp `app` with a `view` function that renders an SVG container with multiple shapes, making use of the library's functional approach to SVG. ```html ``` -------------------------------- ### Hyperapp Select Action Using Reusable `fetchJson` Effect Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet demonstrates how to use the reusable `fetchJson` effecter within the `Select` action in Hyperapp. The action now returns a tuple containing the new state and an "effect" (a tuple of `[effecter, options]`). This pattern cleanly separates the state update logic from the side effect execution, making the code more modular and maintainable. ```JavaScript const Select = (state, selected) => [ {...state, selected}, [ fetchJson, { url: "https://jsonplaceholder.typicode.com/posts/" + state.ids[selected], action: GotBio, } ] ] ``` -------------------------------- ### Hyperapp Select Action Returning an Effecter for Side Effects Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet demonstrates the correct way to handle side effects in Hyperapp actions. Instead of directly performing the fetch, the `Select` action now returns a tuple: the new state and an "effecter" function. Hyperapp will call this function, allowing asynchronous operations like `fetch` to run without blocking the state update. ```JavaScript const Select = (state, selected) => [ {...state, selected}, () => fetch("https://jsonplaceholder.typicode.com/users/" + state.ids[selected]) .then(response => response.json()) .then(data => { console.log("Got data: ", data) /* now what ? */ }) ] ``` -------------------------------- ### Using Custom Event Effecter in Hyperapp Application Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/effects.md Illustrates how to integrate and use the `emit` custom effecter within a Hyperapp application. This example shows a button that, when clicked, triggers the `emit` effect to dispatch an 'outgoing' custom event with a specific message, demonstrating inter-application communication. ```JavaScript import { h, text, app } from "hyperapp" import { emit } from "./fx" app({ view: () => h("main", {}, [ h( "button", { onclick: (state) => [ state, emit("outgoing", { message: "hello" }) ], }, text("Send greetings") ), ]), node: document.querySelector("main"), }) ``` -------------------------------- ### Update Hyperapp Person Component for Selection and Click Handling Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript snippet modifies the `person` component to visually indicate selection and handle click events. It dynamically applies a `selected` CSS class based on `props.selected` and assigns `props.onselect` to the `onclick` event handler of the main `div`, allowing the entire component to trigger a selection action. ```js const person = props => h("div", { class: { person: true, highlight: props.highlight, selected: props.selected, // <--- }, onclick: props.onselect, // <--- }, [ h("p", {}, text(props.name)), h("input", { type: "checkbox", checked: props.highlight, onclick: props.ontoggle, }), ]) ``` -------------------------------- ### Conditional Effects - Less Optimal Approach (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/effects.md An example of conditionally adding effects to an action's return value, demonstrating a less optimal pattern where the return type (state or state with effects) is conditionally determined. This can lead to more complex logic for handling the return value. ```JavaScript const DoIt = (state) => { let transition = { ...state, value: "MacGuffin" } if (state.eating) { transition = [transition, log("eating")] } if (state.drinking) { transition = Array.isArray(transition) ? [...transition, log("drinking")] : [transition, log("drinking")] } return transition } ``` -------------------------------- ### Define Hyperapp Action to Toggle Highlight State by Index Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This JavaScript action, `ToggleHighlight`, demonstrates how to update a specific item's highlight status within the application state. It receives the current `state` and an `index` payload, creates a shallow copy of the `highlight` array, flips the boolean value at the given index, and returns a new state object with the updated array, ensuring immutability. ```js const ToggleHighlight = (state, index) => { // make shallow clone of original highlight array let highlight = [...state.highlight] // flip the highlight value of index in the copy highlight[index] = !highlight[index] // return shallow copy of our state, replacing // the highlight array with our new one return { ...state, highlight} } ``` -------------------------------- ### Conditional Effects - Best Practice with Falsy Values (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/effects.md The most concise and idiomatic way to conditionally include effects in Hyperapp, leveraging the fact that falsy values in the effects array are ignored. This example shows how `state.eating && log('eating')` will only add the effect if `state.eating` is true, resulting in cleaner code. ```JavaScript const DoItBest = (state) => [ { ...state, value: "MacGuffin" }, state.eating && log("eating"), state.drinking && log("drinking"), ] ``` -------------------------------- ### Pass Selection State and Action to Hyperapp Person Component Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This snippet shows how to pass selection-related properties and actions to a `person` component in Hyperapp. It includes a `selected` boolean property (derived from the current state's `selected` index) and an `onselect` action tuple `[Select, index]`, enabling the component to react to selection events and update the global state. ```js person({ name, highlight: state.highlight[index], ontoggle: [ToggleHighlight, index], selected: state.selected === index, // <---- onselect: [Select, index], // <---- }) ``` -------------------------------- ### Hyperapp Subscriber: Problematic Cleanup with Destructured Props Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/subscriptions.md This example highlights a 'gotcha' where destructuring `props` (e.g., `{ action, type }`) in a subscriber can lead to issues in the cleanup function. The closure captures the `action` reference at the time of creation, meaning subsequent updates to the action will not be reflected, potentially causing incorrect dispatches during cleanup. ```javascript const listenToEvent = (dispatch, { action, type }) => { const listener = (event) => requestAnimationFrame(() => dispatch(action, event.detail)) addEventListener(type, listener) return () => { removeEventListener(type, listener) dispatch(action, "cleaned-up") // <-- uh, oh! } } ``` -------------------------------- ### Handle Checkbox Click with Event Propagation Stop and Action Chaining in Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/tutorial.md This Hyperapp snippet shows how to handle a checkbox click event by first stopping its DOM propagation and then dispatching another action. The `onclick` handler is defined as an intermediate action that calls `event.stopPropagation()` and then returns `props.ontoggle`, effectively chaining the original action after preventing the event from bubbling up. ```js h("input", { type: "checkbox", checked: props.highlight, onclick: (_, event) => { event.stopPropagation() return props.ontoggle }, }) ``` -------------------------------- ### Ill-formed Asynchronous Hyperapp Effecter Example Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/effects.md Presents an example of an ill-formed asynchronous effecter. While it uses `requestAnimationFrame`, the `dispatch` call is nested within the callback, which might not always align perfectly with Hyperapp's repaint cycle if `response.json()` is also asynchronous or if the state update logic is complex. ```JavaScript // This effecter is ill-formed. const runBrotherhood = async (dispatch, payload) => { const response = await fetch(payload.lookForKaneHere) const kaneLives = response.json() requestAnimationFrame(() => { dispatch((state) => ({ ...state, message: kaneLives ? "One vision! One purpose!" : "", })) }) } ``` -------------------------------- ### Hyperapp `init` Option: State with Effects (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/app.md Illustrates initializing the application state along with a list of effects to be run after the state is set, useful for side effects like logging or data loading. ```JavaScript app({ init: [ { loading: true }, log("Loading..."), load("myUrl?init", DoneAction), ], // ... }) ``` -------------------------------- ### Applying Inline CSS Styles to Hyperapp VNodes Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/h.md Demonstrates how to apply inline CSS styles to a Hyperapp VNode using the `style` prop. The `style` prop accepts an object where keys are CSS property names (camelCase or quoted for hyphenated names) and values are the corresponding CSS property values. This example sets background color, text color, display, and font-weight. ```js h( "span", { style: { backgroundColor: "white", color: "blue", display: "inline-block", "font-weight": "bold", }, }, text("+\"") ) ``` -------------------------------- ### Hyperapp `init` Option: Action with Payload Initialization (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/app.md Shows how to initialize the application by running a specific action with an associated payload, allowing for dynamic initial state based on input. ```JavaScript const SetCounter = (_state, n) => ({ counter: n }) app({ init: [SetCounter, 10], // ... }) ``` -------------------------------- ### Hyperapp `init` Option: Action Initialization (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/app.md Demonstrates initializing the application by running a predefined action, which can be reused later. In this case, the state passed to the action is `undefined`. ```JavaScript const Reset = (_state) => ({ counter: 0 }) app({ init: Reset, // ... }) ``` -------------------------------- ### Effect Signature Definition in Hyperapp Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/effects.md Defines the signature for an Effect in Hyperapp, showing it can be an `EffecterFn` or a tuple of `EffecterFn` and `Payload`. This signature guides how effects are structured and interpreted by the Hyperapp runtime. ```Elm Effect : EffecterFn | [EffecterFn, Payload] ``` -------------------------------- ### Ill-formed JavaScript Effecter for DOM Manipulation Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/effects.md Demonstrates an example of an ill-formed effecter in JavaScript. This snippet is problematic because it tightly couples the effecter to the application's state structure and hard-codes a specific DOM element ID, limiting its reusability and flexibility. ```JavaScript // This effecter is ill-formed. const runHarvest = (dispatch, _payload) => { const tiberium = document.getElementById("tiberium") dispatch((state) => ({ ...state, tiberium })) } ``` -------------------------------- ### Hyperapp Middleware: Enforce Immutable State Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/architecture/dispatch.md An example of a Hyperapp middleware that enforces state immutability using JavaScript Proxies. This middleware prevents accidental mutations of the state object during development, throwing an error if a modification is attempted. ```javascript // a proxy prohibiting mutation const immutableProxy = o => { if (o===null || typeof o !== 'object') return o return new Proxy(o, { get(obj, prop) { return immutableProxy(obj[prop]) }, set(obj, prop) { throw new Error(`Can not set prop ${prop} on immutable object`) } }) } export const immutableMiddleware = stateMiddleware(state => immutableProxy(state)) ``` -------------------------------- ### Hyperapp `init` Option: Direct State Initialization (JavaScript) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/app.md Shows how to initialize the application state directly using the `init` property, setting an initial value for the state object. ```JavaScript app({ init: { counter: 0 }, // ... }) ``` -------------------------------- ### Advanced Class Assignment with h() class prop (Recursive Array) Source: https://github.com/jorgebucaran/hyperapp/blob/main/docs/api/h.md Presents a complex example of the `class` property using a recursive array structure, allowing for nested arrays and conditional class application based on state. ```JavaScript h("input", { type: "range", class: [ { dragonzord: state.green && !state.white }, "mastodon", state.pink && "pterodactyl", [ { triceratops: state.blue }, "sabretooth-tiger", state.red && "tyrannosaurus", ], ], }) ```