Skip to content

Commit

Permalink
Merge pull request #565 from streamich/peritext-slices
Browse files Browse the repository at this point in the history
Peritext `Point` class implementation
  • Loading branch information
streamich authored Apr 6, 2024
2 parents 0838b13 + 45b1241 commit 97c213c
Show file tree
Hide file tree
Showing 12 changed files with 1,588 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/json-crdt-extensions/peritext/Peritext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {Anchor} from './constants';
import {Point} from './point/Point';
import {printTree} from '../../util/print/printTree';
import {ArrNode, StrNode} from '../../json-crdt/nodes';
import {type ITimestampStruct} from '../../json-crdt-patch/clock';
import type {Model} from '../../json-crdt/model';
import type {Printable} from '../../util/print/types';

export class Peritext implements Printable {
constructor(
public readonly model: Model,
public readonly str: StrNode,
slices: ArrNode,
) {}

public point(id: ITimestampStruct, anchor: Anchor = Anchor.After): Point {
return new Point(this, id, anchor);
}

public pointAt(pos: number, anchor: Anchor = Anchor.Before): Point {
const str = this.str;
const id = str.find(pos);
if (!id) return this.point(str.id, Anchor.After);
return this.point(id, anchor);
}

public pointAtStart(): Point {
return this.point(this.str.id, Anchor.After);
}

public pointAtEnd(): Point {
return this.point(this.str.id, Anchor.Before);
}

// ---------------------------------------------------------------- Printable

public toString(tab: string = ''): string {
const nl = () => '';
return this.constructor.name + printTree(tab, [(tab) => this.str.toString(tab)]);
}
}
43 changes: 43 additions & 0 deletions src/json-crdt-extensions/peritext/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
export const enum Anchor {
Before = 0,
After = 1,
}

export const enum SliceHeaderMask {
X1Anchor = 0b1,
X2Anchor = 0b10,
Behavior = 0b11100,
}

export const enum SliceHeaderShift {
X1Anchor = 0,
X2Anchor = 1,
Behavior = 2,
}

export const enum SliceBehavior {
/**
* A Split slice, which is used to mark a block split position in the document.
* For example, paragraph, heading, blockquote, etc.
*/
Split = 0b000,

/**
* Appends attributes to a stack of attributes for a specific slice type. This
* is useful when the same slice type can have multiple attributes, like
* inline comments, highlights, etc.
*/
Stack = 0b001,

/**
* Overwrites the stack of attributes for a specific slice type. Could be used
* for simple inline formatting, like bold, italic, etc.
*/
Overwrite = 0b010,

/**
* Removes all attributes for a specific slice type. For example, could be
* used to re-verse inline formatting, like bold, italic, etc.
*/
Erase = 0b011,
}
Loading

0 comments on commit 97c213c

Please sign in to comment.