|
| 1 | +import {Point} from '../rga/Point'; |
| 2 | +import {CursorAnchor} from '../slice/constants'; |
| 3 | +import {PersistedSlice} from '../slice/PersistedSlice'; |
| 4 | + |
| 5 | +export class Cursor<T = string> extends PersistedSlice<T> { |
| 6 | + public get anchorSide(): CursorAnchor { |
| 7 | + return this.type as CursorAnchor; |
| 8 | + } |
| 9 | + |
| 10 | + public set anchorSide(value: CursorAnchor) { |
| 11 | + this.update({type: value}); |
| 12 | + } |
| 13 | + |
| 14 | + public anchor(): Point<T> { |
| 15 | + return this.anchorSide === CursorAnchor.Start ? this.start : this.end; |
| 16 | + } |
| 17 | + |
| 18 | + public focus(): Point<T> { |
| 19 | + return this.anchorSide === CursorAnchor.Start ? this.end : this.start; |
| 20 | + } |
| 21 | + |
| 22 | + public set(start: Point<T>, end?: Point<T>, anchorSide: CursorAnchor = this.anchorSide): void { |
| 23 | + if (!end || end === start) end = start.clone(); |
| 24 | + super.set(start, end); |
| 25 | + this.update({ |
| 26 | + range: this, |
| 27 | + type: anchorSide, |
| 28 | + }); |
| 29 | + } |
| 30 | + |
| 31 | + public setAt(start: number, length: number = 0): void { |
| 32 | + let at = start; |
| 33 | + let len = length; |
| 34 | + if (len < 0) { |
| 35 | + at += len; |
| 36 | + len = -len; |
| 37 | + } |
| 38 | + super.setAt(at, len); |
| 39 | + this.anchorSide = length < 0 ? CursorAnchor.End : CursorAnchor.Start; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Move one of the edges of the cursor to a new point. |
| 44 | + * |
| 45 | + * @param point Point to set the edge to. |
| 46 | + * @param edge 0 for "focus", 1 for "anchor." |
| 47 | + */ |
| 48 | + public setEdge(point: Point<T>, edge: 0 | 1 = 0): void { |
| 49 | + if (this.start === this.end) this.end = this.end.clone(); |
| 50 | + let anchor = this.anchor(); |
| 51 | + let focus = this.focus(); |
| 52 | + if (edge === 0) focus = point; else anchor = point; |
| 53 | + if (focus.cmpSpatial(anchor) < 0) this.set(focus, anchor, CursorAnchor.End); |
| 54 | + else this.set(anchor, focus, CursorAnchor.Start); |
| 55 | + } |
| 56 | + |
| 57 | + public move(move: number): void { |
| 58 | + const {start, end} = this; |
| 59 | + start.move(move); |
| 60 | + if (start !== end) { |
| 61 | + end.move(move); |
| 62 | + } |
| 63 | + this.set(start, end); |
| 64 | + } |
| 65 | + |
| 66 | + // ---------------------------------------------------------------- Printable |
| 67 | + |
| 68 | + public toStringName(): string { |
| 69 | + const focusIcon = this.anchorSide === CursorAnchor.Start ? '.→|' : '|←.'; |
| 70 | + return `${super.toStringName()}, ${focusIcon}`; |
| 71 | + } |
| 72 | +} |
0 commit comments