Debian Codegraph @

addons/point_of_sale/static/src/app/services/number_buffer_service.js

raw
1 import { parseFloat as oParseFloat } from "@web/views/fields/parsers";
2 import { barcodeService } from "@barcodes/barcode_service";
3 import { registry } from "@web/core/registry";
4 import { EventBus, onWillDestroy, useComponent } from "@odoo/owl";
5 import { session } from "@web/session";
6
7 const INPUT_KEYS = new Set(
8 ["Delete", "Backspace", "+1", "+2", "+5", "+10", "+20", "+50"].concat(
9 "0123456789+-.,".split("")
10 )
11 );
12 const CONTROL_KEYS = new Set(["Enter", "Esc"]);
13 const ALLOWED_KEYS = new Set([...INPUT_KEYS, ...CONTROL_KEYS]);
14 const getDefaultConfig = () => ({
15 decimalPoint: false,
16 triggerAtEnter: false,
17 triggerAtEsc: false,
18 triggerAtInput: false,
19 useWithBarcode: false,
20 });
21
22 /**
23 * This is a singleton.
24 *
25 * Only one component can `use` the buffer at a time.
26 * This is done by keeping track of each component (and its
27 * corresponding state and config) using a stack (bufferHolderStack).
28 * The component on top of the stack is the one that currently
29 * `holds` the buffer.
30 *
31 * When the current component is unmounted, the top of the stack
32 * is popped and NumberBuffer is set up again for the new component
33 * on top of the stack.
34 *
35 * Usage
36 * =====
37 * - Use the buffer in a child component by calling `NumberBuffer.use(<config>)`
38 * in the constructor of the child component.
39 * - The component that `uses` the buffer has access to the following instance
40 * methods of the NumberBuffer:
41 * - get()
42 * - set(val)
43 * - reset()
44 * - getFloat()
45 * - capture()
46 *
47 * Note
48 * ====
49 * - No need to instantiate as it is a singleton created before exporting in this module.
50 *
51 * Possible Improvements
52 * =====================
53 * - Relieve the buffer from responsibility of handling `Enter` and other control keys.
54 * - Make the constants (ALLOWED_KEYS, etc.) more configurable.
55 * - Write more integration tests. NumberPopup can be used as test component.
56 */
57 class NumberBuffer extends EventBus {
58 static serviceDependencies = ["mail.sound_effects", "localization", "overlay"];
59 constructor() {
60 super();
61 this.setup(...arguments);
62 }
63 setup(services) {
64 this.state = {};
65 this.isReset = false;
66 this.bufferHolderStack = [];
67 this.sound = services["mail.sound_effects"];
68 this.defaultDecimalPoint = services.localization.decimalPoint;
69 this.overlay = services.overlay;
70 window.addEventListener("keyup", this._onKeyboardInput.bind(this));
71 }
72 /**
73 * @returns {String} value of the buffer, e.g. '-95.79'
74 */
75 get() {
76 return this.state ? this.state.buffer : null;
77 }
78 /**
79 * Takes a string that is convertible to float, and set it as
80 * value of the buffer. e.g. val = '2.99';
81 *
82 * @param {String} val
83 */
84 set(val) {
85 this.state.lastSet = val;
86 this.state.buffer = !isNaN(parseFloat(val)) ? val : "";
87 this.trigger("buffer-update", this.state.buffer);
88 }
89 /**
90 * Resets the buffer to empty string.
91 */
92 reset() {
93 this.isReset = true;
94 this.state.buffer = "";
95 this.trigger("buffer-update", this.state.buffer);
96 }
97 /**
98 * Calling this function, we immediately invoke the `handler` method
99 * that handles the contents of the input events buffer (`eventsBuffer`).
100 * This is helpful when we don't want to wait for the timeout that
101 * is supposed to invoke the handler.
102 */
103 capture() {
104 if (this.handler) {
105 clearTimeout(this._timeout);
106 this.handler(true);
107 delete this.handler;
108 }
109 }
110 /**
111 * @returns {number} float equivalent of the value of buffer
112 */
113 getFloat() {
114 return oParseFloat(this.get());
115 }
116 /**
117 * @param {Object} config Use to setup the buffer
118 * @param {String|null} config.decimalPoint The decimal character.
119 * @param {String|null} config.triggerAtEnter Event triggered when 'Enter' key is pressed.
120 * @param {String|null} config.triggerAtEsc Event triggered when 'Esc' key is pressed.
121 * @param {String|null} config.triggerAtInput Event triggered for every accepted input.
122 * that carries a payload of { key }. The key is checked if it is a valid input. If valid,
123 * the number buffer is modified just as it is modified when a keyboard key is pressed.
124 * @param {Boolean} config.useWithBarcode Whether this buffer is used with barcode.
125 * @emits config.triggerAtEnter when 'Enter' key is pressed.
126 * @emits config.triggerAtEsc when 'Esc' key is pressed.
127 * @emits config.triggerAtInput when an input is accepted.
128 */
129 use(config) {
130 this.eventsBuffer = [];
131 const currentComponent = useComponent();
132 config = Object.assign(getDefaultConfig(), config);
133
134 this.bufferHolderStack.push({
135 component: currentComponent,
136 state: config.state ? config.state : { buffer: "", toStartOver: false },
137 config,
138 });
139 this._setUp();
140 onWillDestroy(() => {
141 const currentComponentName = currentComponent.constructor.name;
142 const indexComponent = this.bufferHolderStack.findIndex(
143 (stack) => stack.component.constructor.name === currentComponentName
144 );
145 this.bufferHolderStack.splice(indexComponent, 1);
146 this._setUp();
147 });
148 }
149 get _currentBufferHolder() {
150 return this.bufferHolderStack[this.bufferHolderStack.length - 1];
151 }
152 _setUp() {
153 if (!this._currentBufferHolder) {
154 return;
155 }
156 const { component, state, config } = this._currentBufferHolder;
157 this.component = component;
158 this.state = state;
159 this.config = config;
160 this.decimalPoint = config.decimalPoint || this.defaultDecimalPoint;
161 this.maxTimeBetweenKeys = this.config.useWithBarcode
162 ? barcodeService.maxTimeBetweenKeysInMs
163 : 0;
164 }
165 _onKeyboardInput(event) {
166 const overlays = Object.values(this.overlay.overlays);
167 if (
168 overlays.length &&
169 !overlays.some((overlay) => overlay.props.subComponent?.name === "NumberPopup")
170 ) {
171 return;
172 }
173 return (
174 this._currentBufferHolder &&
175 this._bufferEvents(this._onInput((event) => event.key))(event)
176 );
177 }
178 sendKey(key) {
179 const event = new CustomEvent("", {
180 detail: {
181 key: key,
182 },
183 });
184 Object.defineProperty(event, "target", { value: {} });
185
186 return this._bufferEvents(this._onInput((event) => event.detail.key))(event);
187 }
188 _bufferEvents(handler) {
189 return (event) => {
190 if (["INPUT", "TEXTAREA"].includes(event.target.tagName) || !this.eventsBuffer) {
191 return;
192 }
193 // Ignore any input if combined with Ctrl, Cmd, or Alt
194 if (event.ctrlKey || event.metaKey || event.altKey) {
195 return;
196 }
197 clearTimeout(this._timeout);
198 this.eventsBuffer.push(event);
199 this._timeout = setTimeout(handler, this.maxTimeBetweenKeys);
200 this.handler = handler;
201 };
202 }
203 _onInput(keyAccessor) {
204 return (manualCapture = false) => {
205 // Manual call to NumberBuffer.capture() should allow handling more than 2 items in the buffer.
206 // This is useful in tour test that make very fast screen numpad presses (clicks).
207 if (
208 manualCapture ||
209 session.test_mode ||
210 (!manualCapture && this.eventsBuffer.length <= 2)
211 ) {
212 // Check first the buffer if its contents are all valid
213 // number input.
214 for (const event of this.eventsBuffer) {
215 if (!ALLOWED_KEYS.has(keyAccessor(event))) {
216 this.eventsBuffer = [];
217 return;
218 }
219 }
220 // At this point, all the events in buffer
221 // contains number input. It's now okay to handle
222 // each input.
223 for (const event of this.eventsBuffer) {
224 this._handleInput(keyAccessor(event));
225 event.preventDefault();
226 event.stopPropagation();
227 }
228 }
229 this.eventsBuffer = [];
230 };
231 }
232 _handleInput(key) {
233 if (key === "Enter" && this.config.triggerAtEnter) {
234 this.config.triggerAtEnter(this.state);
235 } else if (key === "Esc" && this.config.triggerAtEsc) {
236 this.config.triggerAtEsc(this.state);
237 } else if (INPUT_KEYS.has(key)) {
238 this._updateBuffer(key);
239 if (this.config.triggerAtInput) {
240 this.config.triggerAtInput({
241 buffer: this.state.buffer,
242 key,
243 });
244 }
245 }
246 }
247 /**
248 * Updates the current buffer state using the given input.
249 * @param {String} input valid input
250 */
251 _updateBuffer(input) {
252 const isEmpty = (val) => val === "" || val === null;
253 if (input === undefined || input === null) {
254 return;
255 }
256 const isFirstInput = isEmpty(this.state.buffer);
257 if (input === "," || input === ".") {
258 if (this.state.toStartOver) {
259 this.state.buffer = "";
260 }
261 if (isFirstInput) {
262 this.state.buffer = "0" + this.decimalPoint;
263 } else if (!this.state.buffer.length || this.state.buffer === "-") {
264 this.state.buffer += "0" + this.decimalPoint;
265 } else if (this.state.buffer.indexOf(this.decimalPoint) < 0) {
266 this.state.buffer = this.state.buffer + this.decimalPoint;
267 }
268 } else if (input === "Delete") {
269 if (this.isReset) {
270 this.state.buffer = "";
271 this.isReset = false;
272 return;
273 }
274 this.state.buffer = isEmpty(this.state.buffer) ? null : "";
275 } else if (input === "Backspace") {
276 if (this.isReset) {
277 this.state.buffer = "";
278 this.isReset = false;
279 return;
280 }
281 if (this.state.toStartOver) {
282 this.state.buffer = "";
283 }
284 const buffer = this.state.buffer;
285 if (isEmpty(buffer)) {
286 this.state.buffer = null;
287 } else {
288 const nCharToRemove = buffer[buffer.length - 1] === this.decimalPoint ? 2 : 1;
289 this.state.buffer = buffer.substring(0, buffer.length - nCharToRemove);
290 }
291 } else if (input === "+") {
292 if (this.state.buffer[0] === "-") {
293 this.state.buffer = this.state.buffer.substring(1, this.state.buffer.length);
294 }
295 } else if (input === "-") {
296 if (isFirstInput) {
297 this.state.buffer = "-0";
298 } else if (this.state.buffer[0] === "-") {
299 this.state.buffer = this.state.buffer.substring(1, this.state.buffer.length);
300 } else {
301 this.state.buffer = "-" + this.state.buffer;
302 }
303 } else if (input[0] === "+" && !isNaN(parseFloat(input))) {
304 // when input is like '+10', '+50', etc
305 const inputValue = oParseFloat(input.slice(1));
306 const currentBufferValue = this.state.buffer
307 ? oParseFloat(this.state.buffer.replace(".", this.decimalPoint))
308 : 0;
309 this.state.buffer = (inputValue + currentBufferValue)
310 .toString()
311 .replace(".", this.decimalPoint);
312 } else if (!isNaN(parseInt(input, 10))) {
313 if (this.state.toStartOver) {
314 // when we want to erase the current buffer for a new value
315 this.state.buffer = "";
316 }
317 if (this.state.buffer === this.state.lastSet) {
318 this.state.buffer = "";
319 this.state.lastSet = false;
320 }
321 if (isFirstInput) {
322 this.state.buffer = "" + input;
323 } else if (this.state.buffer.length > 12) {
324 this.sound.play("bell");
325 } else {
326 this.state.buffer += input;
327 }
328 }
329 if (this.state.buffer === "-") {
330 this.state.buffer = "";
331 }
332 // once an input is accepted and updated the buffer,
333 // the buffer should not be in reset state anymore.
334 this.isReset = false;
335 // it should not be in a start the buffer over state anymore.
336 this.state.toStartOver = false;
337
338 this.trigger("buffer-update", this.state.buffer);
339 }
340 }
341
342 export const numberBufferService = {
343 dependencies: NumberBuffer.serviceDependencies,
344 start(env, deps) {
345 return new NumberBuffer(deps);
346 },
347 };
348
349 registry.category("services").add("number_buffer", numberBufferService);