1 import { BatchDocumentUpdates } from './BatchDocumentUpdates'
2 import { mergeUpdates } from 'yjs'
3 import type { VersionHistoryBatch, VersionHistoryUpdate } from './VersionHistoryBatch'
4 import { DateFormatter } from './DateFormatter'
7 * How many DUs should make up a presentable revision in the history viewer. If the threshold is 10 and a
8 * document has 100 DUs, the UI will show 10 revisions.
10 const BatchThreshold = 10
12 export class NativeVersionHistory {
13 private versionHistoryBatches: VersionHistoryBatch[] = []
14 private _batchDocumentUpdates = new BatchDocumentUpdates()
15 private dateFormatter = new DateFormatter()
17 constructor(updates: VersionHistoryUpdate[]) {
18 this.versionHistoryBatches = this._batchDocumentUpdates.execute(updates, BatchThreshold).getValue()
22 return this.versionHistoryBatches
25 public getTimestampForBatch(batch: VersionHistoryBatch) {
26 const lastUpdate = batch[batch.length - 1]
27 return lastUpdate.timestamp
30 public getFormattedDateAndTimeForBatch(batch: VersionHistoryBatch) {
31 const timestamp = this.getTimestampForBatch(batch)
32 const date = new Date(timestamp)
33 return date.toLocaleString()
36 public getShortFormattedDateAndTimeForBatch(batch: VersionHistoryBatch) {
37 const timestamp = this.getTimestampForBatch(batch)
38 const date = new Date(timestamp)
39 return date.toLocaleString('en-US', {
48 public getFormattedDateForBatch(batch: VersionHistoryBatch) {
49 return this.dateFormatter.formatDate(this.getTimestampForBatch(batch))
52 public isCurrentBatchIndex(index: number) {
53 return index === this.batches.length - 1
56 public getFormattedTimeForBatch(batch: VersionHistoryBatch) {
57 const timestamp = this.getTimestampForBatch(batch)
58 return this.dateFormatter.formatTime(timestamp)
61 public getFormattedBatchGroups() {
62 const formattedBatchGroups: {
64 batchIndexes: { batchIndex: number; formattedTime: string }[]
67 this.batches.forEach((batch, batchIndex) => {
68 const formattedDate = this.getFormattedDateForBatch(batch)
69 const formattedTime = this.getFormattedTimeForBatch(batch)
71 if (lastGroupKey === formattedDate) {
72 formattedBatchGroups[0].batchIndexes.unshift({ batchIndex, formattedTime })
74 formattedBatchGroups.unshift({ formattedDate, batchIndexes: [{ batchIndex, formattedTime }] })
77 lastGroupKey = formattedDate
79 return formattedBatchGroups
82 public getMergedUpdateForBatchIndex(index: number): Uint8Array {
83 const flattenedBatches = this.versionHistoryBatches.slice(0, index + 1).flat()
84 const updates = flattenedBatches.map((du) => du.content)
85 const merged = mergeUpdates(updates)