Copy and paste functionality for DatePicker/DateRangePicker #4445
Replies: 3 comments
-
Each segment is its own input. So we'd need to try some different things out, because focus can't be in multiple fields at once. Maybe we could fake it though. In the meantime, you could provide a button to copy the value to the clipboard programmatically. |
Beta Was this translation helpful? Give feedback.
-
I've been working on a solution for our project's import { isValid, parse } from 'date-fns';
export function DatePicker(props: DatePickerProps) {
// ...
const { copyPasteProps } = useCopyPasteDate(state);
return (
// ..
<DateField {...fieldProps} {...copyPasteProps} />
)
}
interface CopyPasteProps {
onKeyDown: React.KeyboardEventHandler<HTMLInputElement>;
onPaste: React.ClipboardEventHandler<HTMLInputElement>;
}
function useCopyPasteDate(state: DatePickerState): {
copyPasteProps: CopyPasteProps;
} {
return {
copyPasteProps: {
onKeyDown(event) {
const textContent = event.currentTarget.textContent;
/**
* Copy the currently displayed date if the date picker has a value, and the user presses ⌘ + C
*/
if (
event.key === 'c' &&
event.metaKey &&
state.dateValue !== null &&
textContent !== null
) {
navigator.clipboard.writeText(textContent);
}
},
onPaste(event) {
const pastedText = event.clipboardData?.getData('text');
if (!pastedText) {
return;
}
const timeZone = getLocalTimeZone();
const referenceDate =
state.dateValue?.toDate(timeZone) ?? new Date();
const parsedDate = parseDate(pastedText, referenceDate);
if (parsedDate) {
state.setValue(
parseAbsolute(parsedDate.toISOString(), timeZone)
);
}
},
},
};
}
const formats: string[] = [
"yyyy-MM-dd'T'HH:mm:ss.SSSX", // ISO-8601 with time and zone offset
'yyyy-MM-dd', // ISO-8601 without time
// ...
];
function parseDate(value: string, referenceDate: Date): Date | null {
for (const format of formats) {
const parsed = parse(value, format, referenceDate);
if (isValid(parsed)) {
return parsed;
}
}
return null;
} |
Beta Was this translation helpful? Give feedback.
-
I found the conversion from a date as returned by |
Beta Was this translation helpful? Give feedback.
-
It looks like I can't copy and paste values from the DatePicker/DateRangePicker. This might be intentional, but it would be great if this could be supported. Especially a feature that allows copy and pasting the whole date, not just the segments.
Beta Was this translation helpful? Give feedback.
All reactions