Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#1936] Migrate safari_date.js to typescript #2053

Merged
merged 2 commits into from
Oct 28, 2023
Merged
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
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';
Loading