General-Purpose APIs Without Building a Framework

Adding a keyboard shortcut to a text editor sounds like work for a keyboard handler. Then the implementation reaches into the document model, where Backspace, Delete, Cut, and typing over a selection each have their own method. Before the shortcut can work, another document operation seems to be required.

There is a design choice hiding in that small feature. Should the document understand every way a person can request an edit, or should it understand the edit itself?

In the example we will work through, the editor needs only ordinary insertion, deletion, and replacement. Those actions already contain enough overlap to justify a more useful API. We do not need a hypothetical second application or a plan to build an editor framework.

The common operation is replacing a range of text. The interesting work is deciding what that operation promises and what the keyboard handler must still decide. A short method name alone cannot answer either question.

We will build a small TypeScript document, use it from interaction code, and see how the same operation expresses an inverse edit for undo. The implementation uses JavaScript strings; it is a teaching model with explicit limits, rather than a complete Unicode editor. By the end, the next shortcut should have a clear place to go without adding another keyboard-specific method to the document.

On this page

Begin With the Operations the Product Already Needs

Here is the command-shaped interface that puts the shortcut in that awkward position:

type TextRange = {
  start: number
  end: number
}

type CommandShapedDocument = {
  backspace(cursor: number): void
  deleteForward(cursor: number): void
  cutSelection(selection: TextRange): void
  typeOverSelection(selection: TextRange, text: string): void
}

Each operation may be easy to call in one event handler. But maintaining the document now requires understanding what each command means. Does Backspace remove a code unit, a Unicode code point, or a complete user-perceived character? Does typing replace a selection? Should cutting an empty selection do anything?

The interaction layer needs those answers anyway. Giving the document methods names matching keyboard commands does not eliminate the product policy. It can put that policy somewhere the interaction engineer must inspect to understand their own feature.

Look at what those commands do to the text. Insertion replaces an empty range; deletion replaces a range with an empty string; typing over a selection replaces a nonempty range. They differ in how the interaction chooses the range and replacement, while sharing the document mutation. That existing overlap gives us a useful boundary.

Define Positions Before Implementing Operations

A general operation still needs precise semantics. In this example:

  • Positions are offsets measured in UTF-16 code units, matching JavaScript string indexing and String.prototype.slice.
  • A range includes start and excludes end.
  • Both bounds must be integers satisfying 0 <= start <= end <= length.
  • Equal bounds represent an empty range.
  • A range refers to the current document contents when the operation runs.

We now have fewer operation names, but the shortcut is not safe to implement yet. Its handler needs to know what a position means. Without these rules, replace would give callers a number while leaving its meaning uncertain.

For example, the string A😀B has four UTF-16 code units. The emoji occupies offsets one through three, so replacing the range [1, 3) removes the whole emoji. An offset of two is inside its surrogate pair.

The document operation below checks numeric bounds but does not establish grapheme boundaries. Callers implementing visible character deletion need a suitable segmentation policy; subtracting one from an offset is not a general implementation of Backspace. Combining marks and multi-code-point emoji make that distinction important even when surrogate pairs are handled correctly.

A Small Document Mechanism

Here is an implementation covering reading, insertion, deletion, and replacement:

class TextDocument {
  #value: string

  constructor(value: string) {
    this.#value = value
  }

  get length(): number {
    return this.#value.length
  }

  read(range: TextRange): string {
    this.#checkRange(range)
    return this.#value.slice(range.start, range.end)
  }

  replace(range: TextRange, replacement: string): void {
    this.#checkRange(range)
    this.#value =
      this.#value.slice(0, range.start) +
      replacement +
      this.#value.slice(range.end)
  }

  #checkRange({ start, end }: TextRange): void {
    if (
      !Number.isInteger(start) ||
      !Number.isInteger(end) ||
      start < 0 ||
      end < start ||
      end > this.#value.length
    ) {
      throw new RangeError('Expected a valid UTF-16 range')
    }
  }
}

The caller can replace a word directly:

const document = new TextDocument('Hello, team')
document.replace({ start: 7, end: 11 }, 'world')

const result = document.read({ start: 0, end: document.length })
// result: "Hello, world"

An insertion supplies equal bounds. A deletion supplies an empty replacement. An empty range with an empty replacement preserves the text naturally.

The implementation uses whole-string copies, so its performance characteristics follow that choice. It provides no revision tracking, collaborative editing, incremental layout, persistent storage, or history. Input coming from an untrusted boundary also needs validation before being treated as a typed string and range.

These limitations are part of evaluating the example honestly. A small operation vocabulary does not establish that this implementation is sufficient for a large document application.

Keep Interaction Policy With the Interaction

Return to the editor feature. Its interaction code now chooses which range an action affects. For paste or typing, it can replace a normalized selection and move the caret to the end of the inserted text:

function replaceSelection(
  document: TextDocument,
  selection: TextRange,
  insertedText: string,
): TextRange {
  document.replace(selection, insertedText)

  const caret = selection.start + insertedText.length
  return { start: caret, end: caret }
}

This function assumes the interaction adapter has converted its selection into an ordered range in the current document. The new caret uses UTF-16 units, consistent with both the document and the inserted string's length.

Backspace can use the same replacement operation after the interaction code determines the preceding deletion boundary. That boundary may depend on grapheme segmentation, a word-deletion modifier, or an active composition session. The document should not guess those policies from a method name.

Likewise, cutting a selection includes clipboard behavior and permission or user-gesture constraints. The document can remove the selected range, but the interaction owner still decides when the clipboard operation has succeeded and whether deletion should follow.

The handler may gain a few lines, and that can be a good trade. A developer changing keyboard behavior can see the relevant policy in the keyboard code. A developer changing document storage does not have to reconstruct clipboard permissions or composition behavior to preserve a range replacement.

Generality Can Remove Special Cases

The range model also clarifies selection state. A collapsed selection can be represented by equal start and end offsets instead of a separate “selection exists” flag.

Reading that range returns an empty string. Deleting it through replace(range, '') changes nothing. Replacing it with text inserts at the caret. The same operations handle the empty and nonempty cases.

This representation choice reduces special-case code. It works when the empty case has a sensible meaning under the ordinary operation.

There are still UI differences. A visible highlight may appear only for a nonempty selection, and a toolbar may disable a command when it has nothing useful to do. Those presentation choices do not require the document mechanism to maintain a second, potentially inconsistent representation of whether a range exists.

Generality becomes useful here because it gives several current behaviors one precise semantic model. Renaming several specialized branches to a single execute method would not accomplish the same thing.

Fewer Methods Are Helpful Only When Calls Stay Simple

An API can go too far in either direction.

A character-at-a-time interface may have very few operations, yet require every caller to loop over ranges. It pushes ordinary editing work upward and makes batching more difficult. A range operation covers the work at the level callers actually need.

At the other extreme, one method with a dozen flags can hide a collection of specialized operations behind a compact method count. Its signature may be smaller on a diagram, but consumers still have to understand the flags, their combinations, and their exceptions.

For the example, replace(range, text) has one coherent meaning. It does not need booleans for isBackspace, cameFromPaste, or updateSelection. Adding those would bring interaction decisions back into the document.

A useful API review therefore includes ordinary calls, not just the list of methods. Can current consumers express their operations directly? Are they writing repeated loops, decoding mode flags, or reaching into internals to finish the task?

Specialization Needs a Home

Undo tests whether we chose a useful operation or merely gave several commands a common name. After typing replaces a selection, can we describe the inverse without knowing which key or menu item caused the edit?

A general history mechanism can manage actions and grouping, while each action knows how to reverse its particular change. Higher-level interaction code chooses which changes belong in one user-visible undo step.

The general mechanism does not need to know every possible editor operation. The specialized actions do not need to know the history manager's internal representation. The grouping policy stays with the code that understands the interaction.

For example, a text action can record the affected start offset, the removed text, and the inserted text. It does not have to record whether a keypress, paste, or menu command requested the edit:

type TextEdit = {
  start: number
  removedText: string
  insertedText: string
}

function undoTextEdit(document: TextDocument, edit: TextEdit): void {
  document.replace(
    { start: edit.start, end: edit.start + edit.insertedText.length },
    edit.removedText,
  )
}

Record the removed text before applying the original replacement. This inverse assumes that the document is in the state immediately after that edit, as established by correctly ordered history. An offset alone is insufficient if unrelated or concurrent changes have moved the text; those systems need additional revision checks or position transformation. Restoring the caret, selection, and view also requires their own action information and grouping policy.

That is the broader design move: isolate specialized knowledge where it is useful, and let a general mechanism operate without repeatedly interpreting it.

It does not imply that this small TextDocument should acquire an undo framework immediately. Add such a mechanism when history is a requirement, and define what happens to text, caret, selection, and view together. A generic replace function does not supply those guarantees by itself.

Keep the Current Requirements as the Boundary

Several future needs could justify a different implementation or a richer contract. Large files may require a different text representation. Concurrent edits may require revisioned ranges or stable positions. A visible editor may need grapheme-aware navigation and a policy for preserving selection across changes.

The current range API does not solve those requirements. It provides a compact vocabulary for the supported operations, with explicit units and boundaries. That is a useful result even if it is never reused by a second application.

This distinction aligns with investing in current code design: improve the mechanism needed today while keeping speculative functionality outside the task. Generality is valuable when it removes unnecessary specialization from today's work.

Before adding an operation, ask which fact requires a new concept in the interface. A new keyboard shortcut may need only a different range. A new storage representation may need no caller change. A genuinely new requirement, such as applying edits against older revisions, may need an explicit addition.

For the keyboard shortcut that started this example, the decision is now manageable. If it selects a different range and replacement, implement that policy in the interaction layer and call the existing document operation. If it requires a guarantee the document cannot provide, such as editing an older revision safely, name that new guarantee before extending the API.

That gives generality a practical test: does it make the calls we already need easier to express and reason about? Here, one precise operation covers them while leaving visible interaction decisions with their owner.