From 9f917fea47fc796d9ecf33265a9c02c17310dc03 Mon Sep 17 00:00:00 2001 From: Herbert Lin Date: Mon, 13 May 2024 23:30:35 -0700 Subject: [PATCH] feat: Trigger beforeInputUpdate when a candidate is selected in candidate box --- src/lib/components/Keyboard.ts | 7 ++++ src/lib/components/tests/CandidateBox.test.js | 35 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/lib/components/Keyboard.ts b/src/lib/components/Keyboard.ts index cc5479dd..c86d0f2e 100644 --- a/src/lib/components/Keyboard.ts +++ b/src/lib/components/Keyboard.ts @@ -393,6 +393,13 @@ class SimpleKeyboard { candidateStr = selectedCandidate.normalize("NFD"); } + /** + * Perform an action before any input change + */ + if (typeof this.options.beforeInputUpdate === "function") { + this.options.beforeInputUpdate(this); + } + const currentInput = this.getInput(this.options.inputName, true); const initialCaretPosition = this.getCaretPositionEnd() || 0; const inputSubstr = diff --git a/src/lib/components/tests/CandidateBox.test.js b/src/lib/components/tests/CandidateBox.test.js index 62bc4d53..98e89d1b 100644 --- a/src/lib/components/tests/CandidateBox.test.js +++ b/src/lib/components/tests/CandidateBox.test.js @@ -371,6 +371,41 @@ it('CandidateBox selection should trigger onChange', () => { keyboard.destroy(); }); +it('CandidateBox selection should trigger beforeInputChange', () => { + const keyboard = new Keyboard({ + layout: { + default: [ + "a b {bksp}" + ] + }, + layoutCandidates: { + a: "1 2 3 4 5 6" + }, + beforeInputUpdate: jest.fn(), + }); + + let candidateBoxOnItemSelected; + + const onSelect = jest.fn().mockImplementation((selectedCandidate) => { + candidateBoxOnItemSelected(selectedCandidate); + keyboard.candidateBox.destroy(); + }); + + const candidateBoxRenderFn = keyboard.candidateBox.renderPage; + + jest.spyOn(keyboard.candidateBox, "renderPage").mockImplementation((params) => { + candidateBoxOnItemSelected = params.onItemSelected; + params.onItemSelected = onSelect; + candidateBoxRenderFn(params); + }); + + keyboard.getButtonElement("a").click(); + keyboard.candidateBox.candidateBoxElement.querySelector("li").click(); + + expect(keyboard.options.beforeInputUpdate.mock.calls[0][0]).toMatchObject(keyboard); + keyboard.destroy(); +}); + it('CandidateBox normalization will work', () => { const keyboard = new Keyboard({ layout: {