All files / json-crdt-peritext-ui/events/defaults PeritextEventDefaults.ts

33.55% Statements 103/307
30.26% Branches 46/152
52.38% Functions 11/21
35.74% Lines 94/263

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 4525x 5x 5x 5x                       5x   5x 2220x                                               5x       324x                                                           324x 324x 324x       2466x 2466x                 4764x 2166x 2166x 2166x 2220x   2220x         2220x 1428x 2220x 1356x 1356x 708x     2166x 336x 336x 336x 336x   2166x       2256x 2148x 2148x           2148x 18x       324x   324x 210x 210x 210x 210x 210x     324x 612x 612x 612x 612x 612x 612x               612x       612x 612x 612x 612x 612x 612x 612x   612x 612x     324x 4152x 4152x 1536x 1536x   2616x 2616x 2616x 2616x 2616x 2586x       324x 6x 6x 6x 6x 6x 6x             6x 6x 6x                       6x     324x 102x 102x 102x 102x 102x   102x 102x                                 102x     324x                                                                                                                                                                                                                                                                                                                                                                                                       324x                
import {Anchor} from '../../../json-crdt-extensions/peritext/rga/constants';
import {placeCursor} from './annals';
import {Cursor} from '../../../json-crdt-extensions/peritext/editor/Cursor';
import {CursorAnchor, type Peritext} from '../../../json-crdt-extensions/peritext';
import type {Range} from '../../../json-crdt-extensions/peritext/rga/Range';
import type {PeritextDataTransfer} from '../../../json-crdt-extensions/peritext/transfer/PeritextDataTransfer';
import type {PeritextEventHandlerMap, PeritextEventTarget} from '../PeritextEventTarget';
import type {EditorSlices} from '../../../json-crdt-extensions/peritext/editor/EditorSlices';
import type * as events from '../types';
import type {PeritextClipboard, PeritextClipboardData} from '../clipboard/types';
import type {UndoCollector} from '../../types';
import type {UiHandle} from './ui/UiHandle';
import type {Point} from '../../../json-crdt-extensions/peritext/rga/Point';
import type {EditorUi} from '../../../json-crdt-extensions/peritext/editor/types';
 
const toText = (buf: Uint8Array) => new TextDecoder().decode(buf);
 
const getEdge = (start: Point, end: Point, anchor: CursorAnchor, edge: events.SelectionMoveInstruction[0]): Point =>
  edge === 'start'
    ? start
    : edge === 'end'
      ? end
      : edge === 'focus'
        ? anchor === CursorAnchor.Start
          ? end
          : start
        : anchor === CursorAnchor.Start
          ? start
          : end;
 
export interface PeritextEventDefaultsOpts {
  clipboard?: PeritextClipboard;
  transfer?: PeritextDataTransfer;
}
 
/**
 * Implementation of default handlers for Peritext events, such as "insert",
 * "delete", "cursor", etc. These implementations are used by the
 * {@link PeritextEventTarget} to provide default behavior for each event type.
 * If `event.preventDefault()` is called on a Peritext event, the default handler
 * will not be executed.
 */
export class PeritextEventDefaults implements PeritextEventHandlerMap {
  public undo?: UndoCollector;
  public ui?: UiHandle;
 
  protected editorUi: EditorUi = {
    eol: (point: Point, steps: number): Point | undefined => {
      const ui = this.ui;
      Iif (!ui) return;
      const res = ui.getLineEnd(point, steps > 0);
      return res ? res[0] : void 0;
    },
    vert: (point: Point, steps: number): Point | undefined => {
      const ui = this.ui;
      Iif (!ui) return;
      const pos = ui.pointX(point);
      Iif (!pos) return;
      const currLine = ui.getLineInfo(point);
      Iif (!currLine) return;
      const x = pos[0];
      const iterations = Math.abs(steps);
      let nextPoint = point;
      for (let i = 0; i < iterations; i++) {
        const nextLine = steps > 0 ? ui.getNextLineInfo(currLine) : ui.getNextLineInfo(currLine, -1);
        Iif (!nextLine) break;
        nextPoint = ui.findPointAtX(x, nextLine);
        Iif (!nextPoint) break;
        if (point.anchor === Anchor.Before) nextPoint.refBefore();
        else nextPoint.refAfter();
      }
      return nextPoint;
    },
  };
 
  public constructor(
    public readonly txt: Peritext,
    public readonly et: PeritextEventTarget,
    public readonly opts: PeritextEventDefaultsOpts = {},
  ) {}
 
  protected getSelSet({at}: events.SelectionDetailPart): events.SelectionSet {
    const {editor} = this.txt;
    return at ? [editor.sel2range(at)[0]] : editor.cursors();
  }
 
  protected moveRange(
    start: Point,
    end: Point,
    anchor: CursorAnchor,
    move?: events.SelectionMoveInstruction[],
  ): [start: Point, end: Point, anchor: CursorAnchor] {
    if (!move) return [start, end, anchor];
    const {txt, editorUi} = this;
    const start0 = start;
    for (const [edge, to, len, collapse] of move) {
      const point = getEdge(start, end, anchor, edge);
      const point2 =
        typeof to === 'string'
          ? len
            ? txt.editor.skip(point, len, to ?? 'char', editorUi)
            : point.clone()
          : txt.editor.pos2point(to);
      if (point === start) start = point2;
      else end = point2;
      if (collapse) {
        if (to !== 'point') point2.refAfter();
        if (point === start0) end = point2.clone();
        else start = point2.clone();
      }
    }
    if (start.cmpSpatial(end) > 0) {
      const tmp = start;
      start = end;
      end = tmp;
      anchor = anchor === CursorAnchor.Start ? CursorAnchor.End : CursorAnchor.Start;
    }
    return [start, end, anchor];
  }
 
  protected moveSelSet(set: events.SelectionSet, {move}: events.SelectionMoveDetailPart): void {
    if (!move) return;
    for (const selection of set) {
      const [start, end, anchor] = this.moveRange(
        selection.start,
        selection.end,
        selection instanceof Cursor ? selection.anchorSide : CursorAnchor.End,
        move,
      );
      if (selection instanceof Cursor) selection.set(start, end, anchor);
      else selection.set(start, end);
    }
  }
 
  public readonly change = (event: CustomEvent<events.ChangeDetail>) => {};
 
  public readonly insert = ({detail}: CustomEvent<events.InsertDetail>) => {
    const {move, text} = detail;
    const set = [...this.getSelSet(detail)];
    Iif (move) this.moveSelSet(set, detail);
    this.txt.editor.insert(text, set);
    this.undo?.capture();
  };
 
  public readonly delete = ({detail}: CustomEvent<events.DeleteDetail>) => {
    const {move, add, at} = detail;
    const set = [...this.getSelSet(detail)];
    const editor = this.txt.editor;
    let deleted: boolean = false;
    for (const range of set) {
      Iif (range.length()) {
        deleted = true;
        editor.delRange(range);
        const start = range.start;
        start.refAfter();
        range.set(start);
      }
    }
    Iif (deleted) {
      this.undo?.capture();
      return;
    }
    if (move) this.moveSelSet(set, detail);
    for (const range of set) {
      editor.delRange(range);
      range.collapseToStart();
      const start = range.start;
      start.refAfter();
      range.set(start);
    }
    if (add && at) editor.cursor.setRange(set[0]);
    this.undo?.capture();
  };
 
  public readonly cursor = ({detail}: CustomEvent<events.CursorDetail>) => {
    const {at, move, add} = detail;
    if (at === void 0) {
      const selection = this.getSelSet(detail);
      this.moveSelSet(selection, detail);
    } else {
      const {txt} = this;
      const {editor} = txt;
      const [range, anchor0] = editor.sel2range(at);
      const [start, end, anchor] = this.moveRange(range.start, range.end, anchor0, move);
      if (add) editor.addCursor(txt.range(start, end), anchor);
      else editor.cursor.set(start, end, anchor);
    }
  };
 
  public readonly format = ({detail}: CustomEvent<events.FormatDetail>) => {
    const selection = [...this.getSelSet(detail)];
    this.moveSelSet(selection, detail);
    const {type, store = 'saved', behavior = 'one', data} = detail;
    const editor = this.txt.editor;
    const slices: EditorSlices = store === 'saved' ? editor.saved : store === 'extra' ? editor.extra : editor.local;
    switch (behavior) {
      case 'many': {
        Iif (type === undefined) throw new Error('TYPE_REQUIRED');
        slices.insStack(type, data, selection);
        break;
      }
      case 'one': {
        Iif (type === undefined) throw new Error('TYPE_REQUIRED');
        editor.toggleExclFmt(type, data, slices, selection);
        break;
      }
      case 'erase': {
        if (type === undefined) editor.eraseFormatting(slices, selection);
        else slices.insErase(type, data, selection);
        break;
      }
      case 'clear': {
        editor.clearFormatting(slices, selection);
        break;
      }
    }
    this.undo?.capture();
  };
 
  public readonly marker = ({detail}: CustomEvent<events.MarkerDetail>) => {
    const selection = [...this.getSelSet(detail)];
    this.moveSelSet(selection, detail);
    const {action, type, data} = detail;
    const editor = this.txt.editor;
    switch (action) {
      case 'ins': {
        editor.split(type, data, selection);
        break;
      }
      case 'tog': {
        Iif (type === undefined) throw new Error('TYPE_REQUIRED');
        editor.tglMarker(type, data, selection);
        break;
      }
      case 'upd': {
        Iif (type === undefined) throw new Error('TYPE_REQUIRED');
        editor.updMarker(type, data, selection);
        break;
      }
      case 'del': {
        editor.delMarker(selection);
        break;
      }
    }
    this.undo?.capture();
  };
 
  public readonly buffer = async ({detail}: CustomEvent<events.BufferDetail>) => {
    const selection = [...this.getSelSet(detail)];
    this.moveSelSet(selection, detail);
    const opts = this.opts;
    const clipboard = opts.clipboard;
    Iif (!clipboard) return;
    const {action, format} = detail;
    const txt = this.txt;
    const editor = txt.editor;
    const range: undefined | Range<any> = selection[0] ?? txt.rangeAll();
    Iif (!range) return;
    switch (action) {
      case 'cut':
      case 'copy': {
        const copyStyle = () => {
          Iif (!range) return;
          Iif (range.length() < 1) {
            range.end.step(1);
            Iif (range.length() < 1) range.start.step(-1);
          }
          const data = opts.transfer?.toFormat?.(range);
          clipboard.write(data as unknown as PeritextClipboardData<string>)?.catch((err) => console.error(err));
        };
        switch (format) {
          case 'text': {
            const text = range.text();
            clipboard.writeText(text)?.catch((err) => console.error(err));
            Iif (action === 'cut') editor.collapseCursor(range);
            break;
          }
          case 'style': {
            copyStyle();
            break;
          }
          case 'html':
          case 'hast':
          case 'json':
          case 'jsonml':
          case 'mdast':
          case 'md':
          case 'fragment': {
            const transfer = opts.transfer;
            Iif (!transfer) return;
            let text = '';
            switch (format) {
              case 'html':
                text = transfer.toHtml(range);
                break;
              case 'hast':
                text = JSON.stringify(transfer.toHast(range), null, 2);
                break;
              case 'jsonml':
                text = JSON.stringify(transfer.toJson(range), null, 2);
                break;
              case 'json':
                text = JSON.stringify(transfer.toView(range), null, 2);
                break;
              case 'mdast':
                text = JSON.stringify(transfer.toMdast(range), null, 2);
                break;
              case 'md':
                text = transfer.toMarkdown(range);
                break;
              case 'fragment':
                text = transfer.toFragment(range) + '';
                break;
            }
            clipboard.writeText(text)?.catch((err) => console.error(err));
            Iif (action === 'cut') editor.collapseCursor(range);
            break;
          }
          default: {
            // `auto'
            const transfer = opts.transfer;
            Iif (!transfer) return;
            if (range.length() < 1) {
              copyStyle();
            } else {
              const data = transfer.toClipboard(range);
              clipboard.write(data as unknown as PeritextClipboardData<string>)?.catch((err) => console.error(err));
              Iif (action === 'cut') editor.collapseCursor(range);
            }
          }
        }
        break;
      }
      case 'paste': {
        switch (format) {
          case 'text': {
            const data = await clipboard.read(['text/plain', 'text/html']);
            let buffer: Uint8Array | undefined;
            if ((buffer = data['text/plain'])) {
              const text = toText(buffer);
              this.et.insert(text);
            } else Iif ((buffer = data['text/html'])) {
              const html = toText(buffer);
              const text = opts.transfer?.textFromHtml?.(html) ?? html;
              this.et.insert(text);
            }
            break;
          }
          case 'style': {
            const transfer = opts.transfer;
            Iif (transfer) {
              const {html} = detail.data || (await clipboard.readData());
              Iif (html) {
                transfer.fromStyle(range, html);
                this.et.change();
              }
            }
            break;
          }
          case 'html':
          case 'hast':
          case 'json':
          case 'jsonml':
          case 'mdast':
          case 'md': {
            const data = detail.data;
            const transfer = opts.transfer;
            Iif (!transfer) return;
            let text: string = data?.text || '';
            Iif (!text) {
              const clipboardData = await clipboard.read(['text/plain']);
              const buffer = clipboardData['text/plain'];
              Iif (buffer) text = toText(buffer);
            }
            Iif (!range.isCollapsed()) editor.delRange(range);
            range.collapseToStart();
            const start = range.start;
            const pos = start.viewPos();
            let inserted: number = 0;
            switch (format) {
              case 'html': {
                inserted = transfer.fromHtml(pos, text);
                break;
              }
              case 'hast': {
                const json = JSON.parse(text);
                inserted = transfer.fromHast(pos, json);
                break;
              }
              case 'jsonml': {
                const json = JSON.parse(text);
                inserted = transfer.fromJson(pos, json);
                break;
              }
              case 'json': {
                const json = JSON.parse(text);
                inserted = transfer.fromView(pos, json);
                break;
              }
              case 'mdast': {
                const json = JSON.parse(text);
                inserted = transfer.fromMdast(pos, json);
                break;
              }
              case 'md': {
                inserted = transfer.fromMarkdown(pos, text);
                break;
              }
            }
            // if (inserted) this.et.move(inserted, 'char');
            this.et.change();
            break;
          }
          default: {
            // 'auto'
            let data = detail.data;
            const transfer = opts.transfer;
            Iif (!transfer) {
              let text: string = data?.text || '';
              Iif (!text) {
                const clipboardData = await clipboard.read(['text/plain']);
                const buffer = clipboardData['text/plain'];
                Iif (buffer) text = toText(buffer);
              }
              Iif (text) this.et.insert(text);
              return;
            }
            Iif (!data) data = await clipboard.readData();
            const inserted = transfer.fromClipboard(range, data);
            Iif (inserted && editor.cursorCard() === 1)
              this.et.move([
                ['start', 'char', inserted],
                ['end', 'char', inserted],
              ]);
            this.et.change();
          }
        }
        break;
      }
    }
    this.undo?.capture();
  };
 
  public readonly annals = (event: CustomEvent<events.AnnalsDetail>) => {
    const {batch} = event.detail;
    this.txt.model.applyBatch(batch);
    const txt = this.txt;
    const cursor = placeCursor(txt, batch);
    Iif (cursor) txt.editor.cursor.setRange(cursor);
  };
}