Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerEditorRevision.ts

78 lines2.4 KB

1export interface ComposerNativeEventSnapshot {
2 readonly eventCount: number;
3 readonly value: string;
4 readonly selection: ComposerEditorSelection | null;
5}
6​
7interface ComposerEditorSelection {
8 readonly start: number;
9 readonly end: number;
11​
12export function acknowledgeComposerNativeEvent(
13 mostRecentEventCount: number,
14 incomingEventCount: number,
15): number | null {
16 if (!Number.isSafeInteger(incomingEventCount) || incomingEventCount < mostRecentEventCount) {
17 return null;
18 }
19 return incomingEventCount;
21​
22export function resolveComposerControlledEventCount(
23 value: string,
24 selection: ComposerEditorSelection | null,
25 mostRecentEventCount: number,
26 snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
27): number {
28 let newestValueEventCount: number | null = null;
29 for (let index = snapshots.length - 1; index >= 0; index -= 1) {
30 const snapshot = snapshots[index];
31 if (snapshot?.value !== value) continue;
32​
33 newestValueEventCount ??= snapshot.eventCount;
34 if (
35 selection === null ||
36 (snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end)
37 ) {
38 return snapshot.eventCount;
39 }
40 }
41​
42 // A value emitted by native paired with a different selection is an
43 // intermediate React render. Keep it behind the native revision so it
44 // cannot move the caret while newer keystrokes are being processed.
45 if (newestValueEventCount !== null && mostRecentEventCount > 0) {
46 return Math.min(newestValueEventCount, mostRecentEventCount - 1);
47 }
48​
49 return mostRecentEventCount;
51​
52export function isComposerNativeEcho(
53 value: string,
54 selection: ComposerEditorSelection | null,
55 eventCount: number,
56 snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
57): boolean {
58 for (let index = snapshots.length - 1; index >= 0; index -= 1) {
59 const snapshot = snapshots[index];
60 if (
61 snapshot !== undefined &&
62 snapshot.eventCount === eventCount &&
63 snapshot.value === value &&
64 (selection === null ||
65 (snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end))
66 ) {
67 return true;
68 }
69 }
70 return false;
72​
73export function pruneAcknowledgedComposerNativeEvents(
74 snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
75 acknowledgedEventCount: number,
76): ComposerNativeEventSnapshot[] {
77 return snapshots.filter((snapshot) => snapshot.eventCount > acknowledgedEventCount);