npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bazariodev/galley

v0.2.0

Published

Parse plain text and calculate list edits.

Downloads

526

Readme

Galley

Galley parses plain text into paragraphs and lists. It calculates list edits for a text composer.

Install

npm install @bazariodev/galley

Usage

import { createTextFormat } from '@bazariodev/galley';

const format = createTextFormat();
const blocks = format.parse('- milk\n- tea');
console.log(blocks[0].items[0].text); // milk

A composer can calculate an edit. Apply the returned span and selection in the composer.

import { LIST_KINDS } from '@bazariodev/galley';

const edit = format.toggleList('milk', { start: 4, end: 4 }, LIST_KINDS.BULLET);
// { start: 0, end: 4, text: '- milk', selection: { start: 6, end: 6 } }

Supply a renderer, an inline text pipeline, and a key map. The ./dom entry applies edits to a textarea.

Output

parse returns an array of blocks in source order. For example, parsing 'Shopping\n\n3) milk\n - oat' returns:

[
  { type: 'paragraph', gapBefore: 0, text: 'Shopping' },
  {
    type: 'list',
    kind: 'number',
    depth: 1,
    gapBefore: 1,
    items: [
      {
        marker: '3)',
        text: 'milk',
        children: [
          {
            type: 'list',
            kind: 'bullet',
            depth: 2,
            gapBefore: 0,
            items: [{ marker: '-', text: 'oat', children: [] }],
          },
        ],
      },
    ],
  },
]

A ParagraphBlock contains its paragraph in text. A ListBlock has a kind, a 1-based depth, and an items array. Each ListItem keeps its literal marker and its content in text. Its children array contains any nested list blocks.

gapBefore counts the blank lines before a block, including leading blank lines before the first block. A child block always has gapBefore: 0.

format.getListItem returns a ListItemInfo with kind and depth for an item line. It returns null for other lines.

A TextEdit contains start, end, text, and selection. Replace value.slice(start, end) with text. Then set selection.start and selection.end in the resulting value.

Behavior

  • Lines end at \n. The parser ignores one trailing \r on each line. Space and tab are whitespace. A tab advances to the next multiple of 4 columns
  • A list marker is -, *, •, or 1 to 9 ASCII digits followed by . or ). It must have whitespace after it. A line without a valid marker is a paragraph line. An empty item has a marker and whitespace with no content
  • Paragraph lines form paragraphs. Blank lines end paragraphs and lists. gapBefore counts blank lines before a block. The parser omits trailing blank lines
  • Depth is relative to open levels. Two extra columns start a child level. maxDepth clamps deeper items without dropping them. indentWidth does not change parsing
  • Each parse returns fresh plain data. Text is not HTML. A renderer must show number markers as typed. It can draw its own bullet glyph. The parser accepts untrusted text
  • The format object is frozen. Its methods work when detached
  • Selections and edits use UTF-16 offsets. An edit replaces [start, end) and supplies the final selection. The span is a compact prefix and suffix comparison that keeps the original caret inside the replaced span for a collapsed selection. Boundaries do not split surrogate pairs or CRLF. For a collapsed edit that keeps the caret on its line, Galley adds the original content offset to the resulting line's content start. It clamps the caret to the line end. null means no change
  • A selection affects each intersected line. An end at column 0 excludes that line. A line break belongs to the preceding line
  • getListKindAt reads only the line at position. It returns the list kind for an item, including an empty item, or null for other lines. It uses the same marker rules as parse. An offset on \n is on the preceding line. If \n is the first character, offset 0 is on the empty first line. After a final \n, the end offset is on the empty last line. This standalone function uses no configuration. format.getListItem returns the kind and the depth, which uses the instance's maxDepth
  • Toggle removes the indentation, marker, and following whitespace when all non-blank selected lines have the requested kind. It preserves the remaining text literally, even if that text starts with a list marker. An exposed number keeps its literal spelling and does not start renumbering. Removal of an outer numbered marker can still renumber its old run suffix. In other selections, the toggle makes each non-blank line that kind. An all-blank selection makes an empty item on the first selected line. A new number follows the run above, or starts at 1
  • A mixed toggle keeps the indentation of existing items. A plain line loses its leading spaces and tabs. It becomes a list item at column 0 with one space after the marker. Galley parses the edited text again to find each item's depth and parent. Removing a parent marker keeps the text and indentation of unselected children
  • Continue splits an item at the caret. An empty item is outdented or ends the list. Indent moves an eligible item and its children one level deeper. Outdent moves them one level shallower. A moved line uses the recorded column of its new level if that level is open. If the level is closed, it uses the recorded column of the parent's level plus indentWidth. The parent's own line can have a different column. For example, indent b in ' - x\n- a\n- b'. Depth 1 records column 3 from x, so b gets 7 spaces with the default width of 4. A new depth-1 level uses column 0. Unmoved following lines keep their indentation. Their parent and depth can change when Galley parses the result
  • An edit that moves items returns null if the sum of positive indentation increases in UTF-16 code units exceeds Math.max(1_048_576, 8 * value.length). Indentation decreases do not reduce this sum
  • Edits renumber affected numbered runs from the earliest structural change. The earlier prefix stays as typed. A new, moved, or reparented run head starts at 1. A surviving head under the same parent keeps its number. Children that move only with a parent keep their run. Continue can give the original item’s children a new parent; affected numbered runs are renumbered. Delimiters stay. An edit returns null if a number needs more than 9 digits
  • CommonMark has different list and indentation rules. The same text can produce a different structure. The default edit indentation is 4 spaces
  • trimTrailingEmptyItems removes trailing empty items and blank lines. It keeps the leading indentation of retained lines. Each call also removes at most one trailing \r from the last retained line: p\r\r\n becomes p\r

Textarea edits

import { applyTextareaEdit } from '@bazariodev/galley/dom';

const selection = { start: textarea.selectionStart, end: textarea.selectionEnd };
const textareaEdit = format.toggleList(textarea.value, selection, LIST_KINDS.BULLET);
if (textareaEdit) applyTextareaEdit(textarea, textareaEdit);

Supply textarea. Calculate the edit from its current value and apply it synchronously. applyTextareaEdit returns true when the full edit and final selection are applied. It returns false if they are not. A read-only or effectively disabled textarea, or a replacement over maxLength, is skipped. Before focus, the adapter checks that edit.text is a string and that each span endpoint is an integer in the current value. It also checks that each final selection endpoint is an integer in the resulting value. Both ranges use UTF-16 offsets and have the start at or before the end. An invalid edit returns false before focus, any change to the value or selection, or an input event. After focus and before a fallback write, the adapter checks writability and the length limit again. An empty replacement over an empty span sets only the final selection, even when the current value exceeds maxLength. It does not dispatch input or create an undo step.

The native path uses one compact replacement. It selects the replacement range before the command. A native input listener can see an interim selection. If the browser dispatches a native beforeinput event for the command and a listener cancels it, the adapter returns false and skips the fallback. Focus and selection can already have changed. The adapter does not dispatch beforeinput itself. Tested headless WebKit dispatched a cancellable event. Tested headless Chromium and Firefox did not dispatch this event for these commands.

The adapter checks the value after the command, including when the command returns false or throws. If the expected value is present, the adapter sets the final selection.

The adapter tries the fallback if the command leaves the original value and a replacement is still necessary. The textarea must still be writable and the replacement must fit maxLength. The adapter calls setRangeText, sets the final selection, and dispatches a bubbling input event. If a listener restores the original value during the native event, the fallback can dispatch a second event.

If focus or the command leaves an unexpected value, the adapter returns false and keeps the current value and selection. After the fallback event, it also returns false if a listener changes the value or selection. A listener's changes can remain after a false result. The fallback can apply an edit without adding a native undo step.

The native undo contract has two tiers. In Chromium and Firefox, one keyboard Undo restores the pre-edit value and original selection or selected replacement span. A collapsed insertion restores the original caret. In WebKit, one Undo can also remove immediately preceding typing. It must restore the whole earlier value from Undo of equivalent real typing, never a partial edit, with a valid selection. In each engine, one Redo restores the post-edit value. The headless browser suite checks these tiers. Real Safari and controlled composers need their own checks.

API

| Export | Result | | --- | --- | | createTextFormat(options?) | Frozen TextFormat | | getListKindAt(value, position) | ListKind or null, independent of format options | | BLOCK_TYPES, LIST_KINDS | Frozen maps of block types and list kinds | | format.parse(text) | Fresh TextBlock[] | | format.getListItem(value, position) | { kind, depth } or null. Depth uses the instance's maxDepth | | format.toggleList(value, selection, kind) | TextEdit or null | | format.continueList(value, selection) | TextEdit or null | | format.indentList(value, selection) | TextEdit or null | | format.outdentList(value, selection) | TextEdit or null | | format.trimTrailingEmptyItems(value) | Trimmed string | | applyTextareaEdit(textarea, edit) from @bazariodev/galley/dom | true if applied, else false |

indentWidth defaults to 4 and accepts integers from 2 to 16. maxDepth defaults to 2 and accepts integers of 1 or more. The factory ignores unknown option keys.

Errors

The factory throws TypeError for arrays, null, and other values outside its options object contract. Pass undefined to use the defaults. The factory throws RangeError for invalid option values. Methods throw TypeError for invalid text, selection, or kind. They throw RangeError for invalid offsets or a reversed selection.

getListKindAt throws TypeError if value is not a string. It throws RangeError if position is not an integer UTF-16 offset from 0 through value.length. Passing a string such as '0' as an offset throws RangeError.

TypeScript

The root entry includes declarations for TextFormat, TextFormatOptions, TextBlock, ParagraphBlock, ListBlock, ListItem, ListItemInfo, TextSelection, TextEdit, BlockType, and ListKind.

License

MIT