Improve date rendering with toggleable rendering

This commit is contained in:
Xevion
2023-01-22 04:36:48 -06:00
parent 7c720181dd
commit 742b370ee3
4 changed files with 45 additions and 4 deletions

View File

@@ -0,0 +1,30 @@
import type {FunctionComponent} from "react";
import {useBoolean} from "usehooks-ts";
import {format, formatDistanceToNow} from "date-fns";
type DynamicDateProps = {
value: Date | number;
absoluteFormat?: string;
}
/**
* A component for a toggleable switch between the absolute & human-relative date.
* @param value The date to be displayed, the Date value, or
* @param absoluteFormat Optional - the date-fns format string to use for the absolute date rendering.
*/
const DynamicDate: FunctionComponent<DynamicDateProps> = ({value, absoluteFormat}) => {
const {value: showAbsolute, toggle: toggleFormat} = useBoolean(true);
const date = new Date(value);
return (
<button onClick={toggleFormat}>
<span title={date.toISOString()}>
{showAbsolute
? format(date, absoluteFormat ?? "LLL do, y HH:mm:ss")
: formatDistanceToNow(date, {includeSeconds: true, addSuffix: true})}
</span>
</button>
)
}
export default DynamicDate;

View File

@@ -1,6 +1,7 @@
import type {FunctionComponent} from "react";
import type {Event} from "@/schema";
import type {Event} from "@/types";
import {Fragment} from "react";
import DynamicDate from "@/components/DynamicDate";
export type EventsProps = {
data: Event[];
@@ -13,9 +14,7 @@ const Events: FunctionComponent<EventsProps> = ({data}) => {
{eventAction}:
</dt>
<dd>
<span
title={eventDate.toString()}>{eventDate.toString()}
</span>
<DynamicDate value={new Date(eventDate)}/>
{eventActor != null ? ` (by ${eventActor})` : null}
</dd>
</Fragment>