All files / json-crdt-extensions/peritext/rga Point.ts

90.47% Statements 247/273
78.62% Branches 114/145
84.84% Functions 28/33
93.04% Lines 214/230

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 52961x 61x 61x 61x 61x                                         61x   225420x 225420x 225420x                   36x 36x                 83857x       78x 78x 78x                           141855x 141855x 97854x                           254387x 254387x 254387x 56205x 56205x 198182x 2004x 2004x   196178x 196178x 156811x 156811x 2690x 2690x 2690x 2638x 2638x 2638x 24706x 23973x   1905x                   444769x 444769x 444769x 336323x 336323x 336323x 336323x   123289x 123289x             315981x 315981x 315834x 315834x 293852x                 2133x 2133x 2133x 1998x                                               21408x 21407x 21407x   21407x 766x 1523x 766x 766x 766x 79x 79x   20641x 20641x 20641x 20603x 20603x 20603x 11191x   11229x     11308x 47358x 39464x 39464x   7894x 7894x 7894x 1271x 1271x   4685x                   33388x 33331x 33331x 33331x 33331x 33088x 32880x 32880x 19012x   19220x 19220x 43283x 31190x 31190x   12093x 12093x 10932x   1161x 1161x   8288x                   3104x 3104x 33x 33x 33x   3071x 3071x 3071x 3018x 3018x 3018x 3018x                   3578x 3578x 75x 75x 75x   3503x 3503x 3503x 2671x 2671x 2671x 2671x                             743852x               177335x               113178x                 164x 116x 116x                 158x 112x 112x 112x 112x 112x             1861x 1861x             106x 106x             295x 295x 295x             7x 7x 7x                   17913x 17913x 614x 556x 556x 556x 556x 556x     58x 58x   17299x 15886x 15886x                   43131x 43131x 1941x 636x 636x 636x 635x 635x 635x 635x 635x       1306x 1306x   41190x 27280x 27280x                 584x 342x                       7817x 7250x 7250x 7250x 4095x 4095x 40x 40x   4055x 4055x     3155x 3155x 259x 259x   2896x 2896x     6951x                     582x 582x 582x 576x 352x 352x 77x 73x   224x 224x 65x 63x     576x                   22x                                      
import {compare, type ITimestampStruct, printTs, equal, tick, containsId} from '../../../json-crdt-patch/clock';
import {Anchor} from './constants';
import {ChunkSlice} from '../util/ChunkSlice';
import {hashId, updateId} from '../../../json-crdt/hash';
import {Position} from '../constants';
import type {AbstractRga, Chunk} from '../../../json-crdt/nodes/rga';
import type {Stateful} from '../types';
import type {Printable} from 'tree-dump/lib/types';
 
/**
 * A "point" in a rich-text Peritext document. It is a combination of a
 * character ID and an anchor. Anchor specifies the side of the character to
 * which the point is attached. For example, a point with an anchor "before" .▢
 * points just before the character, while a point with an anchor "after" ▢.
 * points just after the character. Points attached to string characters are
 * referred to as *relative* points, while points attached to the beginning or
 * end of the string are referred to as *absolute* points.
 *
 * The *absolute* points are reference the string itself, by using the string's
 * ID as the character ID. The *absolute (abs) start* references the very start
 * of the string, before the first character, and even before any deleted
 * characters. The *absolute (abs) end* references the very end of the string,
 * after the last character, and even after any deleted characters at the end
 * of the string.
 */
export class Point<T = string> implements Pick<Stateful, 'refresh'>, Printable {
  constructor(
    protected readonly rga: AbstractRga<T>,
    public id: ITimestampStruct,
    public anchor: Anchor,
  ) {}
 
  /**
   * Overwrites the internal state of this point with the state of the given
   * point.
   *
   * @param point Point to copy.
   */
  public set(point: Point<T>): void {
    this.id = point.id;
    this.anchor = point.anchor;
  }
 
  /**
   * Creates a copy of this point.
   *
   * @returns Returns a new point with the same ID and anchor as this point.
   */
  public clone(): Point<T> {
    return new Point(this.rga, this.id, this.anchor);
  }
 
  public copy(mutate: (copy: Point<T>) => void): Point<T> {
    const copy = this.clone();
    mutate(copy);
    return copy;
  }
 
  /**
   * Compares two points by their character IDs and anchors. First, the character
   * IDs are compared. If they are equal, the anchors are compared. The anchor
   * "before" is considered less than the anchor "after".
   *
   * @param other The other point to compare to.
   * @returns Returns 0 if the two points are equal, -1 if this point is less
   *          than the other point, and 1 if this point is greater than the other
   *          point.
   */
  public cmp(other: Point<T>): -1 | 0 | 1 {
    const cmp = compare(this.id, other.id);
    if (cmp !== 0) return cmp;
    return (this.anchor - other.anchor) as -1 | 0 | 1;
  }
 
  /**
   * Compares two points by their spatial (view) location in the string. Takes
   * into account not only the character position in the view, but also handles
   * deleted characters, attachment anchors, and absolute points.
   *
   * @param other The other point to compare to.
   * @returns Returns 0 if the two points are equal, negative if this point is
   *          less than the other point, and positive if this point is greater
   *          than the other point.
   */
  public cmpSpatial(other: Point<T>): number {
    const thisId = this.id;
    const otherId = other.id;
    if (this.isAbs()) {
      const isStart = this.anchor === Anchor.After;
      return isStart ? (other.isAbsStart() ? 0 : -1) : other.isAbsEnd() ? 0 : 1;
    } else if (other.isAbs()) {
      const isStart = other.anchor === Anchor.After;
      return isStart ? (this.isAbsStart() ? 0 : 1) : this.isAbsEnd() ? 0 : -1;
    }
    const cmp0 = compare(thisId, otherId);
    if (!cmp0) return this.anchor - other.anchor;
    const cmp1 = this.pos() - other.pos();
    if (cmp1) return cmp1;
    let chunk = this.chunk();
    Iif (!chunk) return cmp0;
    if (containsId(chunk.id, chunk.span, otherId)) return thisId.time - otherId.time;
    const rga = this.rga;
    chunk = rga.next(chunk);
    while (chunk) {
      if (containsId(chunk.id, chunk.span, otherId)) return -1;
      chunk = rga.next(chunk);
    }
    return 1;
  }
 
  private _chunk: Chunk<T> | undefined;
 
  /**
   * @returns Returns the chunk that contains the character referenced by the
   *          point, or `undefined` if the chunk is not found.
   */
  public chunk(): Chunk<T> | undefined {
    let chunk = this._chunk;
    const id = this.id;
    if (chunk) {
      const chunkId = chunk.id;
      const chunkIdTime = chunkId.time;
      const idTime = id.time;
      if (id.sid === chunkId.sid && idTime >= chunkIdTime && idTime < chunkIdTime + chunk.span) return chunk;
    }
    this._chunk = chunk = this.rga.findById(this.id);
    return chunk;
  }
 
  /**
   * @returns Returns position of the character referenced by the point.
   */
  public pos(): number {
    const chunk = this.chunk();
    if (!chunk) return this.isAbsEnd() ? Position.AbsEnd : Position.AbsStart;
    const pos = this.rga.pos(chunk);
    if (chunk.del) return pos;
    return pos + this.id.time - chunk.id.time;
  }
 
  /**
   * @returns Returns the view position of the point, as if it is a caret in
   *          the text pointing between characters (0 is before the first
   *          character, 1 is after the first character, etc.).
   */
  public viewPos(): number {
    const pos = this.pos();
    const isAbs = equal(this.rga.id, this.id);
    if (isAbs) return this.anchor === Anchor.After ? 0 : this.rga.length();
    return this.anchor === Anchor.Before ? pos : pos + 1;
  }
 
  /**
   * @returns Returns `true` if the point is at the very start of the string, i.e.
   *     there are no visible characters before it.
   */
  public isStart(): boolean {
    const chunk = this.chunk();
    Iif (!chunk) return true;
    Iif (!chunk.del && chunk.id.time < this.id.time) return false;
    const l = chunk.l;
    return l ? !l.len : true;
  }
 
  /**
   * Goes to the next visible character in the string. The `move` parameter
   * specifies how many characters to move the cursor by. If the cursor reaches
   * the end of the string, it will return `undefined`.
   *
   * @param skip How many characters to move by.
   * @returns Next visible ID in string.
   */
  public nextId(skip: number = 1): ITimestampStruct | undefined {
    if (this.isAbsEnd()) return;
    let remaining: number = skip;
    const {id, rga} = this;
    let chunk: Chunk<T> | undefined;
    if (this.isAbsStart()) {
      chunk = rga.first();
      while (chunk && chunk.del) chunk = rga.next(chunk);
      Iif (!chunk) return;
      const span = chunk.span;
      if (remaining <= span) return tick(chunk.id, remaining - 1);
      remaining -= span;
      chunk = rga.next(chunk);
    } else {
      chunk = this.chunk();
      Iif (!chunk) return undefined;
      if (!chunk.del) {
        const offset = id.time - chunk.id.time;
        const span = chunk.span;
        if (offset + remaining < span) return tick(id, remaining);
        else remaining -= span - offset - 1;
      }
      chunk = rga.next(chunk);
    }
    let lastVisibleChunk: Chunk<T> | undefined;
    while (chunk && remaining >= 0) {
      if (chunk.del) {
        chunk = rga.next(chunk);
        continue;
      }
      lastVisibleChunk = chunk;
      const span = chunk.span;
      if (remaining <= span) return remaining > 1 ? tick(chunk.id, remaining - 1) : chunk.id;
      remaining -= span;
      chunk = rga.next(chunk);
    }
    if (remaining > 0) return;
    return lastVisibleChunk ? tick(lastVisibleChunk.id, lastVisibleChunk.span - 1) : undefined;
  }
 
  /**
   * @returns ID of the character that is `move` characters before the
   *          character referenced by the point, or `undefined` if there is no
   *          such character.
   */
  public prevId(skip: number = 1): ITimestampStruct | undefined {
    if (this.isAbsStart()) return;
    let remaining: number = skip;
    const {id, rga} = this;
    let chunk = this.chunk();
    if (!chunk) return rga.id;
    if (!chunk.del) {
      const offset = id.time - chunk.id.time;
      if (offset >= remaining) return tick(id, -remaining);
      remaining -= offset;
    }
    chunk = rga.prev(chunk);
    while (chunk) {
      if (chunk.del) {
        chunk = rga.prev(chunk);
        continue;
      }
      const span = chunk.span;
      if (remaining <= span) {
        return tick(chunk.id, span - remaining);
      }
      remaining -= span;
      chunk = rga.prev(chunk);
    }
    return;
  }
 
  /**
   * Returns one character to the left of the point, or `undefined` if there
   * is no such character. Skips any deleted characters. Handles absolute points.
   *
   * @returns A character slice to the left of the point.
   */
  public leftChar(): ChunkSlice<T> | undefined {
    const rga = this.rga;
    if (this.isAbsEnd()) {
      const res = rga.findChunk(rga.length() - 1);
      Iif (!res) return;
      return new ChunkSlice(res[0], res[1], 1);
    }
    const tmp = this.clone();
    tmp.refAfter();
    if (tmp.isAbsStart()) return;
    const chunk = tmp.chunk();
    Iif (!chunk || chunk.del) return;
    const off = tmp.id.time - chunk.id.time;
    return new ChunkSlice(chunk, off, 1);
  }
 
  /**
   * Returns one character to the right of the point, or `undefined` if there
   * is no such character. Skips any deleted characters. Handles absolute points.
   *
   * @returns A character slice to the right of the point.
   */
  public rightChar(): ChunkSlice<T> | undefined {
    const rga = this.rga;
    if (this.isAbsStart()) {
      const res = rga.findChunk(0);
      Iif (!res) return;
      return new ChunkSlice(res[0], res[1], 1);
    }
    const tmp = this.clone();
    tmp.refBefore();
    if (tmp.isAbsEnd()) return;
    const chunk = tmp.chunk();
    Iif (!chunk || chunk.del) return;
    const off = tmp.id.time - chunk.id.time;
    return new ChunkSlice(chunk, off, 1);
  }
 
  public char(): ChunkSlice<T> | undefined {
    return this.anchor === Anchor.Before ? this.rightChar() : this.leftChar();
  }
 
  /**
   * Checks if the point is an absolute point. An absolute point is a point that
   * references the string itself, rather than a character in the string. It can
   * be either the very start or the very end of the string.
   *
   * @returns Returns `true` if the point is an absolute point.
   */
  public isAbs(): boolean {
    return equal(this.id, this.rga.id);
  }
 
  /**
   * @returns Returns `true` if the point is an absolute point and is anchored
   *          before the first character in the string.
   */
  public isAbsStart(): boolean {
    return this.isAbs() && this.anchor === Anchor.After;
  }
 
  /**
   * @returns Returns `true` if the point is an absolute point and is anchored
   *          after the last character in the string.
   */
  public isAbsEnd(): boolean {
    return this.isAbs() && this.anchor === Anchor.Before;
  }
 
  /**
   * @returns Returns `true` if the point is exactly the relative start, i.e.
   *          it is attached to the first visible character in the string and
   *          anchored "before".
   */
  public isRelStart(): boolean {
    if (this.anchor !== Anchor.Before) return false;
    const id = this.rga.find(0);
    return !!id && equal(this.id, id);
  }
 
  /**
   * @returns Returns `true` if the point is exactly the relative end, i.e. it
   *          is attached to the last visible character in the string and
   *          anchored "after".
   */
  public isRelEnd(): boolean {
    if (this.anchor !== Anchor.After) return false;
    const rga = this.rga;
    const length = rga.length();
    Iif (length === 0) return false;
    const id = rga.find(length - 1);
    return !!id && equal(this.id, id);
  }
 
  /**
   * Sets the point to the absolute start of the string.
   */
  public refAbsStart(): void {
    this.id = this.rga.id;
    this.anchor = Anchor.After;
  }
 
  /**
   * Sets the point to the absolute end of the string.
   */
  public refAbsEnd(): void {
    this.id = this.rga.id;
    this.anchor = Anchor.Before;
  }
 
  /**
   * Sets the point to the relative start of the string.
   */
  public refStart(): this {
    this.refAbsStart();
    this.refBefore();
    return this;
  }
 
  /**
   * Sets the point to the relative end of the string.
   */
  public refEnd(): this {
    this.refAbsEnd();
    this.refAfter();
    return this;
  }
 
  /**
   * Modifies the location of the point, such that the view location remains
   * the same, but ensures that it is anchored before a character. Skips any
   * deleted characters (chunks), attaching the point to the next visible
   * character.
   */
  public refBefore(): void {
    const chunk = this.chunk();
    if (!chunk) {
      if (this.isAbsStart()) {
        const id = this.rga.find(0);
        if (id) {
          this.id = id;
          this.anchor = Anchor.Before;
          return;
        }
      }
      this.refAbsEnd();
      return;
    }
    if (!chunk.del && this.anchor === Anchor.Before) return;
    this.anchor = Anchor.Before;
    this.id = this.nextId() || this.rga.id;
  }
 
  /**
   * Modifies the location of the point, such that the view location remains
   * the same, but ensures that it is anchored after a character. Skips any
   * deleted characters (chunks), attaching the point to the next visible
   * character.
   */
  public refAfter(): void {
    const chunk = this.chunk();
    if (!chunk) {
      if (this.isAbsEnd()) {
        const rga = this.rga;
        const length = rga.length();
        if (length !== 0) {
          const id = rga.find(length - 1);
          if (id) {
            this.id = id;
            this.anchor = Anchor.After;
            return;
          }
        }
      }
      this.refAbsStart();
      return;
    }
    if (!chunk.del && this.anchor === Anchor.After) return;
    this.anchor = Anchor.After;
    this.id = this.prevId() || this.rga.id;
  }
 
  /**
   * Modifies the location of the point, such that the spatial location remains
   * the same and tries to preserve anchor location, but ensures that the point
   * references a visible (not deleted) character.
   */
  public refVisible(): void {
    if (this.anchor === Anchor.Before) this.refBefore();
    else this.refAfter();
  }
 
  /**
   * Moves point past given number of visible characters. Accepts positive
   * and negative distances.
   *
   * @param length How many characters to move by. Positive number moves the
   *     point to the right, negative number moves the point to the left.
   * @returns Returns `true` if the absolute end of the string is reached.
   */
  public step(length: number): boolean {
    if (!length) return this.isAbs();
    const anchor = this.anchor;
    if (anchor !== Anchor.After) this.refAfter();
    if (length > 0) {
      const nextId = this.nextId(length);
      if (!nextId) {
        this.refAbsEnd();
        return true;
      } else {
        this.id = nextId;
        if (anchor !== Anchor.After) this.refBefore();
      }
    } else {
      const prevId = this.prevId(-length);
      if (!prevId) {
        this.refAbsStart();
        return true;
      } else {
        this.id = prevId;
        if (anchor !== Anchor.After) this.refBefore();
      }
    }
    return false;
  }
 
  /**
   * Moves the to the next point, which does not necessarily result in a visible
   * character skip.
   *
   * @param length How many points to move by.
   * @returns Returns `true` if the absolute end of the string is reached.
   */
  public halfstep(length: number): boolean {
    this.refVisible();
    const isOdd = !!(length % 2);
    if (isOdd) {
      if (length > 0) {
        length--;
        if (this.anchor === Anchor.After) this.refBefore();
        else if (this.isAbs()) return true;
        else this.anchor = Anchor.After;
      } else {
        length++;
        if (this.anchor === Anchor.Before) this.refAfter();
        else if (this.isAbs()) return true;
        else this.anchor = Anchor.Before;
      }
    }
    return this.step(length / 2);
  }
 
  public key(): number {
    return hashId(this.id) + (this.anchor ? 0 : 1);
  }
 
  // ----------------------------------------------------------------- Stateful
 
  public refresh(): number {
    return updateId(this.anchor, this.id);
  }
 
  // ---------------------------------------------------------------- Printable
 
  public toStringName(): string {
    return 'Point';
  }
 
  public toString(tab: string = '', lite?: boolean): string {
    const name = lite ? '' : this.toStringName() + ' ';
    const pos = this.pos();
    const id = printTs(this.id);
    let char: string | undefined = this.char()?.view() as string | undefined;
    char = typeof char === 'string' ? JSON.stringify(char) : '▢';
    const anchor = this.anchor === Anchor.Before ? '.' + char : char + '.';
    return `${name}{ ${pos === Position.AbsEnd ? '∞' : pos}, ${id}, ${anchor} }`;
  }
}