Search

Undo/Redo

Handling Data

Save, undo and restore changes in the timeline.

Undo/Redo
View live example →

Change the timeline state by pinning or focusing entities or by using the controls below the timeline.

Calling set() updates the state with detected changes.

Use the Undo and Redo buttons to cycle through the changes and replay the states.

See Also

Change the timeline state by pinning or focusing entities or by using the controls below the timeline.

Use the Undo and Redo buttons to cycle through the changes and replay the states.

See Also

import { createTimeline } from "kronograph";
import data from "./data";

const timeline = createTimeline("my-timeline");

const initialRange = {
  start: 1755159741000,
  end: 1755194919000,
};

const initialState = {
  entities: data.entities,
  events: data.events,
  focus: [],
  pin: [],
  ordering: "shorteneventlines",
};

let undoStack = [];
let redoStack = [];
let currentState;

function applyTimelineState(newState) {
  const oldPin = currentState ? currentState.pin : initialState.pin;
  currentState = newState;

  timeline.set({ entities: newState.entities, events: newState.events });
  timeline.focus(newState.focus);
  timeline.setOrdering(newState.ordering);
  timeline.pin(newState.pin, true);

  const newPinIndex = {};
  newState.pin.forEach((id) => {
    newPinIndex[id] = true;
  });
  timeline.pin(
    oldPin.filter((id) => !newPinIndex[id]),
    false
  );
}

function setTimelineState(newState) {
  applyTimelineState(newState);
  updateUIControls();
}

/**
 * Replace current timeline state with the new state, pushing the old onto the undo stack
 */
function pushNewTimelineState(newState) {
  undoStack = [currentState, ...undoStack];
  redoStack = [];
  setTimelineState(newState);
}

function doUndo() {
  if (undoStack.length > 0) {
    const [first, ...rest] = undoStack;
    redoStack = [currentState, ...redoStack];
    undoStack = rest;
    setTimelineState(first);
  }
}

function doRedo() {
  if (redoStack.length > 0) {
    const [first, ...rest] = redoStack;
    redoStack = rest;
    undoStack = [currentState, ...undoStack];
    setTimelineState(first);
  }
}

const removeEntityButton = document.getElementById("removeentity");
const removeEventButton = document.getElementById("removeevent");
const undoButton = document.getElementById("undo");
const redoButton = document.getElementById("redo");

setTimelineState({ ...initialState });
timeline.range(initialRange.start, initialRange.end);

let nextEntity = 1;
function makeNewEntityId() {
  return `Entity ${nextEntity++}`;
}

let nextEvent = 1;
function makeNewEventId() {
  return `Event ${nextEvent++}`;
}

function addEntityWithEvent() {
  const newEntityId = makeNewEntityId();
  const newEntities = { ...currentState.entities, [newEntityId]: {} };
  const newEntityIds = Object.keys(newEntities);
  const entityCount = newEntityIds.length;

  // Join this entity to another (or itself) with an event
  const entityIds = [newEntityId];
  const entity2Index = Math.floor(Math.random() * entityCount);
  const entity2Id = newEntityIds[entity2Index];
  if (entity2Id !== newEntityId) {
    entityIds.push(entity2Id);
  }

  const time = initialRange.start + Math.random() * (initialRange.end - initialRange.start);
  const event = { entityIds, time };
  const newEvents = { ...currentState.events, [makeNewEventId()]: event };

  pushNewTimelineState({ ...currentState, entities: newEntities, events: newEvents });
}

function removeEvent() {
  const currentEventIds = Object.keys(currentState.events);
  const indexToRemove = Math.floor(Math.random() * currentEventIds.length);
  const idToRemove = currentEventIds[indexToRemove];
  const { [idToRemove]: eventToRemove, ...newEvents } = currentState.events;

  pushNewTimelineState({ ...currentState, events: newEvents });
}

function removeEntity() {
  // Remove an entity and all events it participates in
  const currentEntityIds = Object.keys(currentState.entities);
  const indexToRemove = Math.floor(Math.random() * currentEntityIds.length);
  const idToRemove = currentEntityIds[indexToRemove];
  const { [idToRemove]: entityToRemove, ...newEntities } = currentState.entities;
  const newEvents = {};
  Object.keys(currentState.events).forEach((eventId) => {
    const event = currentState.events[eventId];
    if (event.entityIds.every((id) => newEntities[id])) {
      newEvents[eventId] = event;
    }
  });

  pushNewTimelineState({ ...currentState, entities: newEntities, events: newEvents });
}

// If the user caused the change, treat as an entry in the undo/redo stack
// If the change happened automatically, amend the existing state without adding to the stack
timeline.on("focus", (event) => {
  const { why, focus } = event;
  const newState = { ...currentState, focus };
  if (why === "user") {
    pushNewTimelineState(newState);
  } else {
    // Not a user action, so just update existing state without adding to stack
    setTimelineState(newState);
  }
});

timeline.on("pin", (event) => {
  const { why, pin } = event;
  const newState = { ...currentState, pin };
  if (why === "user") {
    pushNewTimelineState(newState);
  } else {
    // Not a user action, so just update existing state without adding to stack
    setTimelineState(newState);
  }
});

function updateUIControls() {
  document.getElementById("undo-length").innerHTML = `(${undoStack.length})`;
  document.getElementById("redo-length").innerHTML = `(${redoStack.length})`;
  document.getElementById("ordering-select").value = currentState.ordering;
  undoButton.disabled = undoStack.length === 0;
  redoButton.disabled = redoStack.length === 0;
  removeEntityButton.disabled = Object.keys(currentState.entities).length === 0;
  removeEventButton.disabled = Object.keys(currentState.events).length === 0;
}

undoButton.addEventListener("click", doUndo);
redoButton.addEventListener("click", doRedo);

document.getElementById("reset").addEventListener("click", () => {
  undoStack = [];
  redoStack = [];
  setTimelineState({ ...initialState });
});

document.getElementById("ordering-select").addEventListener("change", (e) => {
  pushNewTimelineState({ ...currentState, ordering: e.target.value });
});

document.getElementById("addentity").addEventListener("click", addEntityWithEvent);
removeEntityButton.addEventListener("click", removeEntity);
removeEventButton.addEventListener("click", removeEvent);
export default {
  entities: {
    "smith-johnathan-151": {
      label: "John Smith",
    },
    "west-josephine-126": {
      label: "Josephine West",
    },
    "roberts-nathaniel-023": {
      label: "Nathan Roberts",
    },
    "baxter-eleanor-004": {
      label: "Ella Baxter",
    },
  },
  events: {
    "Email 1": {
      entityIds: ["smith-johnathan-151", "roberts-nathaniel-023"],
      time: new Date(2025, 7, 14, 8, 49),
    },
    "Email 2": {
      entityIds: ["smith-johnathan-151", "baxter-eleanor-004"],
      time: new Date(2025, 7, 14, 8, 56),
    },
    "Email 3": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 9, 2),
    },
    "Email 4": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 9, 27),
    },
    "Email 5": {
      entityIds: ["baxter-eleanor-004", "roberts-nathaniel-023"],
      time: new Date(2025, 7, 14, 10, 20),
    },
    "Email 6": {
      entityIds: ["roberts-nathaniel-023", "smith-johnathan-151"],
      time: new Date(2025, 7, 14, 10, 30),
    },
    "Email 7": {
      entityIds: ["west-josephine-126", "smith-johnathan-151"],
      time: new Date(2025, 7, 14, 10, 40),
    },
    "Email 8": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 10, 51),
    },
    "Email 9": {
      entityIds: ["west-josephine-126", "smith-johnathan-151"],
      time: new Date(2025, 7, 14, 12, 5),
    },
    "Email 10": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 14, 37),
    },
    "Email 11": {
      entityIds: ["baxter-eleanor-004", "west-josephine-126"],
      time: new Date(2025, 7, 14, 16, 7),
    },
    "Email 12": {
      entityIds: ["west-josephine-126", "roberts-nathaniel-023"],
      time: new Date(2025, 7, 14, 17, 42),
    },
  },
};
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="@ci/theme/kg/css/examples.css" />
  </head>
  <body>
    <div class="story">
      <div class="story__timeline" id="my-timeline"></div>
      <div class="story__controls story__controls--row">
        <div>
          <div class="story__controls__button-container">
            <button class="button" id="addentity" type="button">Add entity/event</button>
            <button class="button button--neutral" id="removeentity" type="button">
              Remove an entity
            </button>
            <button class="button button--neutral" id="removeevent" type="button">
              Remove an event
            </button>
          </div>
          <br />
          <div class="story__controls__button-container">
            <label for="ordering-select">Ordering</label>
            <select id="ordering-select" class="select width-100pct">
              <option value="alphabetical">Alphabetical</option>
              <option value="firstevent">First event</option>
              <option value="lastevent">Last event</option>
              <option value="keyorder">Key order</option>
              <option value="shorteneventlines" selected>Shorten event lines</option>
            </select>
          </div>
          <br />
          <div class="story__controls__button-container">
            <button class="button" id="undo" type="button">
              Undo&nbsp;
              <span class="count" id="undo-length">(0)</span>
            </button>
            <button class="button" id="redo" type="button">
              Redo&nbsp;
              <span class="count" id="redo-length">(0)</span>
            </button>
            <button class="button button--neutral" id="reset" type="button">Reset</button>
          </div>
        </div>
      </div>
    </div>
    <script type="module" src="./code.js"></script>
  </body>
</html>
import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import Timeline from "kronograph/react/Timeline";
import data from "./data";

const initialRange = {
  start: 1755159741000,
  end: 1755194919000,
};

const initialTimelineState = {
  entities: data.entities,
  events: data.events,
  focus: [],
  pin: [],
  ordering: "shorteneventlines",
};

let nextEntity = 1;
function makeNewEntityId() {
  return `Entity ${nextEntity++}`;
}

let nextEvent = 1;
function makeNewEventId() {
  return `Event ${nextEvent++}`;
}

export const Demo = () => {
  const [undo, setUndo] = useState([]);
  const [redo, setRedo] = useState([]);
  const [timelineState, setTimelineState] = useState(initialTimelineState);

  function pushNewTimelineState(newState) {
    setUndo([timelineState, ...undo]);
    setRedo([]);
    setTimelineState(newState);
  }

  function changeHandler(event) {
    const { focus, pin, why } = event;

    if (focus || pin) {
      const newTimelineState = { ...timelineState };
      if (focus) {
        newTimelineState.focus = focus;
      }
      if (pin) {
        newTimelineState.pin = pin;
      }
      if (why === "user") {
        // Push onto stack
        pushNewTimelineState(newTimelineState);
      } else {
        // Not a user action, so just update existing state without adding to stack
        setTimelineState(newTimelineState);
      }
    }
  }

  function doUndo() {
    if (undo.length > 0) {
      const [first, ...rest] = undo;
      setRedo([timelineState, ...redo]);
      setUndo(rest);
      setTimelineState(first);
    }
  }

  function doRedo() {
    if (redo.length > 0) {
      const [first, ...rest] = redo;
      setRedo(rest);
      setUndo([timelineState, ...undo]);
      setTimelineState(first);
    }
  }

  function doReset() {
    setUndo([]);
    setRedo([]);
    setTimelineState({ ...initialTimelineState });
  }

  function setOrdering(newOrdering) {
    pushNewTimelineState({ ...timelineState, ordering: newOrdering });
  }

  function addEntityWithEvent() {
    const newEntityId = makeNewEntityId();
    const newEntities = { ...timelineState.entities, [newEntityId]: {} };
    const newEntityIds = Object.keys(newEntities);
    const entityCount = newEntityIds.length;

    // Join this entity to another (or itself) with an event
    const entityIds = [newEntityId];
    const entity2Index = Math.floor(Math.random() * entityCount);
    const entity2Id = newEntityIds[entity2Index];
    if (entity2Id !== newEntityId) {
      entityIds.push(entity2Id);
    }

    const time = initialRange.start + Math.random() * (initialRange.end - initialRange.start);
    const event = { entityIds, time };
    const newEvents = { ...timelineState.events, [makeNewEventId()]: event };

    pushNewTimelineState({ ...timelineState, entities: newEntities, events: newEvents });
  }

  function removeEvent() {
    const currentEventIds = Object.keys(timelineState.events);
    const indexToRemove = Math.floor(Math.random() * currentEventIds.length);
    const idToRemove = currentEventIds[indexToRemove];
    const { [idToRemove]: eventToRemove, ...newEvents } = timelineState.events;

    pushNewTimelineState({ ...timelineState, events: newEvents });
  }

  function removeEntity() {
    // Remove an entity and all events it participates in
    const currentEntityIds = Object.keys(timelineState.entities);
    const indexToRemove = Math.floor(Math.random() * currentEntityIds.length);
    const idToRemove = currentEntityIds[indexToRemove];
    const { [idToRemove]: entityToRemove, ...newEntities } = timelineState.entities;
    const newEvents = {};
    Object.keys(timelineState.events).forEach((eventId) => {
      const event = timelineState.events[eventId];
      if (event.entityIds.every((id) => newEntities[id])) {
        newEvents[eventId] = event;
      }
    });

    pushNewTimelineState({ ...timelineState, entities: newEntities, events: newEvents });
  }

  return (
    <div className="story">
      <Timeline
        className="story__timeline"
        entities={timelineState.entities}
        events={timelineState.events}
        focus={timelineState.focus}
        ordering={timelineState.ordering}
        pin={timelineState.pin}
        range={initialRange}
        onTimelineChange={changeHandler}
      />
      <div className="story__controls story__controls--row">
        <div>
          <div className="story__controls__button-container">
            <button className="button" key="addentity" type="button" onClick={addEntityWithEvent}>
              Add entity/event
            </button>
            <button
              className="button button--neutral"
              key="removeentity"
              type="button"
              disabled={Object.keys(timelineState.entities).length === 0}
              onClick={removeEntity}
            >
              Remove an entity
            </button>
            <button
              className="button button--neutral"
              key="removeevent"
              type="button"
              disabled={Object.keys(timelineState.events).length === 0}
              onClick={removeEvent}
            >
              Remove an event
            </button>
          </div>
          <br />
          <div className="story__controls__button-container">
            <label htmlFor="ordering-select">Ordering</label>
            <select
              id="ordering-select"
              className="select width-100pct"
              value={timelineState.ordering}
              onChange={(e) => {
                setOrdering(e.target.value);
              }}
            >
              <option value="alphabetical">Alphabetical</option>
              <option value="firstevent">First event</option>
              <option value="lastevent">Last event</option>
              <option value="keyorder">Key order</option>
              <option value="shorteneventlines">Shorten event lines</option>
            </select>
          </div>
          <br />
          <div className="story__controls__button-container">
            <button
              className="button"
              key="undo"
              type="button"
              disabled={undo.length === 0}
              onClick={doUndo}
            >
              Undo&nbsp;
              <span className="count">({undo.length})</span>
            </button>
            <button
              className="button"
              key="redo"
              type="button"
              disabled={redo.length === 0}
              onClick={doRedo}
            >
              Redo&nbsp;
              <span className="count">({redo.length})</span>
            </button>
            <button className="button button--neutral" key="reset" type="button" onClick={doReset}>
              Reset
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

const root = createRoot(document.getElementById("my-timeline"));
root.render(<Demo />);
export default {
  entities: {
    "smith-johnathan-151": {
      label: "John Smith",
    },
    "west-josephine-126": {
      label: "Josephine West",
    },
    "roberts-nathaniel-023": {
      label: "Nathan Roberts",
    },
    "baxter-eleanor-004": {
      label: "Ella Baxter",
    },
  },
  events: {
    "Email 1": {
      entityIds: ["smith-johnathan-151", "roberts-nathaniel-023"],
      time: new Date(2025, 7, 14, 8, 49),
    },
    "Email 2": {
      entityIds: ["smith-johnathan-151", "baxter-eleanor-004"],
      time: new Date(2025, 7, 14, 8, 56),
    },
    "Email 3": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 9, 2),
    },
    "Email 4": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 9, 27),
    },
    "Email 5": {
      entityIds: ["baxter-eleanor-004", "roberts-nathaniel-023"],
      time: new Date(2025, 7, 14, 10, 20),
    },
    "Email 6": {
      entityIds: ["roberts-nathaniel-023", "smith-johnathan-151"],
      time: new Date(2025, 7, 14, 10, 30),
    },
    "Email 7": {
      entityIds: ["west-josephine-126", "smith-johnathan-151"],
      time: new Date(2025, 7, 14, 10, 40),
    },
    "Email 8": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 10, 51),
    },
    "Email 9": {
      entityIds: ["west-josephine-126", "smith-johnathan-151"],
      time: new Date(2025, 7, 14, 12, 5),
    },
    "Email 10": {
      entityIds: ["smith-johnathan-151", "west-josephine-126"],
      time: new Date(2025, 7, 14, 14, 37),
    },
    "Email 11": {
      entityIds: ["baxter-eleanor-004", "west-josephine-126"],
      time: new Date(2025, 7, 14, 16, 7),
    },
    "Email 12": {
      entityIds: ["west-josephine-126", "roberts-nathaniel-023"],
      time: new Date(2025, 7, 14, 17, 42),
    },
  },
};
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="@ci/theme/kg/css/examples.css" />
  </head>
  <body>
    <div id="my-timeline" style="height: 100vh"></div>
    <script type="module" src="./code.jsx"></script>
  </body>
</html>

Terms of use

These terms do not alter or supersede any existing agreements between you (or your employer) and us.

By accessing or using any Content you agree to be bound by these Terms of Use. Please review these terms carefully before using the website.

The contents of this website, including but not limited to any text, code samples, API references, schemas, interactive tools, and other materials (collectively, the 'Content'), are made available for informational and internal evaluation purposes only. All intellectual property rights in the Content are reserved. No licence is granted to use the Content for any commercial purpose, or to copy, distribute, modify, reverse-engineer, or incorporate any part of the Content into any product or service, without our prior written consent.

This Content is provided “as is” and “as available,” without any representations, warranties, or guarantees of any kind, whether express or implied, including but not limited to implied warranties of merchantability, fitness for a particular purpose, non-infringement, or accuracy. To the fullest extent permitted by applicable law, we expressly exclude and disclaim all implied warranties, conditions, and other terms that might otherwise be implied.

We disclaim all liability for any loss or damage, whether direct, indirect, incidental, consequential, or otherwise, arising from any reliance placed on the Content or from your use of it, to the fullest extent permitted by applicable law. By continuing to access or use the Content, you acknowledge and agree to these terms.