### 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`` ``` ```javascript svg`` ``` -------------------------------- ### Read File as Data URL Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads a file and returns a promise of a data URL. Useful for displaying local files, such as images, in the browser. Note that for large files, URL.createObjectURL may be more efficient. ```javascript Files.url(file).then(url => { var image = new Image; image.src = url; return image; }) ``` ```javascript { const image = new Image; image.src = URL.createObjectURL(file); invalidation.then(() => URL.revokeObjectURL(image.src)); return image; } ``` -------------------------------- ### Generate TeX Element from LaTeX String Literal Source: https://github.com/observablehq/stdlib/blob/main/README.md Renders a LaTeX string literal as an HTML element using KaTeX for inline math display. ```javascript tex`E = mc^2` ``` -------------------------------- ### Generators and Iterators Utilities Source: https://github.com/observablehq/stdlib/blob/main/README.md This module provides utilities for working with JavaScript generators and iterators. It helps in managing sequences of values and asynchronous operations efficiently. ```javascript import * as Generators from "@observablehq/stdlib"; // Example: Creating a generator that yields numbers from 0 to 9 function* countToTen() { for (let i = 0; i < 10; i++) { yield i; } } const numberGenerator = countToTen(); // Example: Using a generator utility (e.g., taking a specific number of values) // const firstFive = Generators.take(numberGenerator, 5); // for (const value of firstFive) { // console.log(value); // } ``` -------------------------------- ### Create Worker Generator Source: https://github.com/observablehq/stdlib/blob/main/README.md Demonstrates how to use Generators.worker to create a new Web Worker that executes the provided JavaScript source code. The worker is automatically terminated when the generator is disposed. ```javascript worker = Generators.worker(` onmessage = function({data}) { postMessage({echo: data}); }; `) ``` -------------------------------- ### Create Range Input Element Source: https://github.com/observablehq/stdlib/blob/main/README.md Generates a new HTML range input element. Allows setting minimum, maximum, and step values. It's generally recommended to use the html tagged template literal for creating range inputs. ```javascript DOM.range(-180, 180, 1) ``` ```javascript html`

` ``` ```javascript DOM.element("a", {target: "_blank"}) ``` ```javascript html`` ``` ```javascript DOM.element("svg:svg") ``` ```javascript svg`` ``` -------------------------------- ### Create Aliased Require Function Source: https://github.com/observablehq/stdlib/blob/main/README.md Creates a new require function with custom aliases for modules. This is useful for simplifying module loading or for using specific versions or UMD builds of libraries. ```javascript React = require("react@16/umd/react.production.min.js") ``` ```javascript ReactDOM = require("react-dom@16/umd/react-dom.production.min.js") ``` ```javascript Semiotic = require.alias({"react": React, "react-dom": ReactDOM})("semiotic@1") ``` ```javascript r = require.alias({ "react": "react@16/umd/react.production.min.js", "react-dom": "react-dom@16/umd/react-dom.production.min.js", "semiotic": "semiotic@1" }) ``` ```javascript React = r("react") ``` ```javascript ReactDOM = r("react-dom") ``` ```javascript Semiotic = r("semiotic") ``` -------------------------------- ### Queue Push-based Data with Generators.queue Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a generator that yields promises for observable values, adapting push-based data sources to a pull-based one. Similar to Generators.observe, it uses an initialize function to manage callbacks and disposal. This version does not debounce calls to the change function. ```javascript Generators.queue(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); }) ``` -------------------------------- ### Access File Contents as ZipArchive with FileAttachment Source: https://github.com/observablehq/stdlib/blob/main/README.md Opens a ZIP archive file and returns a ZipArchive object, which allows access to the files within the archive. This is useful for working with compressed files. It requires the file to be a valid ZIP archive. ```JavaScript const archive = await FileAttachment("archive.zip").zip(); ``` -------------------------------- ### Read File as Text Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads a file and returns a promise of a string. Suitable for text files such as plain text, CSV, Markdown, and HTML. ```javascript Files.text(file) ``` -------------------------------- ### Read File as ArrayBuffer Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads a file and returns a promise of an ArrayBuffer. Useful for binary files like shapefiles and ZIP archives. ```javascript Files.buffer(file) ``` -------------------------------- ### Resolve Module URL Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a promise that resolves to the URL of a module, allowing for direct access to module resources. ```javascript require.resolve("d3-array") // "https://cdn.jsdelivr.net/npm/d3-array@2.0.3/dist/d3-array.min.js" ``` -------------------------------- ### Parse File as XMLDocument with FileAttachment Source: https://github.com/observablehq/stdlib/blob/main/README.md Parses the contents of a file as an XMLDocument, providing an object model for navigating and manipulating XML data. This is suitable for files containing XML markup. It requires the file to be well-formed XML. ```JavaScript const document = await FileAttachment("cars.xml").xml(); ``` -------------------------------- ### Create Text Node Source: https://github.com/observablehq/stdlib/blob/main/README.md Generates a new text node containing the specified string. The html tagged template literal provides a simpler alternative for creating text content. ```javascript DOM.text("Hello, world!") ``` ```javascript html`Hello, world!` ``` -------------------------------- ### visibility: Promise for Viewport Visibility Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a promise that resolves with a specified value when the cell becomes visible in the viewport. This function is provided by the runtime and is specific to each cell. -------------------------------- ### Library Resolve Alias Source: https://github.com/observablehq/stdlib/blob/main/README.md Provides an alias for d3.require.resolve, facilitating the resolution of module URLs within the library context. ```javascript Library.resolve(name[, base]) ``` -------------------------------- ### Generate HTML Element from Markdown String Literal Source: https://github.com/observablehq/stdlib/blob/main/README.md Converts a Markdown string literal into an HTML element using the Marked library. It trims whitespace and supports embedding DOM elements or arrays of strings/DOM elements. ```javascript md`# Hello, world!` ``` ```javascript md`My *favorite* number is ${tex`\tau`}.` ``` ```javascript md` | Name | Symbol | Atomic number | |-----------|-------------|---------------|${elements.map(e => ` | ${e.name} | ${e.symbol} | ${e.number} |`)} ` ``` -------------------------------- ### Parse File as HTMLDocument with FileAttachment Source: https://github.com/observablehq/stdlib/blob/main/README.md Parses the contents of a file as an HTMLDocument, allowing programmatic access to the HTML structure. This is useful for processing HTML files. It requires the file to contain valid HTML. ```JavaScript const document = await FileAttachment("index.html").html(); ``` -------------------------------- ### Generators.disposable: Create a generator with automatic resource disposal Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a new generator that yields a specified value once. The generator's return method calls a provided dispose function with the value, enabling automatic resource cleanup when the cell is re-evaluated. This is useful for managing resources like TensorFlow tensors. ```JavaScript x = Generators.disposable(tf.tensor2d([[0.0, 2.0], [4.0, 6.0]]), x => x.dispose()) ``` -------------------------------- ### width: Cell Width Source: https://github.com/observablehq/stdlib/blob/main/README.md Represents the current width of cells in the Observable environment. Useful for creating responsive layouts and elements that adapt to the available cell width. ```javascript html` ` ``` -------------------------------- ### Read File Attachment as JSON Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads the content of a file attachment, parses it as JSON, and returns a promise that resolves to the parsed JavaScript values. ```javascript const logs = await FileAttachment("weekend-logs.json").json(); ``` -------------------------------- ### now: Current Timestamp Source: https://github.com/observablehq/stdlib/blob/main/README.md Provides the current value of Date.now, representing the current timestamp in milliseconds since the UNIX epoch. Used for displaying or processing current time information. ```javascript md`The current time is: ${new Date(now).toISOString()}` ``` -------------------------------- ### Read File Attachment as CSV Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads the content of a file attachment, parses it as comma-separated values (CSV), and returns a promise that resolves to an array. Options for array format and type inference are available. ```javascript const data = await FileAttachment("cars.csv").csv(); ``` -------------------------------- ### Read File Attachment as ArrayBuffer Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads the content of a file attachment and returns a promise that resolves to the content as an ArrayBuffer, suitable for binary data. ```javascript const city = shapefile.read(await FileAttachment("sf.shp").arrayBuffer()); ``` -------------------------------- ### Promises.when: Resolve Promise at Specific Date Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a promise that resolves with a specified value at a given date. This function relies on setTimeout and has a limitation on the maximum delay duration. -------------------------------- ### Read File Attachment as TSV Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads the content of a file attachment, parses it as tab-separated values (TSV), and returns a promise that resolves to an array. Options for array format and type inference are available. ```javascript const data = await FileAttachment("cars.tsv").tsv(); ``` -------------------------------- ### Read File Attachment as Text Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads the content of a file attachment and returns a promise that resolves to the content as a JavaScript string. ```javascript const hello = await FileAttachment("hello.txt").text(); ``` -------------------------------- ### Generate HTML Element from String Literal Source: https://github.com/observablehq/stdlib/blob/main/README.md Creates an HTML element from a tagged template literal string. It trims whitespace and wraps non-element fragments in a DIV. Embedded expressions can be DOM elements or arrays. ```javascript html`

Hello, world!` ``` ```javascript html`
Hello, world!
` ``` ```javascript html`I like ${tex`\KaTeX`} for math.` ``` ```javascript html`${["zero", "one", "two"].map((name, i) => html``)}
${name}${i}
` ``` -------------------------------- ### Access Specific File within ZipArchive Source: https://github.com/observablehq/stdlib/blob/main/README.md Retrieves a specific file from within a ZipArchive as a new FileAttachment. This allows you to then use other FileAttachment methods (like .text()) to read the content of the extracted file. It requires a ZipArchive object and the path to the desired file. ```JavaScript const archive = await FileAttachment("archive.zip").zip(); const text = await archive.file("readme.txt").text(); ``` -------------------------------- ### Retrieve Value at Index from Iterator Source: https://github.com/observablehq/stdlib/blob/main/README.md Illustrates the use of Generators.valueAt to fetch a specific element from an iterator based on its index. Note that this method does not await promises yielded by the iterator. ```javascript first = Generators.valueAt(iterator, 0) ``` -------------------------------- ### Stream File Contents with FileAttachment Source: https://github.com/observablehq/stdlib/blob/main/README.md Reads the contents of a file as a ReadableStream. This is useful for processing large files efficiently by reading them in chunks. It requires the file to be accessible via FileAttachment. ```JavaScript const stream = await FileAttachment("metrics.csv").stream(); const reader = stream.getReader(); let done, value; while (({done, value} = await reader.read()), !done) { yield value; } ``` -------------------------------- ### Promises.tick: Synchronized Promise Resolution Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a promise that resolves at the next integer multiple of milliseconds since the UNIX epoch. Enables synchronized asynchronous operations, similar to Promises.delay but with precise timing. ```javascript yield Promises.tick(1000, ++i); ``` ```javascript await Promises.tick(1000); ``` -------------------------------- ### Map Iterator Values with Generators.map Source: https://github.com/observablehq/stdlib/blob/main/README.md Generates a sequence of transformed values from an iterator using a provided mapping function. The transform function receives the value and its index. This function assumes a synchronous iterator; it does not await promises yielded by the iterator. ```javascript x = Generators.map(Generators.range(100), x => x * x) ``` -------------------------------- ### Generate Unique Identifier Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a unique identifier object, useful for SVG attributes like clip-path or xlink:href. The identifier can optionally be named for debugging. Using DOM.uid ensures uniqueness even when code is imported. ```javascript { const clip = DOM.uid("clip"); return svg` `; } ``` -------------------------------- ### Generators.filter: Create a generator yielding a subset of values Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a generator that yields values from an iterator only if a test function returns truthy for the value. The test function is invoked with the value and its index. Assumes the iterator is synchronous. ```JavaScript x = Generators.filter(Generators.range(100), x => x & 1) ``` -------------------------------- ### Promises.delay: Resolve Promise After Duration Source: https://github.com/observablehq/stdlib/blob/main/README.md Returns a promise that resolves with a specified value after a given duration in milliseconds. Useful for creating timed intervals or delays in asynchronous operations. ```javascript yield Promises.delay(1000, ++i); ``` -------------------------------- ### Generate SVG Element from String Literal Source: https://github.com/observablehq/stdlib/blob/main/README.md Creates an SVG element from a tagged template literal string. It trims whitespace and wraps non-element fragments in a G element. Embedded expressions can be DOM elements or arrays. ```javascript svg` ` ``` ```javascript svg` ` ``` -------------------------------- ### invalidation: Promise for Cell Re-evaluation Source: https://github.com/observablehq/stdlib/blob/main/README.md A promise that resolves when the current cell is re-evaluated due to code changes, manual execution, or input changes. Commonly used for resource cleanup, such as aborting fetches. ```javascript invalidation.then(() => controller.abort()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.