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

55.55% Statements 30/54
100% Branches 1/1
0% Functions 0/3
55.55% Lines 30/54

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 53 54 551x 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 {Calendar} from '../primereact/index.js';
 
import type {IWidgetProps} from '@feasibleone/blong';
import React from 'react';
 
export const dateIn = (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);
};
 
export const dateOut = (d: Date) => new Date(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
 
export function DateWidget({
    id,
    name,
    value,
    onChange,
    onBlur,
    error,
    readOnly,
    disabled,
}: IWidgetProps) {
    const dateValue = React.useMemo(
        () => (value != null ? dateIn(value as string) : null),
        [value],
    );

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

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