@equinor/eds-core-react
Version:
The React implementation of the Equinor Design System
73 lines (69 loc) • 2.53 kB
JavaScript
import { useState, useRef } from 'react';
import { useDateFormatter, useDateSegment } from 'react-aria';
import styled, { css } from 'styled-components';
import { tokens } from '@equinor/eds-tokens';
import { useDatePickerContext } from '../utils/context.js';
import { jsx } from 'react/jsx-runtime';
const Segment = styled.div.withConfig({
displayName: "DateSegment__Segment",
componentId: "sc-19uidpx-0"
})(({
$placeholder,
$disabled
}) => {
return css(["font-family:", ";&:focus-visible{outline:2px solid ", ";background-color:", ";}", " ", ""], tokens.typography.input.text.fontFamily, tokens.colors.interactive.primary__resting.rgba, tokens.colors.ui.background__medium.rgba, $placeholder ? css({
color: tokens.colors.text.static_icons__tertiary.rgba
}) : css({
color: tokens.colors.text.static_icons__default.rgba
}), $disabled && css(["color:", ";"], tokens.colors.interactive.disabled__text.rgba));
});
/**
* DateSegment is used to represent a single segment of a date in the DateField (i.e. day, month, year)
*/
function DateSegment({
segment,
state
}) {
const {
formatOptions,
timezone
} = useDatePickerContext();
const formatter = useDateFormatter(formatOptions);
const parts = state.value ? formatter.formatToParts(state.value.toDate(timezone)) : [];
const part = parts.find(p => p.type === segment.type);
const value = segment.isPlaceholder || segment.type === 'literal' ? segment.text : part?.value ?? segment.text;
const [focus, setFocus] = useState(false);
const ref = useRef(null);
const {
segmentProps
} = useDateSegment(segment, state, ref);
return /*#__PURE__*/jsx(Segment, {
...segmentProps,
onFocus: e => {
setFocus(true);
segmentProps.onFocus(e);
},
onBlur: e => {
setFocus(false);
segmentProps.onBlur(e);
},
$invalid: state.isInvalid,
$disabled: state.isDisabled,
$placeholder: segment.isPlaceholder,
style: {
padding: segment.type === 'literal' ? '0 2px' : '0'
},
onKeyDown: e => {
if (e.code === 'Enter' || e.code === 'Space') {
e.stopPropagation();
e.preventDefault();
} else if (segmentProps.onKeyDown) {
segmentProps.onKeyDown(e);
}
},
ref: ref,
className: `segment ${segment.isPlaceholder ? 'placeholder' : ''}`,
children: focus ? segment.isPlaceholder || segment.type === 'literal' ? segment.text : segment.text.padStart(segment.type === 'year' ? 4 : 2, '0') : value
});
}
export { DateSegment };