### DOM Elements for app.mount() Source: https://context7.com/selfawarestudio/picoapp/llms.txt Example HTML elements with `data-component` and `data-util` attributes, demonstrating how picoapp components can be bound to specific elements. ```html
...
``` -------------------------------- ### Install picoapp with npm Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Install the picoapp library using npm. This command adds picoapp as a dependency to your project. ```bash npm i picoapp --save ``` -------------------------------- ### Add Components Dynamically with Picoapp Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Use `app.add` to include components, including asynchronously loaded ones. The example shows adding a `lazyImage` component. ```javascript app.add({ lazyImage: component(context => {}) }); ``` -------------------------------- ### Define Picoapp Plugins Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Extend the component API by passing a function to `app.use`. This function receives the node and returns an object to be merged into the component's context. The example adds a `props` object parsed from `data-props`. ```javascript app.use(node => { const props = JSON.parse(node.dataset.props || "{}"); return { props }; }); ``` -------------------------------- ### Access Plugin Properties in Picoapp Components Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Components can access properties exposed by plugins through the `ctx` object. The example shows accessing `ctx.props` to get image data. ```javascript const foo = component(node, ctx) => { const { images = [] } = ctx.props console.log(`start preloading ${images.length} images...`) }) ``` -------------------------------- ### Emit state-updating events Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Use `ctx.emit()` to trigger state changes. Passing an object merges it into the global state, and listeners receive the updated state. This example increments a counter. ```javascript export default component((node, ctx) => { ctx.on("incremenent", state => { node.innerHTML = `I've been clicked ${state.count} times`; }); node.onclick = () => { ctx.emit("increment", { count: ctx.getState().count + 1 }); }; }); ``` -------------------------------- ### Initialize picoapp with components Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Import your custom components and instantiate picoapp by passing them as an object. This sets up the application to manage these components. ```javascript import { picoapp } from "picoapp"; import button from "./button.js"; const app = picoapp({ button }); ``` -------------------------------- ### Initialize Components with app.mount() Source: https://context7.com/selfawarestudio/picoapp/llms.txt Scan the DOM for elements with data attributes and instantiate components. You can specify custom attribute names for different component types. ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({ slider: component((node, ctx) => { console.log("Slider initialized on", node); return () => console.log("Slider destroyed"); }), lazyImage: component((node, ctx) => { const src = node.dataset.src; node.src = src; }) }); // Mount using default data-component attribute app.mount(); // Mount using multiple custom attributes app.mount(["data-component", "data-util", "data-widget"]); ``` -------------------------------- ### Picoapp - Create Application Instance Source: https://context7.com/selfawarestudio/picoapp/llms.txt Creates the main picoapp instance that manages components, state, and the event bus. Accepts component definitions, initial state, and plugins. ```APIDOC ## picoapp - Create Application Instance Creates the main picoapp instance that manages components, state, and the event bus. The function accepts an object of component definitions, optional initial state, and an optional array of plugins. ### Method `picoapp(components, initialState, plugins)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { picoapp } from "picoapp"; import button from "./components/button.js"; import modal from "./components/modal.js"; // Create app with components and initial state const app = picoapp( { button, modal }, { count: 0, isOpen: false } ); // Access current state console.log(app.getState()); // { count: 0, isOpen: false } // Subscribe to events app.on("increment", (state) => { console.log("Count is now:", state.count); }); // Emit events with state updates app.emit("increment", { count: 1 }); // Update state without emitting events app.hydrate({ isOpen: true }); // Mount all components found in DOM app.mount(); // Unmount components (cleanup event listeners) app.unmount(); ``` ### Response #### Success Response (200) - **app** (object) - The initialized picoapp instance with methods for state management, event handling, and component lifecycle. #### Response Example ```json { "app": { "getState": "function", "setState": "function", "on": "function", "off": "function", "emit": "function", "hydrate": "function", "mount": "function", "unmount": "function" } } ``` ``` -------------------------------- ### Create picoapp Instance Source: https://context7.com/selfawarestudio/picoapp/llms.txt Use this to create the main picoapp instance. It manages components, state, and events. Pass component definitions, initial state, and plugins. ```javascript import { picoapp } from "picoapp"; import button from "./components/button.js"; import modal from "./components/modal.js"; // Create app with components and initial state const app = picoapp( { button, modal }, { count: 0, isOpen: false } ); // Access current state console.log(app.getState()); // { count: 0, isOpen: false } // Subscribe to events app.on("increment", (state) => { console.log("Count is now:", state.count); }); // Emit events with state updates app.emit("increment", { count: 1 }); // Update state without emitting events app.hydrate({ isOpen: true }); // Mount all components found in DOM app.mount(); // Unmount components (cleanup event listeners) app.unmount(); ``` -------------------------------- ### app.mount() - Initialize Components Source: https://context7.com/selfawarestudio/picoapp/llms.txt Scans the DOM for elements with data attributes and instantiates corresponding components. Accepts optional custom attribute names for different component types. ```APIDOC ## app.mount() - Initialize Components Scans the DOM for elements with data attributes and instantiates corresponding components. Accepts optional custom attribute names for different component types. ### Method `app.mount(customAttributes)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({ slider: component((node, ctx) => { console.log("Slider initialized on", node); return () => console.log("Slider destroyed"); }), lazyImage: component((node, ctx) => { const src = node.dataset.src; node.src = src; }) }); // Mount using default data-component attribute app.mount(); // Mount using multiple custom attributes app.mount(["data-component", "data-util", "data-widget"]); ``` ### Response #### Success Response (200) - **mountedComponents** (array) - An array of the component instances that were successfully mounted. #### Response Example ```json { "mountedComponents": [ "sliderInstance1", "lazyImageInstance1" ] } ``` ``` -------------------------------- ### Mount picoapp components to the DOM Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md After initializing picoapp, call the `mount()` method to discover and instantiate components bound to DOM elements. ```javascript app.mount(); ``` -------------------------------- ### Mount Components by Attribute with Picoapp Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Configure `app.mount` to scan the DOM for specific data attributes (e.g., `data-component`, `data-util`) and initialize their corresponding JavaScript modules. ```javascript app.mount(["data-component", "data-util"]); ``` -------------------------------- ### Register Components Dynamically with Picoapp Source: https://context7.com/selfawarestudio/picoapp/llms.txt Use `app.add()` to register new components after the initial instance creation. This is useful for lazy-loading or conditional component registration. Remember to call `app.mount()` after adding new components. ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({ header: component((node, ctx) => { console.log("Header initialized"); }) }); app.mount(); // Dynamically import and add components async function loadGallery() { const { default: gallery } = await import("./components/gallery.js"); app.add({ gallery, lightbox: component((node, ctx) => { node.onclick = () => ctx.emit("openLightbox"); }) }); // Mount newly added components app.mount(); } loadGallery(); ``` -------------------------------- ### Initialize picoapp with state Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Provide an initial state object when creating a picoapp instance. This state can be accessed and modified by components via the context. ```javascript const app = picoapp({ button }, { count: 0 }); ``` -------------------------------- ### Emit and Listen to Events with Picoapp Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Use `app.emit` to trigger events and `app.on` to listen for them. The event listener receives the state as an argument. ```javascript app.emit("event", { data: "global" }); app.on("event", state => {}); ``` -------------------------------- ### Subscribe and Emit Events with Picoapp Source: https://context7.com/selfawarestudio/picoapp/llms.txt Use `app.on` to subscribe to events and `app.emit` to trigger them. Supports single, multiple, wildcard, and property-keyed subscriptions. State can be merged or updated using functions. ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({}, { user: null, theme: "light" }); // Single event subscription app.on("login", (state) => { console.log("User logged in:", state.user); }); // Multiple event subscription app.on(["login", "logout"], (state) => { updateUI(state); }); // Wildcard - fires on any state change app.on("*", (state) => { localStorage.setItem("appState", JSON.stringify(state)); }); // Property-keyed subscription app.on("theme", ({ theme }) => { document.body.className = theme; }); // Emit with object (merges into state) app.emit("login", { user: { name: "John" } }); // Emit with function (access previous state) app.emit("updateTheme", (state) => ({ theme: state.theme === "light" ? "dark" : "light" })); // Update state silently without emitting app.hydrate({ user: { name: "John", role: "admin" } }); ``` -------------------------------- ### Manage Global State with Picoapp Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Initialize or update the global state using `app.hydrate` and retrieve the current state with `app.getState`. ```javascript app.hydrate({ count: 5 }); ``` ```javascript app.getState(); // { count: 5 } ``` -------------------------------- ### Subscribe to specific or wildcard events Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md picoapp, leveraging evx, supports advanced event subscriptions including specific properties, multiple properties, and wildcards for comprehensive state change handling. ```javascript ctx.on(["count", "otherProp"], state => {}); // fires on `count` & `otherProp` ctx.on("*", state => {}); // fires on all state updates ctx.on("someProp", ({ someProp }) => {}); // fires on all someProp updates ``` -------------------------------- ### Register Plugins to Extend Component Context Source: https://context7.com/selfawarestudio/picoapp/llms.txt Use `app.use()` to register plugins that extend the component context. Plugins receive the DOM node and evx instance, returning an object that is merged into the context provided to components. This is useful for parsing data attributes or collecting referenced elements. ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({ productCard: component((node, ctx) => { // Access plugin-provided props and refs console.log(ctx.props); // { id: "123", price: 29.99 } console.log(ctx.refs.image); // element }) }); // Plugin to parse data-props JSON attribute app.use((node) => ({ props: JSON.parse(node.dataset.props || "{}") })); // Plugin to collect data-ref elements app.use((node) => { const refs = {}; node.querySelectorAll("[data-ref]").forEach((el) => { refs[el.dataset.ref] = el; }); return { refs }; }); app.mount(); ``` ```html
``` -------------------------------- ### Picoapp Error Handling for Components Source: https://context7.com/selfawarestudio/picoapp/llms.txt Picoapp catches errors thrown during component mounting and emits them as 'error' events. This prevents a single failing component from crashing the entire application. Subscribe to the 'error' event to handle these errors gracefully. ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({ buggyComponent: component((node, ctx) => { throw new Error("Something went wrong!"); }), stableComponent: component((node, ctx) => { console.log("This still initializes"); }) }); // Subscribe to errors app.on("error", ({ error }) => { console.error("Component error:", error.message); // Send to error tracking service errorTracker.capture(error); }); app.mount(); // Logs: "Component error: Something went wrong!" // Logs: "This still initializes" ``` -------------------------------- ### Define a picoapp component Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Create a reusable component by importing the `component` function from picoapp. The component function receives the DOM node and context, and can define its behavior, such as handling click events. ```javascript import { component } from "picoapp"; export default component((node, ctx) => { let count = 0; node.onclick = () => { node.innerHTML = `I've been clicked ${++count} times`; }; }); ``` -------------------------------- ### Re-mount components after PJAX transition Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md In scenarios with PJAX, unmount existing components and then mount new ones after each route transition to ensure the application state is correctly reset and updated. ```javascript router.on("after", state => { app.unmount(); // cleanup app.mount(); // init new components }); ``` -------------------------------- ### Define a Component with picoapp Source: https://context7.com/selfawarestudio/picoapp/llms.txt Wrap your component function with `component` to manage subscriptions and unmount handlers. Components receive the DOM node and a context object for state and events. ```javascript import { component } from "picoapp"; export default component((node, ctx) => { let count = ctx.getState().count || 0; // Subscribe to events - automatically cleaned up on unmount ctx.on("increment", (state) => { count = state.count; node.innerHTML = `Clicked ${count} times`; }); // Handle user interactions node.onclick = () => { ctx.emit("increment", (state) => ({ count: state.count + 1 })); }; // Return unmount handler for cleanup return (node) => { node.onclick = null; console.log("Component unmounted"); }; }); ``` -------------------------------- ### Listen for component errors Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Subscribe to the 'error' event on the picoapp instance to catch and handle any errors thrown by components during mounting or operation. ```javascript app.on("error", ({ error }) => { // do something with error }); ``` -------------------------------- ### Bind Component to DOM Element Source: https://context7.com/selfawarestudio/picoapp/llms.txt Use a `data-component` attribute on an HTML element to bind a picoapp component to it. ```html ``` -------------------------------- ### Define an unmount handler for a component Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Components can return a cleanup function that picoapp will execute when the component is unmounted. This is crucial for removing event listeners or other resources. ```javascript import { component } from "picoapp"; export default component((node, ctx) => { ctx.on("incremenent", state => { node.innerHTML = `I've been clicked ${state.count} times`; }); function handler(e) { ctx.emit("increment", { count: ctx.getState().count + 1 }); } node.addEventListener("click", handler); return node => { node.removeEventListener("click", handler); }; }); ``` -------------------------------- ### Cleanup Components with app.unmount() Source: https://context7.com/selfawarestudio/picoapp/llms.txt Destroy mounted components that have an unmount handler, removing event subscriptions. Components without unmount handlers persist. Useful for global elements and PJAX transitions. ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({ // This component will be unmounted pageContent: component((node, ctx) => { ctx.on("update", () => node.classList.add("updated")); return () => node.classList.remove("updated"); }), // This component persists (no unmount handler) globalNav: component((node, ctx) => { ctx.on("menuToggle", (state) => { node.classList.toggle("open", state.menuOpen); }); }) }); app.mount(); // Use with PJAX router for page transitions router.on("after", () => { app.unmount(); // Cleanup page-specific components app.mount(); // Initialize new components }); ``` -------------------------------- ### Unmount picoapp components Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Call the `unmount()` method on the picoapp instance to destroy all mounted components and clean up their associated event listeners and subscriptions. ```javascript app.unmount(); ``` -------------------------------- ### app.unmount() - Cleanup Components Source: https://context7.com/selfawarestudio/picoapp/llms.txt Destroys all mounted components that define an unmount handler, removing event subscriptions. Components without unmount handlers persist across calls. ```APIDOC ## app.unmount() - Cleanup Components Destroys all mounted components that define an unmount handler, removing event subscriptions. Components without unmount handlers persist across calls, useful for global elements. ### Method `app.unmount()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { picoapp, component } from "picoapp"; const app = picoapp({ // This component will be unmounted pageContent: component((node, ctx) => { ctx.on("update", () => node.classList.add("updated")); return () => node.classList.remove("updated"); }), // This component persists (no unmount handler) globalNav: component((node, ctx) => { ctx.on("menuToggle", (state) => { node.classList.toggle("open", state.menuOpen); }); }) }); app.mount(); // Use with PJAX router for page transitions router.on("after", () => { app.unmount(); // Cleanup page-specific components app.mount(); // Initialize new components }); ``` ### Response #### Success Response (200) - **unmountedCount** (integer) - The number of components that were successfully unmounted. #### Response Example ```json { "unmountedCount": 5 } ``` ``` -------------------------------- ### Emit state updates using a function Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md When emitting events, you can pass a function to `ctx.emit()` to calculate the new state based on the previous state. This ensures atomic state updates. ```javascript ctx.emit("increment", state => { return { count: state.count + 1 }; }); ``` -------------------------------- ### component - Define a Component Source: https://context7.com/selfawarestudio/picoapp/llms.txt Wraps a component function to properly manage event subscriptions and unmount handlers. Components receive the DOM node and a context object with state management and event methods. ```APIDOC ## component - Define a Component Wraps a component function to properly manage event subscriptions and unmount handlers. Components receive the DOM node and a context object with state management and event methods. ### Method `component(componentFunction)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { component } from "picoapp"; export default component((node, ctx) => { let count = ctx.getState().count || 0; // Subscribe to events - automatically cleaned up on unmount ctx.on("increment", (state) => { count = state.count; node.innerHTML = `Clicked ${count} times`; }); // Handle user interactions node.onclick = () => { ctx.emit("increment", (state) => ({ count: state.count + 1 })); }; // Return unmount handler for cleanup return (node) => { node.onclick = null; console.log("Component unmounted"); }; }); ``` ### Response #### Success Response (200) - **componentWrapper** (function) - A function that wraps the provided component logic, enabling picoapp's lifecycle and event management. #### Response Example ```json { "componentWrapper": "function" } ``` ``` -------------------------------- ### Consume state within a component Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Access the global state within a component using `ctx.getState()`. This allows components to read shared data. ```javascript export default component((node, ctx) => { // ctx.getState().count }); ``` -------------------------------- ### Hydrate state without emitting events Source: https://github.com/selfawarestudio/picoapp/blob/master/README.md Use `ctx.hydrate()` to directly update the state without triggering any event listeners. This is useful for setting initial or background state changes. ```javascript export default component((node, ctx) => { ctx.hydrate({ count: 12 }); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.