wix-style-react
Version:
105 lines (82 loc) • 2.9 kB
JavaScript
import { dateTimeFormat } from 'wix-design-systems-locale-utils';
import { DEFAULT_STEP } from './TimeInputNext';
const timeRegex =
/([下上午오전후 ]{0,3})([0-2]?[0-9]{0,2})([:.h]{0,1})([0-5][0-9]{0,2})/;
const validationRegex =
/^([下上午오전후 ]{0,3})(([0-1]?[0-9]|2[0-3])[^0-9]{0,3}([0-5]([0-9]([^0-9]+)?)?)?)?$/;
export const getFormattedDate = ({ value, timeStyle, locale }) => {
if (!value) {
return '';
}
if (timeStyle === 'long') {
return dateTimeFormat.getLongTime(locale, value);
}
return dateTimeFormat.getShortTime(locale, value);
};
export const getTimeSlot = ({ value, timeStyle, locale }) => {
const formattedDate = getFormattedDate({
value,
timeStyle,
locale,
});
return {
id: new Date(value).getTime(),
value: formattedDate,
};
};
export const getTimeSlots = ({
value = new Date(Date.now()),
timeStyle,
locale,
step,
}) => {
const validatedStep = parseInt(step) ? parseInt(step) : DEFAULT_STEP;
const minuteMs = 60000;
const stepMs = validatedStep > 60 ? 60 * minuteMs : validatedStep * minuteMs;
const startOfTheDay = new Date(value).setHours(0, 0, 0, 0);
const dayMs = 86400000;
const amountOfTimeSlots = dayMs / stepMs;
return new Array(amountOfTimeSlots).fill().map((_, i) => {
const timeInMs = startOfTheDay + i * stepMs;
return getTimeSlot({ value: timeInMs, timeStyle, locale });
});
};
export const getClosestTimeSlot = ({
value = new Date(Date.now()),
timeSlots,
}) => {
return timeSlots.find(option => option.id >= value.getTime());
};
const regexReplacer = (_, __, hours, divider, minutes) => {
if (/^[1-9]$/.test(hours)) {
return `0${hours}${divider}${minutes}`;
}
return `${hours}${divider}${minutes}`;
};
const normalizeTimeSlots = timeSlots =>
timeSlots.map(slot => ({
...slot,
value: slot.value.replace(/\s+/g, '').replace(timeRegex, regexReplacer),
}));
const removeIrrelevantCharacters = input =>
input
.replace(/[下上午오전후 ]{0,3}/, '')
.replace(/\s+/g, '')
.replace(/[.:h]+/, ':');
export const getSuggestedOption = (inputValue, timeSlots) => {
const value = removeIrrelevantCharacters(inputValue);
if (!value || value === '0') {
return;
}
const currentTime = Date.now();
const nextTimeSlotId = timeSlots.findIndex(time => time.id > currentTime);
const highPriorityList = timeSlots.slice(nextTimeSlotId, timeSlots.length);
const lowPriorityList = timeSlots.slice(0, nextTimeSlotId);
const prioritizedList = [...highPriorityList, ...lowPriorityList];
const normalizedTimeSlots = normalizeTimeSlots(prioritizedList);
return normalizedTimeSlots.find(
slot => slot.value.startsWith(value) || slot.value.startsWith(`0${value}`),
);
};
export const isInputValid = inputValue => validationRegex.test(inputValue);
export const getErorMessageByLocale = () => 'Invalid Value';