Skip to content

Commit

Permalink
use dayjs to format when recently viewed urls (#3923)
Browse files Browse the repository at this point in the history
  • Loading branch information
peterbe authored Jun 1, 2021
1 parent d97ff8f commit cfbe278
Showing 1 changed file with 8 additions and 25 deletions.
33 changes: 8 additions & 25 deletions client/src/writers-homepage/viewed-documents.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,25 @@
import React, { useEffect, useState } from "react";
import React from "react";
import { Link } from "react-router-dom";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";

import { usePageVisibility } from "./hooks";

import "./viewed-documents.scss";

dayjs.extend(relativeTime);

type Entry = {
url: string;
title: string;
timestamp: number;
};

// Simpler and cheaper than a proper library
function friendlyDateDisplay(date: Date): string {
const today = new Date();
const dateString = date.toDateString();
const secondsDiff = (today.getTime() - date.getTime()) / 1000;
if (secondsDiff < 60) {
return "seconds ago";
}
if (secondsDiff < 60 * 15) {
return "minutes ago";
}
if (today.toDateString() === dateString) {
return "today";
}
const yesterday = new Date(today.getTime() - 1000 * 3600 * 24);
if (yesterday.toDateString() === dateString) {
return "yesterday";
}
return dateString;
}

export default function ViewedDocuments() {
const isVisible = usePageVisibility();
const [entries, setEntries] = useState<Entry[] | null>(null);
const [entries, setEntries] = React.useState<Entry[] | null>(null);

useEffect(() => {
React.useEffect(() => {
if (isVisible) {
const localStorageKey = "viewed-documents";
const previousVisits = JSON.parse(
Expand Down Expand Up @@ -82,7 +65,7 @@ export default function ViewedDocuments() {
{entry.title} <small>{entry.url}</small>
</Link>
</td>
<td>{friendlyDateDisplay(new Date(entry.timestamp))}</td>
<td>{dayjs(new Date(entry.timestamp)).fromNow()}</td>
</tr>
);
})}
Expand Down

0 comments on commit cfbe278

Please sign in to comment.