← Back to scenarios
ScenarioCatalog DB

Text editor memento

Store text-editor content snapshots so a user can undo changes.

Problem

A text editor must preserve prior document states for undo operations without exposing or coupling history management to the editor's internal content representation.

Related patterns

Implementations

Memento

TypeScriptApplication

Memento in TypeScript

Captures editor content snapshots so a history manager can restore earlier document states without exposing editor internals.

TypeScript
class EditorMemento {
  constructor(readonly content: string) {}
}

class TextEditor {
  private content = "";

  write(text: string) {
    this.content = text;
  }

  createMemento() {
    return new EditorMemento(this.content);
  }

  restore(memento: EditorMemento) {
    this.content = memento.content;
  }

  print() {
    console.log(this.content);
  }
}

class History {
  private readonly snapshots: EditorMemento[] = [];

  save(memento: EditorMemento) {
    this.snapshots.push(memento);
  }

  undo(): EditorMemento | undefined {
    return this.snapshots.pop();
  }
}

const editor = new TextEditor();
const history = new History();

editor.write("Draft version");
history.save(editor.createMemento());

editor.write("Published version");
editor.print();

const previousVersion = history.undo();

if (previousVersion) {
  editor.restore(previousVersion);
}

editor.print();

Associated technologies