### Create Arithmetic Progression Generator Source: https://github.com/observablehq/stdlib/blob/main/README.md Shows how to use Generators.range to create a generator that yields an arithmetic progression. Examples include iterating over integers and handling floating-point steps. ```javascript i = { for (const i of Generators.range(0, 100, 1)) { yield i; } } ``` ```javascript i = Generators.range(100) ``` ```javascript Generators.range(0, 1, 0.2) // 0, 0.2, 0.4, 0.6000000000000001, 0.8 ``` ```javascript [...Generators.range(49)].map(d => d / 49) // GOOD: returns 49 elements. ``` -------------------------------- ### Get File Contents as Blob with FileAttachment Source: https://github.com/observablehq/stdlib/blob/main/README.md Retrieves the raw contents of a file as a Blob object. This method is suitable for handling binary data or when the entire file content needs to be available as a single unit. It uses the FileAttachment API to access the file. ```JavaScript const blob = await FileAttachment("binary-data.dat").blob(); ``` -------------------------------- ### Get File Attachment URL Source: https://github.com/observablehq/stdlib/blob/main/README.md Retrieves a promise that resolves to the URL of the file attachment. This is useful for embedding or referencing the file. ```javascript const url = await FileAttachment("file.txt").url(); ``` -------------------------------- ### Get Filenames from ZipArchive Source: https://github.com/observablehq/stdlib/blob/main/README.md Retrieves an array of all file paths contained within a ZipArchive. This allows you to see the structure of the archive before accessing individual files. It requires a ZipArchive object obtained from FileAttachment. ```JavaScript const archive = await FileAttachment("archive.zip").zip(); console.log(archive.filenames); ``` -------------------------------- ### Rendering Content with Observable Stdlib Source: https://github.com/observablehq/stdlib/blob/main/README.md This module provides functions to render various content formats, including HTML, Markdown, SVG, and LaTeX, directly within Observable notebooks. This enables rich data visualization and presentation. ```javascript import { html, md, svg, tex } from "@observablehq/stdlib"; // Example: Rendering HTML const myHtml = html`
This is bold text.
`; // Example: Rendering Markdown const myMarkdown = md`## A Heading This is a paragraph with *italics*.`; // Example: Rendering SVG const mySvg = svg``; // Example: Rendering LaTeX const myLatex = tex`$$ \int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2} $$`; ``` -------------------------------- ### Loading Libraries with require Source: https://github.com/observablehq/stdlib/blob/main/README.md The `require` function allows loading third-party libraries dynamically into your Observable notebook. This is crucial for extending functionality with external packages. ```javascript import { require } from "@observablehq/stdlib"; // Example: Loading the 'lodash' library // const _ = await require("lodash@4.17.21"); // console.log(_.capitalize("hello")); // Output: Hello ``` -------------------------------- ### Create and Use Standard Library Source: https://github.com/observablehq/stdlib/blob/main/README.md Instantiates a new standard library object, optionally with a custom module resolver. The library provides access to various Observable built-ins, such as DOM manipulation. ```javascript const library = new Library(); const canvas = library.DOM.canvas(960, 500); ``` -------------------------------- ### Resource Management with Invalidation and Visibility Source: https://github.com/observablehq/stdlib/blob/main/README.md These utilities help manage resources and react to changes in the notebook's environment. `invalidation` is used to dispose of resources when they are no longer needed, while `visibility` allows reacting to element visibility changes. ```javascript import { invalidation, visibility } from "@observablehq/stdlib"; // Example: Using invalidation to clean up resources // const timerId = setInterval(() => console.log("Tick"), 1000); invalidation.then(() => { // clearInterval(timerId); console.log("Resources cleaned up."); }); // Example: Waiting for an element to become visible // async function waitForElement() { // await visibility("#my-element"); // console.log("Element is visible!"); // } ``` -------------------------------- ### File Handling with Observable Stdlib Source: https://github.com/observablehq/stdlib/blob/main/README.md This module offers functionalities to read local files directly into memory and to access remote files. It's essential for data loading and integration within Observable notebooks. ```javascript import * as Files from "@observablehq/stdlib"; import * as FileAttachments from "@observablehq/stdlib"; // Example: Reading a local file (requires user interaction or specific environment setup) // const fileContent = await Files.file("path/to/your/file.txt"); // Example: Reading a remote file attachment // const remoteFileContent = await FileAttachments.fileAttachment("data.csv").text(); ``` -------------------------------- ### Accessing Runtime Information Source: https://github.com/observablehq/stdlib/blob/main/README.md This module provides access to runtime information such as the current time and page width. It's useful for creating responsive and time-aware visualizations. ```javascript import { now, width } from "@observablehq/stdlib"; // Example: Getting the current timestamp const currentTime = now(); console.log("Current time:", currentTime); // Example: Getting the current page width const pageWidth = width; console.log("Page width:", pageWidth); ``` -------------------------------- ### Create Download Link with DOM.download Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns an anchor element with a download button for a given object. The object can be a File, Blob, or a Promise resolving to these. It can also be a function that returns the object or a Promise. The optional name parameter specifies the download filename. ```javascript DOM.download(await new Promise(resolve => canvas.toBlob(resolve))) ``` ```javascript DOM.download(() => new Promise(resolve => canvas.toBlob(resolve))) ``` -------------------------------- ### Observe Push-based Data with Generators.observe Source: https://github.com/observablehq/stdlib/blob/main/README.md Creates a generator that yields promises for observable values, converting push-based data sources (like Observables or EventTargets) into a pull-based interface. The initialize function can register a change callback and optionally a dispose function. ```javascript Generators.observe(change => { // An event listener to yield the element’s new value. const inputted = () => change(element.value); // Attach the event listener. element.addEventListener("input", inputted); // Yield the element’s initial value. change(element.value); // Detach the event listener when the generator is disposed. return () => element.removeEventListener("input", inputted); }) ``` ```javascript { const generator = Generators.observe(…); const values = []; for (const value of generator) { if (values.push(await value) >= 4) { return values; } } } ``` -------------------------------- ### Require Modules from npm Source: https://github.com/observablehq/stdlib/blob/main/README.md Loads modules from npm asynchronously. Supports specifying package names, scoped packages, and semver ranges. Multiple modules can be loaded and merged into a single object. ```javascript d3 = require("d3-array") ``` ```javascript d3 = require("d3-array", "d3-color") ``` ```javascript d3 = require("d3-array@1.1") ``` -------------------------------- ### Load File as SQLite Database with FileAttachment Source: https://github.com/observablehq/stdlib/blob/main/README.md Loads a file as a SQLite database client, allowing direct interaction with the database contents. This is ideal for working with structured data stored in SQLite files. It requires the file to be a valid SQLite database. ```JavaScript const db = await FileAttachment("chinook.db").sqlite(); ``` -------------------------------- ### Promise Utilities with Observable Stdlib Source: https://github.com/observablehq/stdlib/blob/main/README.md This module offers utilities for simplifying common asynchronous operations involving Promises. It aids in managing concurrent requests and handling promise states. ```javascript import * as Promises from "@observablehq/stdlib"; // Example: Creating a promise that resolves after a delay const delayedPromise = new Promise(resolve => setTimeout(() => resolve("Done!"), 1000)); // Example: Using a promise utility (e.g., waiting for multiple promises) // const results = await Promises.all([promise1, promise2]); ``` -------------------------------- ### Accumulate Generator Values Source: https://github.com/observablehq/stdlib/blob/main/README.md Demonstrates how to use Generators.queue to create a generator and manually retrieve its yielded values, specifically accumulating the first four. ```javascript { const generator = Generators.queue(…); const values = []; for (const value of generator) { if (values.push(await value) >= 4) { return values; } } } ``` -------------------------------- ### DOM Manipulation with Observable Stdlib Source: https://github.com/observablehq/stdlib/blob/main/README.md This module provides utilities for creating and manipulating HTML and SVG elements within the Observable environment. It simplifies the process of dynamically generating user interfaces. ```javascript import * as DOM from "@observablehq/stdlib"; // Example: Create a div element const divElement = DOM.element("div", { className: "my-class" }, "Hello, Observable!"); // Example: Create an SVG circle const svgCircle = DOM.svg("circle", { cx: 50, cy: 50, r: 40, fill: "blue" }); ``` -------------------------------- ### Instantiate FileAttachment Source: https://github.com/observablehq/stdlib/blob/main/README.md Creates a FileAttachment object for a given file name. This is the initial step to access file contents. ```javascript photo = FileAttachment("sunset.jpg") ``` -------------------------------- ### Create Canvas 2D Context with DOM.context2d Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a new canvas context with specified width, height, and optional DPI for automatic pixel density scaling. The context's canvas can be accessed via context.canvas. For WebGL, DOM.canvas or html tagged literals are preferred. ```javascript { const context = DOM.context2d(960, 500); return context.canvas; } ``` -------------------------------- ### Generate TeX Element with Custom Options Source: https://github.com/observablehq/stdlib/blob/main/README.md Creates a function that renders LaTeX string literals with specified KaTeX options, such as displayMode. ```javascript tex.options({displayMode: true})`E = mc^2` ``` -------------------------------- ### Create Select Element with Options Source: https://github.com/observablehq/stdlib/blob/main/README.md Creates a new HTML select (dropdown) element populated with options from a given array of strings or data. The html tagged template literal offers more control over option display. ```javascript DOM.select(["red", "green", "blue"]) ``` ```javascript html`` ``` ```javascript html`` ``` -------------------------------- ### Create SVG Element Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a new SVG element with specified width and height. For responsive SVGs, styles can be applied. The svg tagged template literal is often preferred for SVG creation. ```javascript DOM.svg(960, 500) ``` ```javascript svg`