Skip to content
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"scripts": {
"build": "rm -rf dist && tsup --config tsup.config.mts",
"format": "prettier --write src",
"format:translations": "find src/translations -name '*.json' -exec pnpm exec sort-json {} \\;",
"format:translations": "find src/i18n/translations -name '*.json' -exec pnpm exec sort-json {} \\;",
"lint": "tsc && eslint --fix src",
"prepare": "husky",
"storybook": "storybook dev --no-open -p 6006",
Expand Down
5 changes: 3 additions & 2 deletions src/components/Form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
const isGrouped = Array.isArray(content);

const revalidate = () => {
const hasErrors = Object.keys(errors).length > 0;
const hasErrors = Object.keys(errors).length > 0 || rootErrors.length;
if (hasErrors) {
validationSchema
.safeParseAsync(values)
Expand All @@ -156,7 +156,8 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
};

useEffect(() => {
revalidate();
setErrors({});
setRootErrors([]);
}, [resolvedLanguage]);

const isSuspended = Boolean(suspendWhileSubmitting && isSubmitting);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';

import { OneTimePasswordInput } from './OneTimePasswordInput';

type Props = React.ComponentPropsWithoutRef<typeof OneTimePasswordInput>;

const TEST_ID = 'OneTimePasswordInput';

const TestOneTimePasswordInput: React.FC<Partial<Props>> = (props) => {
return <OneTimePasswordInput data-testid={TEST_ID} {...(props as Props)} />;
};

describe('OneTimePasswordInput', () => {
it('should render', () => {
render(<TestOneTimePasswordInput />);
expect(screen.getByTestId(TEST_ID)).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { Meta, StoryObj } from '@storybook/react';

import { NotificationHub } from '../NotificationHub';
import { OneTimePasswordInput } from './OneTimePasswordInput';

type Story = StoryObj<typeof OneTimePasswordInput>;

export default {
args: {
onComplete: (code) => {
alert(`Code: ${code}`);
}
},
component: OneTimePasswordInput,
decorators: [
(Story) => {
return (
<>
<NotificationHub />
<Story />
</>
);
}
]
} as Meta<typeof OneTimePasswordInput>;

export const Default: Story = {};
109 changes: 109 additions & 0 deletions src/components/OneTimePasswordInput/OneTimePasswordInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { useEffect, useRef, useState } from 'react';
import type { ChangeEvent, ClipboardEvent, KeyboardEvent } from 'react';

import type { Promisable } from 'type-fest';

import { useNotificationsStore, useTranslation } from '@/hooks';
import { cn } from '@/utils';

const CODE_LENGTH = 6;

const EMPTY_CODE = Object.freeze(Array<null>(CODE_LENGTH).fill(null));

type OneTimePasswordInputProps = {
[key: `data-${string}`]: unknown;
className?: string;
onComplete: (code: number) => Promisable<void>;
};

function getUpdatedDigits(digits: (null | number)[], index: number, value: null | number) {
const updatedDigits = [...digits];
updatedDigits[index] = value;
return updatedDigits;
}

export const OneTimePasswordInput = ({ className, onComplete, ...props }: OneTimePasswordInputProps) => {
const notifications = useNotificationsStore();
const { t } = useTranslation('libui');
const [digits, setDigits] = useState<(null | number)[]>([...EMPTY_CODE]);
const inputRefs = digits.map(() => useRef<HTMLInputElement>(null));

useEffect(() => {
const isComplete = digits.every((value) => Number.isInteger(value));
if (isComplete) {
void onComplete(parseInt(digits.join('')));
setDigits([...EMPTY_CODE]);
}
}, [digits]);

const focusNext = (index: number) => inputRefs[index + 1 === digits.length ? 0 : index + 1]?.current?.focus();

const focusPrev = (index: number) => inputRefs[index - 1 >= 0 ? index - 1 : digits.length - 1]?.current?.focus();

const handleChange = (e: ChangeEvent<HTMLInputElement>, index: number) => {
let value: null | number;
if (e.target.value === '') {
value = null;
} else if (Number.isInteger(parseInt(e.target.value))) {
value = parseInt(e.target.value);
} else {
return;
}
setDigits((prevDigits) => getUpdatedDigits(prevDigits, index, value));
focusNext(index);
};

const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>, index: number) => {
switch (e.key) {
case 'ArrowLeft':
focusPrev(index);
break;
case 'ArrowRight':
focusNext(index);
break;
case 'Backspace':
setDigits((prevDigits) => getUpdatedDigits(prevDigits, index - 1, null));
focusPrev(index);
}
};

const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
const pastedDigits = e.clipboardData
.getData('text/plain')
.split('')
.slice(0, CODE_LENGTH)
.map((value) => parseInt(value));
const isValid = pastedDigits.length === CODE_LENGTH && pastedDigits.every((value) => Number.isInteger(value));
if (isValid) {
setDigits(pastedDigits);
} else {
notifications.addNotification({
message: t('oneTimePasswordInput.invalidCodeFormat'),
type: 'warning'
});
}
};

return (
<div className={cn('flex gap-2', className)} {...props}>
{digits.map((_, index) => (
<input
className="w-1/6 rounded-md border border-slate-300 bg-transparent p-2 shadow-xs hover:border-slate-300 focus:border-sky-800 focus:outline-hidden dark:border-slate-600 dark:hover:border-slate-400 dark:focus:border-sky-500"
key={index}
maxLength={1}
ref={inputRefs[index]}
type="text"
value={digits[index] ?? ''}
onChange={(e) => {
handleChange(e, index);
}}
onKeyDown={(e) => {
handleKeyDown(e, index);
}}
onPaste={handlePaste}
/>
))}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/OneTimePasswordInput/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './OneTimePasswordInput';
1 change: 1 addition & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export * from './LineGraph';
export * from './ListboxDropdown';
export * from './MenuBar';
export * from './NotificationHub';
export * from './OneTimePasswordInput';
export * from './Pagination';
export * from './Popover';
export * from './Progress';
Expand Down
22 changes: 14 additions & 8 deletions src/i18n/translations/libui.json
Original file line number Diff line number Diff line change
Expand Up @@ -131,26 +131,32 @@
}
}
},
"oneTimePasswordInput": {
"invalidCodeFormat": {
"en": "Invalid code format",
"fr": "Format de code invalide"
}
},
"pagination": {
"firstPage": {
"en": "<< First",
"fr": "<< Première"
},
"info": {
"en": "Showing {{first}} to {{last}} of {{total}} results",
"fr": "Affichage de {{first}} à {{last}} sur {{total}} résultats"
},
"lastPage": {
"en": "Last >>",
"fr": "Dernière >>"
},
"next": {
"en": "Next",
"fr": "Suivant"
},
"previous": {
"en": "Previous",
"fr": "Précédent"
},
"firstPage": {
"en": "<< First",
"fr": "<< Première"
},
"lastPage": {
"en": "Last >>",
"fr": "Dernière >>"
}
},
"searchBar": {
Expand Down