json-joy
Version:
Collection of libraries for building collaborative editing apps.
57 lines (56 loc) • 1.92 kB
JavaScript
import { CONST, updateNum } from '../../../json-hash/hash';
import { updateId } from '../../../json-crdt/hash';
import { Timestamp, printTs } from '../../../json-crdt-patch/clock';
export class ChunkSlice {
off;
len;
constructor(
/** Chunk from which slice is computed. */
chunk,
/** Start offset of the slice within the chunk. */
off,
/** Length of the slice. */
len) {
this.off = off;
this.len = len;
this.chunk = chunk;
}
// -------------------------------------------------------------- IChunkSlice
chunk;
id() {
const id = this.chunk.id;
const off = this.off;
return !off ? id : new Timestamp(id.sid, id.time + off);
}
key() {
const id = this.chunk.id;
const sid = id.sid;
const time = id.time + this.off;
return sid.toString(36) + time.toString(36);
}
view() {
const offset = this.off;
return this.chunk.view().slice(offset, offset + this.len);
}
// ----------------------------------------------------------------- Stateful
hash = 0;
refresh() {
const { chunk, off, len } = this;
const delOffLenState = (((off << 16) + len) << 1) + +chunk.del;
let state = CONST.START_STATE;
state = updateId(state, chunk.id);
state = updateNum(state, delOffLenState);
return (this.hash = state);
}
// ---------------------------------------------------------------- Printable
toString(tab = '') {
const name = 'ChunkSlice';
const off = this.off;
const len = this.len;
const str = this.view() + '';
const truncate = str.length > 32;
const view = JSON.stringify(truncate ? str.slice(0, 32) : str) + (truncate ? ' …' : '');
const id = printTs(this.chunk.id);
return `${name} ${id} [${off}..${off + len}) ${view}`;
}
}