### DreamlandJS Basic App Structure (JavaScript) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/getting-started.mdx An example of a basic DreamlandJS application using `html` tagged template literals for rendering components. It demonstrates state management with `this.count` and event handling for a button click. The `use` function is used to render reactive values. ```javascript import { css } from "dreamland/core"; import { html } from "dreamland/js-runtime"; function App() { this.count = 0; return html`

:3

`; }; App.style = css` :scope { border: 4px dashed cornflowerblue; padding: 1em; } `; document.querySelector("#app").replaceWith(html`<${App} />`); ``` -------------------------------- ### JSX Syntax Example in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/1.-Basic-HTML Provides an example of using JSX syntax within DreamlandJS for creating an interactive button with a click counter. This syntax requires a preprocessor like tsc, babel, or esbuild. ```jsx return ( ); ``` -------------------------------- ### DreamlandJS Vite Plugin Configuration (vite.config.js) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/getting-started.mdx This JavaScript configuration for Vite sets up the `jsxPlugin` from `dreamland/vite`. This plugin automatically configures Vite's esbuild options to use DreamlandJS's JSX transform (`jsx: "automatic"`, `jsxImportSource: "dreamland"`). ```javascript import { jsxPlugin } from "dreamland/vite"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [jsxPlugin()], }); ``` -------------------------------- ### DreamlandJS Importmap Configuration (HTML) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/getting-started.mdx This HTML script tag defines an importmap for DreamlandJS, specifying the paths for core, JS runtime, and router modules. This is necessary for DreamlandJS to import itself internally when using pure JavaScript without a bundler. ```html ``` -------------------------------- ### DreamlandJS Vite esbuild Configuration (JSON) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/getting-started.mdx This JSON object represents the esbuild configuration within Vite when using the DreamlandJS `jsxPlugin`. It specifies the JSX transform to be `automatic` and sets the `jsxImportSource` to `dreamland`, enabling efficient JSX processing for DreamlandJS components. ```json { esbuild: { jsx: "automatic", jsxImportSource: "dreamland" } } ``` -------------------------------- ### Pure JavaScript Setup with Import Maps for dreamland.js Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt Integrate dreamland.js into plain JavaScript projects without a build step using import maps in HTML. The `html` tagged template function from `dreamland/js-runtime` is used for creating components. ```html
``` -------------------------------- ### Transform Pointer Values with map, zip, and, or in DreamlandJS Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt Demonstrates the use of map for value transformation, zip for combining pointers, and and/or for conditional logic. It also shows mapEach for transforming array elements. This example requires the 'dreamland/core' module. ```tsx import { createState, type Pointer, NO_CHANGE } from "dreamland/core"; let state = createState({ count: 0, firstName: "John", lastName: "Doe", temperature: 72, isMetric: false, items: ["a", "b", "c"] }); // map() - Transform pointer values let doubled = use(state.count).map((x) => x * 2); let greeting = use(state.firstName).map((name) => `Hello, ${name}!`); // map() with reverse function for two-way binding let tempDisplay = use(state.temperature).map( (f) => state.isMetric ? ((f - 32) * 5/9).toFixed(1) + "°C" : f + "°F", (str) => { const num = parseFloat(str); return isNaN(num) ? NO_CHANGE : num; } ); // zip() - Combine multiple pointers let fullName = use(state.firstName) .zip(use(state.lastName)) .map(([first, last]) => `${first} ${last}`); // Shorthand: pass multiple values to use() let fullNameAlt = use(state.firstName, state.lastName) .map(([first, last]) => `${first} ${last}`); // and() / or() - Conditional transformations let status = use(state.count) .map((x) => x > 10) .and("High count!") .or("Keep clicking..."); // mapEach() - Transform array elements let listItems = use(state.items).mapEach((item, i) =>
  • {item.toUpperCase()}
  • ); document.body.appendChild(

    Count: {use(state.count)} (doubled: {doubled})

    {greeting}

    Full name: {fullName}

    Temperature: {tempDisplay}

    Status: {status}

    ); ``` -------------------------------- ### Create store with custom async backing in TypeScript Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/features/stores.mdx This example shows how to create a store with a custom backing by providing an object with asynchronous `read` and `write` functions. This allows for integration with other storage solutions like IndexedDB or external APIs. ```typescript import { createStore } from "dreamland/core"; let backing = { async read(ident: string): Promise { // read from IDB or fetch externally... }, async write(ident: string, value: string): Promise { // write to IDB or post to server... }, }; export let settings = createStore( { color: "#FFFFFF", fontSize: 16, }, { ident: "settings", backing, autosave: "auto" } ); ``` -------------------------------- ### Component Lifecycle with this.mount Callback Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/2.-Components Illustrates using the `this.mount` callback within a component to execute code after the component is initialized. This example logs the component's root DOM element and then removes it. ```jsx function UselessComponent(){ this.mount = ()=>{ console.log(this.root) //
    hello!..... console.log("goodbye world!") this.root.remove(); } return (
    hello!
    ) } ``` -------------------------------- ### Programmatic Navigation with Dreamland Router Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/extras/router.mdx This example shows how to programmatically navigate between routes using the `router` export from `dreamland/router`. The `navigate` function changes the current route and updates the browser history. ```tsx import { router } from "dreamland/router"; router.navigate("/"); // sent to history ``` -------------------------------- ### Initialize a Chart Component with Client-Side Mounting Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/components.mdx This example shows how to initialize a chart component using the `mount` lifecycle method. The `mount` callback is executed on the client-side after the component's HTML is constructed. It's used here to instantiate a `Chart` object on a canvas element, with potential for updating the chart based on data changes. ```tsx function ChartView(this: FC) { this.cx.mount = () => { // mount the chart on the client once the canvas is constructed let chart = new Chart(this.root as HTMLCanvasElement, { /* ... */ }); // update the chart on data changes ... }; return ; }; ``` -------------------------------- ### DreamlandJS TypeScript Configuration (tsconfig.json) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/getting-started.mdx This JSON configuration for `tsconfig.json` enables the React JSX transform for DreamlandJS, setting `jsx` to `react-jsx` and `jsxImportSource` to `dreamland`. This is the recommended setup for using DreamlandJS with TypeScript. ```json { "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "dreamland" } } ``` -------------------------------- ### Create To-Do App with Dynamic Items in JSX/TSX Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/7.-Arrays Provides a complete example of a To-Do application using DreamlandJS components. It demonstrates how to manage a list of `ToDoItem` components dynamically, including adding new items and removing existing ones by filtering the `items` array. ```tsx const ToDoItem: Component<{ title: string, remove: () => void }, {}> = function() { return (
    {this.title}
    ) } const ToDoList: Component<{ items: ComponentElement[], text: string }, {}> = function() { this.items = []; return (
    ) } ``` -------------------------------- ### Combining Multiple Pointers with zip() in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/reactivity.mdx Demonstrates how to combine the values of multiple pointers into a single pointer using `zip()`. This is useful for scenarios where a derived state depends on several other state variables. The example shows calculating the sum and average of three counters. ```tsx let counters = createState({ one: 0, two: 1, three: 2, }); let sum = use(counters.one) .zip(use(counters.two), use(counters.three)) .map(([one, two, three]) => one + two + three); let average = use(counters.one, counters.two, counters.three).map( ([one, two, three]) => (one + two + three) / 3 ); ``` -------------------------------- ### Update Reactivity Listeners Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx The `useChange(x, callback)` function has been replaced by `use(x).listen(callback)`. This provides a more streamlined way to listen for changes in reactive state. ```tsx // old export const NavBar: Component< {}, { pages: Record }>; path: string; } > = function () { this.path = new URL(document.URL).pathname; useChange(this.path, () => { let url = new URL(document.URL); url.pathname = this.path; if (window.location.toString() != url.toString()) { window.location.assign(url); } }); return
    Nav Bar
    ; }; // new export function NavBar(this: FC<{}, { pages: Record; path: string; }>) { this.path = new URL(document.URL).pathname; use(this.path).listen((path) => { let url = new URL(document.URL); url.pathname = path; if (window.location.toString() != url.toString()) { window.location.assign(url); } }); return
    Nav Bar
    ; }; ``` -------------------------------- ### DreamlandJS Old JSX Transform Configuration (tsconfig.json) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/getting-started.mdx This `tsconfig.json` configuration enables the older JSX transform for DreamlandJS, specifying `jsxFactory` as `h` and `jsxFragmentFactory` as `Fragment`. If using this method, you must manually import `h` and `Fragment` from `dreamland/core`. ```json { "compilerOptions": { "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment" } } ``` -------------------------------- ### Client-Side Routing with DreamlandJS Router Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt Implements client-side routing using the DreamlandJS Router component. Supports nested routes, dynamic URL parameters, and programmatic navigation. It includes examples of defining routes, page components, and handling navigation events. ```tsx import { type FC } from "dreamland/core"; import { Router, Route, Link, router } from "dreamland/router"; // Page components function HomePage(this: FC) { return

    Home

    Welcome!

    ; } function UserPage(this: FC<{ id?: string; outlet?: HTMLElement }>) { return (

    User: {use(this.id)}

    {use(this.outlet)}
    ); } function UserPosts(this: FC<{ id?: string }>) { return
    Posts for user {use(this.id)}
    ; } function UserSettings(this: FC<{ id?: string }>) { return
    Settings for user {use(this.id)}
    ; } function NotFound(this: FC<{ "*"?: string }>) { return

    404

    Path not found: {this["*"].toString()}

    ; } // App with router function App(this: FC) { return (
    {/* Index route (no path) */} } /> {/* Nested routes with layout */} }> } /> } /> } /> {/* Catch-all route */} } />
    ); } // Programmatic navigation document.body.appendChild(); // Navigate programmatically (after router mounts) setTimeout(() => { router.navigate("/users/789"); // Adds to history // router.route("/users/789"); // Changes route without history // Get all SSG-able routes for prerendering const ssgPaths = router.ssgables(); console.log("Prerenderable paths:", ssgPaths); }, 1000); ``` -------------------------------- ### Server-Side Rendering (SSR) with DreamlandJS and Vite Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt Configures server-side rendering using DreamlandJS SSR plugins with Vite. This setup supports hydration on the client and prerendering for static site generation. It includes configurations for server and client entry points, Vite, and a static HTML template. ```tsx // main-common.tsx - Shared app code import { type FC } from "dreamland/core"; import { Router, Route, router } from "dreamland/router"; function App(this: FC) { return (
    } /> } />
    ); } export function createApp(initialRoute?: string) { const app = ; if (initialRoute) router.route(initialRoute); return app; } ``` ```ts // main-server.ts - Server entrypoint import { render } from "dreamland/ssr/server"; import { createApp } from "./main-common"; export function renderApp(route: string) { return render(() => createApp(route)); } ``` ```ts // main-client.ts - Client entrypoint import { hydrate } from "dreamland/ssr/client"; import { createApp } from "./main-common"; hydrate(() => createApp()); ``` ```ts // vite.config.ts - Vite configuration import { jsxPlugin, devSsr } from "dreamland/vite"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [ jsxPlugin(), devSsr({ entry: "./src/main-server.ts" }) ] }); ``` ```html // index.html - HTML template with SSR markers // // // // // // // // // // ``` ```ts // prerender.js - Static site generation import { renderSsr } from "dreamland/vite"; import { writeFile, mkdir } from "fs/promises"; import { dirname, resolve } from "path"; const entry = await import("./dist-ssr/main-server.js"); const template = await readFile("./dist/index.html", "utf-8"); for (const [route, path] of router.ssgables()) { const html = await renderSsr(template, () => entry.renderApp(route)); const outPath = resolve("dist/static", path); await mkdir(dirname(outPath), { recursive: true }); await writeFile(outPath, html); console.log(`Prerendered: ${route} -> ${path}`); } ``` -------------------------------- ### Add DOM Event Listener with DreamlandJS 'on:' prefix Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/basic-html.mdx This example shows how to attach an event listener to an HTML element using the 'on:' prefix in DreamlandJS. It allows for concise event handling, such as triggering an alert on a button click. ```tsx ``` -------------------------------- ### Implement Dynamic Props and State Updates in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/components.mdx This example demonstrates DreamlandJS's dynamic props system where `Pointer` props are automatically proxied to the component's `this` value. Changes to the pointer update the component's state, and vice-versa. It includes a listener to update a `hint` property based on the length of the `text` input. ```tsx function Input(this: FC<{ title: string; text: string }, { hint: string }>) { this.hint = ""; use(this.text).listen((text) => { if (text.length < 3) this.hint = "too short!"; if (text.length > 12) this.hint = "too long!"; }); return (
    {this.title} {/* title won't change */} {use(this.hint)}
    ); }; ``` -------------------------------- ### Create Stateful Object and Basic Usage in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/reactivity.mdx Demonstrates how to create a stateful object using `createState` and bind it to UI elements. The `use` function creates a dynamic reference that automatically updates the DOM when the state changes. This example shows a counter that increments on button click and displays the current count. ```tsx import { createState, use } from "dreamland/core"; let state = createState({ count: 0, }); (self as any).state = state; document.body.appendChild(

    {use(state.count)}

    ); ``` -------------------------------- ### Update Reactive Mapping Syntax Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx The syntax for mapping reactive state has changed from `use(x, (x) => x)` to `use(x).map((x) => x)`. This offers a more functional approach to transforming reactive data. ```tsx // old
    {use(this.path, () => this.pages[this.path].page(this))}
    // new
    {use(this.path).map((path) => this.pages[path].page)}
    ``` -------------------------------- ### Transforming Pointer Values with map() in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/reactivity.mdx Illustrates how to transform the value of a pointer using the `map()` method. This is necessary when you want to derive a new value from the state or perform conditional rendering. The example shows how to display 'Even!' or 'Odd!' based on the current count. ```tsx
    { use(state.count).map((x) => x % 2 == 0 ? "Even!" : "Odd" ) /* <-- works! */ }
    ``` -------------------------------- ### Set Inline Styles on HTML Elements with DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/basic-html.mdx This example demonstrates two ways to set inline styles on HTML elements using DreamlandJS: directly with a CSS string or by passing a JavaScript object that conforms to CSSStyleDeclaration properties. ```tsx let regularStyle =
    ; let objectStyle =
    ; ``` -------------------------------- ### Update Conditional Rendering Syntax Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx The `$if(x, yes, no)` syntax for conditional rendering is replaced with `use(x).and(yes).or(no)`. This provides a more declarative way to handle conditional UI elements. ```tsx // old { $if(this.mobile, , ); } // new { use(this.mobile).and().or(); } ``` -------------------------------- ### Conditional Value Selection with andThen/or in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/reactivity.mdx Shows how to use `andThen` and `or` methods on a pointer to conditionally select between values or computed values based on a boolean or other condition. This is useful for toggling UI elements or styles. The example demonstrates setting CSS classes based on a `darkMode` setting and a `state` property. ```tsx let settings: Stateful<{ darkMode: boolean, state: "one" | "two" | null, }> = createState({ darkMode: true, state: null, }); let class = use(settings.darkMode).and("dark-mode").or("light-mode"); let state = use(settings.state).and((x) => "state-" + x).or("state-none"); ``` -------------------------------- ### Reactive Strings with `use` Template Tag (TSX) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/features/utilities.mdx Creates string pointers using the `use` template tag function, useful for text or class strings that require recalculation. This example shows its application within a TSX input element. ```tsx
    ``` -------------------------------- ### Creating Reactive State with createState in dreamland.js Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt The `createState` function generates a reactive proxy object for state management. Use the `use()` function to create pointers that track state changes and automatically update the DOM. This example demonstrates creating state, accessing it, and listening for changes. ```tsx import { createState, type Stateful } from "dreamland/core"; // Create reactive state let state = createState({ user: { name: "Alice", age: 25 }, items: ["apple", "banana", "cherry"], isLoggedIn: false }); // Access state normally console.log(state.user.name); // "Alice" state.user.age = 26; // Use in JSX - DOM updates automatically when state changes document.body.appendChild(

    Hello, {use(state.user.name)}!

    Age: {use(state.user.age)}

      {use(state.items).mapEach((item) =>
    • {item}
    • )}
    ); // Listen for changes use(state.user.name).listen((newName) => { console.log("Name changed to:", newName); }); // Trigger updates state.user.name = "Bob"; // DOM updates, listener fires state.items = [...state.items, "date"]; // List re-renders ``` -------------------------------- ### TypeScript Setup for dreamland.js JSX Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt Configure TypeScript to use dreamland's JSX factory by setting 'jsx' to 'react-jsx' and 'jsxImportSource' to 'dreamland' in tsconfig.json. Components are defined as functions returning JSX elements, with optional styling using the css tagged template literal. ```json // tsconfig.json { "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "dreamland" } } ``` ```tsx // App.tsx import { type FC, css } from "dreamland/core"; function App(this: FC) { this.count = 0; return (

    Welcome to dreamland!

    ); } App.style = css` :scope { padding: 1em; background: #f0f0f0; } button { padding: 0.5em 1em; cursor: pointer; } `; document.body.appendChild(); ``` -------------------------------- ### Component Syntax Revamp in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v0-1-x.mdx Demonstrates the shift from anonymous function assignments to proper function syntax for components. It highlights changes in generic arguments, the introduction of the `FC` type, and the relocation of `cx`, `root`, and `children` properties. The removal of `DLElement` and the updated `ComponentContext` are also noted. ```tsx // old const App: Component = function () { return (
    this text is red!
    ); }; App.style = css` :scope { height: 100vh; } .red { color: red; } `; // new function App(this: FC) { return (
    this text is red!
    ); }; App.style = css` :scope { height: 100vh; } .red { color: red; } `; ``` ```tsx // old let ChartCard: Component<{}, { chart: HTMLCanvasElement }> = function (cx) { cx.mount = () => { // mount the chart on the client once the canvas is constructed let chart = new Chart(this.chart as HTMLCanvasElement, { /* ... */ }); // update the chart on data changes ... } return (

    Chart

    ); }; // new function ChartCard(this: FC<{}, { chart: HTMLCanvasElement }>) { this.cx.mount = () => { // mount the chart on the client once the canvas is constructed let chart = new Chart(this.chart as HTMLCanvasElement, { /* ... */ }); // update the chart on data changes ... }; return (

    Chart

    ); }; ``` -------------------------------- ### Bidirectional Pointer Transformation with map() in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/reactivity.mdx Explains how to create a bidirectional transformation for a pointer using `map()` by providing both a forward and a reverse mapping function. This allows the pointer's value to be set and updated from the transformed value. The example converts a number to a string and back. ```tsx let stringCount = use(state.count).map( (x) => "" + x, (x) => +x ); stringCount.value = "5"; console.log(stringCount.value); // 5 ``` -------------------------------- ### Delegate Pattern for Child Component Interaction (TypeScript) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/features/utilities.mdx Demonstrates the delegate pattern in DreamlandJS for calling functions on child components without direct state exposure. Delegates have a `listen` function, simplifying communication between parent and child components. This example uses TypeScript for type safety. ```typescript import { createDelegate } from "dreamland/core"; function Ripples(this: FC<{ create: Delegate }>) { this.cx.mount = () => { this.create.listen((e: MouseEvent) => { // create ripple... }); }; return
    ; }; function Button(this: FC) { let ripple = createDelegate(); return (
    ); }; ``` -------------------------------- ### Mapping Each Element of an Array Pointer with mapEach in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/reactivity.mdx Explains how to use `mapEach` to transform each element of an array-like pointer. This is a convenient way to render lists of items where each item needs to be processed or converted into a UI element. The example shows mapping an array of strings to div elements. ```tsx let cards: Pointer = /* ... */; let cardEls = cards.mapEach(x =>
    card: {x}
    ); ``` -------------------------------- ### Dynamic Button Text and Conditional Input Rendering in JavaScript (JSX) Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/5.-Conditional-Rendering This JavaScript example demonstrates a common pattern in DreamlandJS for conditional rendering. It uses a button to toggle a boolean state (`showInput`) and updates the button's text dynamically using `use()`. The input field is rendered only when `showInput` is true, controlled by `$if(use(this.showInput))`. ```javascript function App(){ this.showInput = false; return (

    Conditional Rendering!

    {$if(use(this.showInput), )}
    ) } ``` -------------------------------- ### Implement Custom Handler with Immediate and Update Execution in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/8.-Custom-Handlers The `handle` function registers a callback that executes immediately and on subsequent data updates. It requires a reference pointer from `use` and a closure function. The example shows logging the updated value and binding an input element's value. ```jsx handle(use(this.text), () => { console.log("new value of this.text: ", this.text); }); return ``` -------------------------------- ### Update Inline Style Syntax Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx Inline styles now require CSS property names to be listed verbatim. For example, 'minWidth' must be written as '"min-width"'. ```tsx // old
    // new
    ``` -------------------------------- ### Create localStorage backed store in TypeScript Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/features/stores.mdx This snippet demonstrates how to create a store using `createStore` from 'dreamland/core' with `localStorage` backing. It initializes the store with default settings and configures autosave functionality. ```typescript import { createStore } from "dreamland/core"; export let settings = createStore( { color: "#FFFFFF", fontSize: 16, }, { ident: "settings", backing: "localstorage", autosave: "auto" } ); ``` -------------------------------- ### Replace Vite Plugin for DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx The 'vite-plugin-dreamland' is deprecated and replaced by 'dreamland/vite's jsxPlugin. This new plugin is specifically for non-TypeScript projects. ```ts // old import { defineConfig } from "vite"; import { dreamlandPlugin } from "vite-plugin-dreamland"; export default defineConfig({ plugins: [dreamlandPlugin()], }); // new import { jsxPlugin } from "dreamland/vite"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [jsxPlugin()], }); ``` -------------------------------- ### Update Imports from dreamland/core Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx Imports for core functionalities have moved from 'dreamland/dev' to 'dreamland/core'. This change consolidates essential components like css, createState, and FC. ```tsx // old import "dreamland/dev"; // or whatever // new import { css, createState, type FC } from "dreamland/core"; ``` -------------------------------- ### Reactivity API Update in DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v0-1-x.mdx Illustrates the change in the reactivity API for conditional rendering. The `andThen` method has been replaced with `and` and `or` for a more intuitive conditional logic flow. ```tsx // old { use(this.mobile).andThen(, ); } // new { use(this.mobile).and().or(); } ``` -------------------------------- ### Create a Sign-Up Form with Dynamic Input Components Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/components.mdx This snippet showcases a `SignUp` component that utilizes the previously defined `Input` component. It manages user and password state, which are dynamically passed to the `Input` components. When the submit button is clicked, the input fields are cleared, demonstrating the two-way data binding provided by DreamlandJS's state system. ```tsx function SignUp(this: FC<{}, { user: string; password: string }>) { const submit = () => { // clear the inputs this.user = ""; this.password = ""; }; return (

    Sign Up

    ); }; ``` -------------------------------- ### Importing DreamlandJS Modules Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/pages/main.mdx This snippet demonstrates how to import core functionalities from the dreamlandjs library, including routing, bundling utilities, and local components. It sets up the necessary imports for building a DreamlandJS application. ```javascript import { Link } from "dreamland/router"; import { dl, ssr } from "dl:bundle"; import { Columns } from "./main/helpers"; import { BundleSize } from "./main/frameworks"; import { ExamplesCarousel } from "./main/examples"; ``` -------------------------------- ### Access Component Context via 'this.cx' Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx Access to component context, previously done via `this.`, is now accessed through `this.cx.`. Additionally, `JSX.Element` has been replaced with `ComponentChild` for type safety. ```tsx // old export const Row: Component<{}, { children: JSX.Element }> = function () { this.mount = () => { (this.root.children[0] as HTMLDivElement).addEventListener( "mouseenter", () => { console.log("enter!"); } ); }; return
    {this.children}
    ; }; // new export function Row(this: FC<{ children: ComponentChild }, {}>) { this.cx.mount = () => { (this.children[0] as HTMLDivElement).addEventListener( "mouseenter", () => { console.log("enter!"); } ); }; return
    {this.children}
    ; }; ``` -------------------------------- ### Manually Creating Stateful Objects in JavaScript Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/3.-Reactivity Shows how to manually create a stateful object using `stateful()` for nested data structures. References to properties within the stateful object (e.g., `state.a`, `state.b.c`) update reactively when their values change. ```javascript let state = stateful({ a: 0, b: stateful({ c: 1 }) }) let elm =
    a is {use(state.a)}, c is {use(state.b.c)}
    document.body.appendChild(elm); state.a++ state.b.c++ // div will now show "a is 1, c is 2" ``` -------------------------------- ### Define CSS Classes Externally Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/migrating/migrating-from-v1.mdx CSS classes must now be defined outside the component using the `css` tag. The previous method of defining styles within the component is no longer supported. ```tsx // old const App: Component = function () { this.css = ` height: 100vh; `; const red = css` color: red; `; return (
    this text is red!
    ); }; // new function App(this: FC<{}, { /* ... */ }>) { return (
    this text is red!
    ); }; App.style = css` :scope { height: 100vh; } .red { color: red; } `; ``` -------------------------------- ### Render Dynamic List References in JSX Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/7.-Arrays Shows how to render dynamic lists of elements using `use` with array references in JSX. This allows the UI to update when the array reference itself changes. It also covers updating the list by reassigning the array. ```jsx this.items = [
    1
    ,
    2
    ] let elm =
    {use(this.items)}
    this.items = [
    a different
    ,
    list
    ] ``` -------------------------------- ### Apply Scoped CSS to a Component (TSX) Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/features/css.mdx This snippet demonstrates how to apply scoped CSS to a component using the `css` template tag and assigning it to the `style` property. It shows examples of using `:scope` for component-specific styling and `:global()` for overriding global styles. ```tsx Card.style = css` :scope { background: var(--bg-3); } :global(*) > :scope { /* ... */ } `; ``` -------------------------------- ### Create and Append HTML Element with DreamlandJS (JSX) Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/1.-Basic-HTML Demonstrates the basic creation of an HTML button element using DreamlandJS with JSX syntax and appending it to the document body. This is the simplest way to integrate DreamlandJS into a project. ```jsx let button = ; document.body.appendChild(button); ``` -------------------------------- ### Create Persistent Stores with createStore in TypeScript/JSX Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt The `createStore` function initializes reactive state that persists across page loads. It supports different storage backends like localStorage or custom asynchronous implementations. Autosave can be configured to 'auto' for immediate saving or 'beforeunload' for saving when the page closes. It takes an initial state object and a configuration object with an identifier, backing storage, and autosave behavior. ```tsx import { createStore, saveAllStores } from "dreamland/core"; // Basic localStorage store with autosave let settings = createStore( { theme: "light", fontSize: 16, notifications: true }, { ident: "user-settings", // Unique identifier for storage backing: "localstorage", // Storage backend autosave: "auto" // Save on every change } ); // Store with save-before-exit (useful for larger state) let appState = createStore( { lastOpenFile: null as string | null, recentFiles: [] as string[], editorState: { cursorPos: 0, selection: null } }, { ident: "app-state", backing: "localstorage", autosave: "beforeunload" // Save when page closes } ); // Custom async backing (e.g., IndexedDB or remote API) let userProfile = createStore( { displayName: "Anonymous", avatar: null as string | null, preferences: {} }, { ident: "user-profile", backing: { async read(ident: string): Promise { // Fetch from IndexedDB or API const response = await fetch(`/api/settings/${ident}`); return response.ok ? await response.text() : undefined; }, async write(ident: string, value: string): Promise { await fetch(`/api/settings/${ident}`, { method: "POST", body: value }); } }, autosave: "auto" } ); // Use stores like normal state document.body.appendChild(

    s + "px") }}> Settings Demo

    ); ``` -------------------------------- ### SSR Pre-rendering with Dreamland Router Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/extras/router.mdx This code illustrates how to integrate Dreamland's router with Server-Side Rendering (SSR) for pre-rendering static routes. The `ssgables` function identifies routes suitable for pre-rendering, which are then rendered and saved to static files. ```tsx let paths = router.ssgables(); let template = /* index.html ... */; for (const [route, path] of paths) { const rendered = await renderSsr(template, () => entry.default(route)); console.log(`prerendered: ${route}`); let resolved = resolve("dist/static/" + path); await mkdir(dirname(resolved), { recursive: true }); await writeFile(resolved, rendered); } ``` -------------------------------- ### Referencing DOM Elements with bind:this in DreamlandJS (TSX) Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/6.-bind:this This example demonstrates how to use the bind:this directive to assign a DOM element to a component property. The 'renderRoot' property, typed as HTMLDivElement, is bound to a div element. After the component mounts, the innerHTML of this element can be directly manipulated. ```tsx const RawHTMLRenderer: Component <{ html: string }, { renderRoot: HTMLDivElement }> = function() { this.mount = () => { this.renderRoot.innerHTML = this.html } return (
    unsanitized html below:
    ) } document.body.appendChild() ``` -------------------------------- ### Create and Append HTML Button with DreamlandJS Source: https://github.com/mercuryworkshop/dreamlandjs/blob/rewrite/site/src/docs/intro/basic-html.mdx This snippet demonstrates the creation of a simple HTML button element with a specified class and appending it to the document body using DreamlandJS. It highlights DreamlandJS's direct DOM manipulation approach. ```tsx let button = ; document.body.appendChild(button); ``` -------------------------------- ### Manage Component Lifecycle and DOM Access with ComponentContext in TSX Source: https://context7.com/mercuryworkshop/dreamlandjs/llms.txt Illustrates using `ComponentContext` (`this.cx`) within a TSX component to access lifecycle methods (`init`, `mount`) and bind DOM elements. It shows how to perform DOM manipulations and listen for data changes. Dependencies include 'dreamland/core'. ```tsx import { type FC } from "dreamland/core"; function ChartDashboard(this: FC< { data: number[] }, { canvas: HTMLCanvasElement; status: string } >) { this.status = "initializing"; // init runs on both server and client after element creation this.cx.init = () => { console.log("Component initialized, root element:", this.root); }; // mount runs only on client, ideal for DOM-dependent code this.cx.mount = () => { this.status = "mounted"; // Access referenced DOM element const ctx = this.canvas.getContext("2d"); if (ctx) { // Draw chart using this.data this.data.forEach((value, index) => { ctx.fillRect(index * 30, 100 - value, 25, value); }); } // Listen for data changes and redraw use(this.data).listen((newData) => { ctx?.clearRect(0, 0, this.canvas.width, this.canvas.height); newData.forEach((value, index) => { ctx?.fillRect(index * 30, 100 - value, 25, value); }); }); }; return (

    Status: {use(this.status)}

    {/* Bind canvas element to this.canvas using this={use(...)} */}
    ); } // Usage document.body.appendChild( ); ``` -------------------------------- ### Create and Append HTML Element with DreamlandJS (Plain JS) Source: https://github.com/mercuryworkshop/dreamlandjs/wiki/1.-Basic-HTML Shows the equivalent of creating an HTML button element using DreamlandJS in plain JavaScript with tagstring syntax, avoiding the need for a preprocessor. This is an alternative to JSX. ```javascript return html ` `; ```