Skip to content

Commit

Permalink
[#1936] Migrate safari_date.js to typescript (#2053)
Browse files Browse the repository at this point in the history
Currently, there is still some JavaScript code which remains unmigrated.
This allows for type unsafe code to be written, potentially resulting in
unintended behavior.

Let's migrate safari_date.js to TypeScript code to facilitate future
changes to the code.
  • Loading branch information
jq1836 committed Oct 28, 2023
1 parent 4dae85d commit 7450425
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 49 deletions.
49 changes: 0 additions & 49 deletions frontend/src/utils/safari_date.js

This file was deleted.

54 changes: 54 additions & 0 deletions frontend/src/utils/safari_date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// date keys for handling safari date input //
function isIntegerKey(key: string) {
return !Number.isNaN(+key);
}

function isArrowOrEnterKey(key: string) {
return key === 'ArrowDown' || key === 'ArrowLeft' || key === 'ArrowRight' || key === 'ArrowUp' || key === 'Enter';
}

function isBackSpaceOrDeleteKey(key: string) {
return key === 'Backspace' || key === 'Delete';
}

function validateInputDate(event: KeyboardEvent) {
const key = event.key;
// only allow integer, backspace, delete, arrow or enter keys
if (!(isIntegerKey(key) || isBackSpaceOrDeleteKey(key) || isArrowOrEnterKey(key))) {
event.preventDefault();
}
}

function deleteDashInputDate(event: KeyboardEvent) {
const key = event.key;
// remove two chars before the cursor's position if deleting dash character
if (isBackSpaceOrDeleteKey(key) && event.target !== null && 'value' in event.target
&& 'selectionStart' in event.target) {
const date = event.target.value as string;
const cursorPosition = event.target.selectionStart as number;
if (date[cursorPosition - 1] === '-') {
event.target.value = date.slice(0, cursorPosition - 1);
}
}
}

function formatInputDateOnKeyDown(event: KeyboardEvent) {
validateInputDate(event);
deleteDashInputDate(event);
}

function appendDashInputDate(event: KeyboardEvent) {
// append dash to date with format yyyy-mm-dd
if (event.target !== null && 'value' in event.target) {
const date = event.target.value as string;
if (date.match(/^\d{4}$/) !== null) {
event.target.value = `${event.target.value}-`;
} else if (date.match(/^\d{4}-\d{2}$/) !== null) {
event.target.value = `${event.target.value}-`;
}
}
}

Object.assign(window, { formatInputDateOnKeyDown, appendDashInputDate });

export default 'test';

0 comments on commit 7450425

Please sign in to comment.