All files / blong-browser/src/widgets TimeWidget.tsx

59.61% Statements 31/52
100% Branches 1/1
0% Functions 0/3
59.61% Lines 31/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 531x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x       1x                          
import React from 'react';
import {Calendar} from '../primereact/index.js';
 
import type {IWidgetProps} from '@feasibleone/blong';
 
const timeIn = (d: string | Date) => {
    const dd = new Date(d);
    const properDate = new Date(
        new Date(d).getTime() + new Date(d).getTimezoneOffset() * 60 * 1000,
    );
    const timezoneDiff = properDate.getTimezoneOffset() - dd.getTimezoneOffset();
    if (!timezoneDiff) return properDate;
    return new Date(properDate.getTime() + timezoneDiff * 60 * 1000);
};
 
const timeOut = (d: Date) => new Date(d.setFullYear(1970, 0, 1));
 
export function TimeWidget({
    id,
    name,
    value,
    onChange,
    onBlur,
    error,
    readOnly,
    disabled,
}: IWidgetProps) {
    const dateValue = value instanceof Date ? value : value ? timeIn(value as string) : null;

    const handleChange = React.useMemo(
        () => (event: {value: Date | null | undefined | string | Date[]}) => {
            if (event.value instanceof Date) event.value = timeOut(event.value);
            onChange(event.value);
        },
        [onChange],
    );

    return (
        <Calendar
            inputId={id ?? name}
            value={dateValue}
            onChange={handleChange}
            onHide={onBlur}
            readOnlyInput={readOnly}
            disabled={disabled}
            className={`blong-time w-full ${error ? 'p-invalid' : ''}`}
            showIcon
            showOnFocus={false}
            timeOnly
        />
    );
}