Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions frontend/__tests__/input/handlers/insert-text.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
getInputElementValue,
setInputElementValue,
} from "../../../src/ts/input/input-element";
import { onInsertText } from "../../../src/ts/input/handlers/insert-text";
import {
getLigatureCompletion,
getMatchingLigatureOverride,
resetPendingLigatureCompletion,
} from "../../../src/ts/input/helpers/ligatures";

const mocks = vi.hoisted(() => ({
currentWord: "",
input: {
current: "",
syncWithInputElement: vi.fn(),
},
incrementKeypressErrors: vi.fn(),
}));

vi.mock("../../../src/ts/test/test-ui", () => ({}));
vi.mock("../../../src/ts/test/test-state", () => ({
activeWordIndex: 0,
isActive: true,
}));
vi.mock("../../../src/ts/test/test-logic", () => ({
startTest: vi.fn(),
}));
vi.mock("../../../src/ts/test/test-input", () => ({
input: mocks.input,
corrected: { update: vi.fn() },
incrementAccuracy: vi.fn(),
incrementKeypressCount: vi.fn(),
incrementKeypressErrors: mocks.incrementKeypressErrors,
pushKeypressWord: vi.fn(),
pushMissedWord: vi.fn(),
setBurstStart: vi.fn(),
setCurrentNotAfk: vi.fn(),
}));
vi.mock("../../../src/ts/test/test-words", () => ({
words: {
getCurrentText: vi.fn(() => mocks.currentWord),
},
}));
vi.mock("../../../src/ts/input/helpers/fail-or-finish", () => ({
checkIfFailedDueToDifficulty: vi.fn(),
checkIfFailedDueToMinBurst: vi.fn(),
checkIfFinished: vi.fn(),
}));
vi.mock("../../../src/ts/test/funbox/list", () => ({
findSingleActiveFunboxWithFunction: vi.fn(),
isFunboxActiveWithProperty: vi.fn(() => false),
}));
vi.mock("../../../src/ts/test/replay", () => ({
addReplayEvent: vi.fn(),
}));
vi.mock("../../../src/ts/config/store", () => ({
Config: {
blindMode: false,
keymapMode: "off",
language: "english",
mode: "words",
oppositeShiftMode: "off",
stopOnError: "off",
},
}));
vi.mock("../../../src/ts/events/keymap", () => ({
flash: vi.fn(),
}));
vi.mock("../../../src/ts/test/weak-spot", () => ({
updateScore: vi.fn(),
}));
vi.mock("../../../src/ts/legacy-states/composition", () => ({
getData: vi.fn(() => ""),
}));
vi.mock("../../../src/ts/input/state", () => ({
getIncorrectShiftsInARow: vi.fn(() => 0),
incrementIncorrectShiftsInARow: vi.fn(),
isCorrectShiftUsed: vi.fn(() => true),
resetIncorrectShiftsInARow: vi.fn(),
}));
vi.mock("../../../src/ts/states/notifications", () => ({
showNoticeNotification: vi.fn(),
}));
vi.mock("../../../src/ts/input/helpers/word-navigation", () => ({
goToNextWord: vi.fn(async () => ({
increasedWordIndex: false,
lastBurst: null,
})),
}));
vi.mock("../../../src/ts/input/handlers/before-insert-text", () => ({
onBeforeInsertText: vi.fn(),
}));

describe("insert-text ligature input overrides", () => {
Comment thread
Dawn-Fighter marked this conversation as resolved.
beforeEach(() => {
mocks.currentWord = "";
mocks.input.current = "";
mocks.input.syncWithInputElement.mockImplementation(() => {
mocks.input.current = getInputElementValue().inputValue;
});
setInputElementValue("");
});

afterEach(() => {
vi.clearAllMocks();
resetPendingLigatureCompletion();
setInputElementValue("");
});

it.each([
["o", "œ", "œ"],
["O", "Œ", "Œ"],
["a", "æ", "æ"],
["A", "Æ", "Æ"],
])(
"normalizes '%s' to '%s' when target is '%s'",
(data, target, expected) => {
expect(getMatchingLigatureOverride(data, target)).toBe(expected);
},
);

it.each([
["œ", "e"],
["Œ", "E"],
["æ", "e"],
["Æ", "E"],
])("gets completion '%s' after '%s'", (target, completion) => {
expect(getLigatureCompletion(target)).toBe(completion);
});

it("does not normalize unrelated input", () => {
expect(getMatchingLigatureOverride("e", "œ")).toBeNull();
expect(getLigatureCompletion("o")).toBeNull();
});

it("removes the completion character and keeps input state synced", async () => {
mocks.currentWord = "œuvre";

setInputElementValue("o");
await onInsertText({
now: performance.now(),
data: "o",
});

setInputElementValue("œe");

await onInsertText({
now: performance.now(),
data: "e",
});

expect(getInputElementValue().inputValue).toBe("œ");
expect(mocks.input.current).toBe("œ");
expect(mocks.input.syncWithInputElement).toHaveBeenCalledTimes(2);
expect(mocks.incrementKeypressErrors).not.toHaveBeenCalled();
});

it("penalizes skipping the ligature completion character", async () => {
mocks.currentWord = "œuvre";

setInputElementValue("o");
await onInsertText({
now: performance.now(),
data: "o",
});

setInputElementValue("œu");
await onInsertText({
now: performance.now(),
data: "u",
});

expect(mocks.input.current).toBe("œu");
expect(mocks.incrementKeypressErrors).toHaveBeenCalledOnce();
});
});
46 changes: 39 additions & 7 deletions frontend/src/ts/input/handlers/insert-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@
isCharCorrect,
shouldInsertSpaceCharacter,
} from "../helpers/validation";
import {
getLigatureCompletion,
getMatchingLigatureOverride,
getPendingLigatureCompletionStatus,
setPendingLigatureCompletion,
} from "../helpers/ligatures";

const charOverrides = new Map<string, string>([
["…", "..."],
Expand Down Expand Up @@ -82,6 +88,16 @@
return;
}

const pendingLigatureCompletionStatus = getPendingLigatureCompletionStatus(
options.data,
TestInput.input.current,
);
if (pendingLigatureCompletionStatus === "complete") {
setInputElementValue(inputValue.slice(0, -options.data.length));
TestInput.input.syncWithInputElement();
return;
}

const charOverride = charOverrides.get(options.data);
if (
charOverride !== undefined &&
Expand Down Expand Up @@ -140,13 +156,15 @@
currentWord[(testInput + data).length - 1] ?? "",
);
const correct =
funboxCorrect ??
isCharCorrect({
data,
inputValue: testInput,
targetWord: currentWord,
correctShiftUsed,
});
pendingLigatureCompletionStatus === "skipped"
? false
: (funboxCorrect ??
isCharCorrect({
data,
inputValue: testInput,
targetWord: currentWord,
correctShiftUsed,
}));

// word navigation check
const noSpaceForce =
Expand Down Expand Up @@ -252,7 +270,7 @@
}, 0);
}

if (!CompositionState.getComposing() && lastInMultiOrSingle) {

Check failure on line 273 in frontend/src/ts/input/handlers/insert-text.ts

View workflow job for this annotation

GitHub Actions / ci-fe

[unit] __tests__/input/handlers/insert-text.spec.ts > insert-text ligature input overrides > penalizes skipping the ligature completion character

Error: [vitest] No "getComposing" export is defined on the "../../../src/ts/legacy-states/composition" mock. Did you forget to return it from "vi.mock"? If you need to partially mock a module, you can use "importOriginal" helper inside: vi.mock(import("../../../src/ts/legacy-states/composition"), async (importOriginal) => { const actual = await importOriginal() return { ...actual, // your mocked methods } }) ❯ Module.onInsertText src/ts/input/handlers/insert-text.ts:273:25 ❯ __tests__/input/handlers/insert-text.spec.ts:164:11

Check failure on line 273 in frontend/src/ts/input/handlers/insert-text.ts

View workflow job for this annotation

GitHub Actions / ci-fe

[unit] __tests__/input/handlers/insert-text.spec.ts > insert-text ligature input overrides > removes the completion character and keeps input state synced

Error: [vitest] No "getComposing" export is defined on the "../../../src/ts/legacy-states/composition" mock. Did you forget to return it from "vi.mock"? If you need to partially mock a module, you can use "importOriginal" helper inside: vi.mock(import("../../../src/ts/legacy-states/composition"), async (importOriginal) => { const actual = await importOriginal() return { ...actual, // your mocked methods } }) ❯ Module.onInsertText src/ts/input/handlers/insert-text.ts:273:25 ❯ __tests__/input/handlers/insert-text.spec.ts:142:11
if (
checkIfFailedDueToDifficulty({
testInputWithData: testInput + data,
Expand Down Expand Up @@ -301,6 +319,20 @@
) {
replaceInputElementLastValueChar(targetChar);
normalizedData = targetChar;
} else {
const ligatureOverride = getMatchingLigatureOverride(data, targetChar);
if (ligatureOverride !== null) {
replaceInputElementLastValueChar(ligatureOverride);
normalizedData = ligatureOverride;

const ligatureCompletion = getLigatureCompletion(targetChar);
if (ligatureCompletion !== null) {
setPendingLigatureCompletion(
ligatureCompletion,
testInput.length + ligatureOverride.length,
);
}
}
}
return normalizedData;
}
Expand Down
62 changes: 62 additions & 0 deletions frontend/src/ts/input/helpers/ligatures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const ligatureInputOverrides = new Map<string, string>([
["œ", "oe"],
["Œ", "OE"],
["æ", "ae"],
["Æ", "AE"],
]);

let pendingLigatureCompletion: {
completion: string;
inputLength: number;
} | null = null;

type PendingLigatureCompletionStatus = "complete" | "skipped" | null;

export function getMatchingLigatureOverride(
data: string,
targetChar: string | undefined,
): string | null {
if (targetChar === undefined) return null;

const override = ligatureInputOverrides.get(targetChar);
if (override?.[0] !== data) return null;

return targetChar;
}

export function getLigatureCompletion(
targetChar: string | undefined,
): string | null {
if (targetChar === undefined) return null;

const override = ligatureInputOverrides.get(targetChar);
return override?.slice(1) ?? null;
}

export function setPendingLigatureCompletion(
completion: string,
inputLength: number,
): void {
pendingLigatureCompletion = { completion, inputLength };
}

export function resetPendingLigatureCompletion(): void {
pendingLigatureCompletion = null;
}

export function getPendingLigatureCompletionStatus(
data: string,
currentInput: string,
): PendingLigatureCompletionStatus {
if (pendingLigatureCompletion === null) return null;

if (currentInput.length !== pendingLigatureCompletion.inputLength) {
resetPendingLigatureCompletion();
return null;
}

const completionMatched = data === pendingLigatureCompletion.completion;
resetPendingLigatureCompletion();

return completionMatched ? "complete" : "skipped";
}
Loading