Skip to content

Instantly share code, notes, and snippets.

@zicklag
Created January 24, 2025 23:29
Show Gist options
  • Save zicklag/a0620ab2ed50f71e87e205d00fe73478 to your computer and use it in GitHub Desktop.
Save zicklag/a0620ab2ed50f71e87e205d00fe73478 to your computer and use it in GitHub Desktop.
Loro timetravel
// Get the snapshot for your doc
let snapshot = fetchSnapshot();
// Import your doc
const doc = new LoroDoc();
doc.import(snapshot);
// NOTE: Make sure that whenever you wrote to the doc you enabled timestamps.
// This is important to make sure that we have a simple way to order
// changes based on user intuition.
//
// Like this, but it's not important for us here because we are just reading
// the doc
doc.setRecordTimestamp(true);
// Collect all changes from the document
const changes = doc.getAllChanges();
// Collect list of timestamps for all changes and sorted
const timestamps = [...changes.values()].flat().map(x => x.timestamp);
timestamps.sort((a, b) => a -b)
// Helper for getting the frontier for a timestamp
const getFrontierForTimestamp = (ts: number): { peer: string; counter: number }[] => {
const frontiers = [] as { peer: string; counter: number }[];
// Record the highest counter for each peer where it's change is not higher than
// our target timestamp.
changes.forEach((changes, peer) => {
let counter = 0;
for (const change of changes) {
if (change.timestamp <= ts) {
counter = Math.max(counter, change.counter + change.length - 1);
}
}
if (counter > 0) {
frontiers.push({ counter, peer });
}
});
return frontiers;
};
// Now we get get the frontier for our slider index
let sliderIdx = 3;
const timestamp = timestamps[sliderIdx - 1];
const frontiers = getFrontierForTimestamp(timestamp);
doc.checkout(frontiers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment