-
-
Notifications
You must be signed in to change notification settings - Fork 0
refactor(Counter): recreate component
#3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,35 +1,251 @@ | ||
| "use client"; | ||
| import React, { useEffect, useState, useMemo } from 'react'; | ||
| import { Temporal } from '@js-temporal/polyfill'; | ||
| import { WDXL_Lubrifont_JP_N } from 'next/font/google'; | ||
| import { Incident } from '@/types/global'; | ||
| import { DeleteForever, ExpandMore, ExpandLess, RestartAlt, Info } from '@mui/icons-material'; | ||
|
|
||
| import { useEffect, useState } from "react"; | ||
| const WdxlLubrifontJpN = WDXL_Lubrifont_JP_N({ | ||
| subsets: ['latin'], | ||
| weight: ['400'], | ||
| }); | ||
|
|
||
| export function Counter() { | ||
| const [daysWithoutIncidents, setDaysWithoutIncidents] = useState<number>(0); | ||
| export function Counter({ props: { title, history, description } }: { props: Incident }) { | ||
| const sortedHistory = useMemo( | ||
| () => [...history].sort((a, b) => a.epochMilliseconds - b.epochMilliseconds), | ||
| [history] | ||
| ); | ||
|
|
||
| const [shownDate, setShownDate] = useState<Temporal.Instant>(sortedHistory.at(-1) || Temporal.Now.instant()); | ||
| const [now, setNow] = useState(() => Temporal.Now.instant()); | ||
| const [showAccordion, setShowAccordion] = useState(false); | ||
|
|
||
| useEffect(() => { | ||
| // Only using this to save the date of the last incident in localStorage | ||
| const lastIncident = localStorage.getItem("lastIncidentDate"); | ||
| if (lastIncident) { | ||
| const diff = | ||
| (Date.now() - new Date(lastIncident).getTime()) / (1000 * 60 * 60 * 24); | ||
| setDaysWithoutIncidents(Math.floor(diff)); | ||
| const interval = setInterval(() => { | ||
| setNow(Temporal.Now.instant()); | ||
| }, 1000); | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| return () => clearInterval(interval); | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| }, []); | ||
|
|
||
| function resetDate() { | ||
| const now = Temporal.Now.instant(); | ||
| sortedHistory.push(now); | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| setShownDate(now); | ||
| } | ||
|
IvanGodinez21 marked this conversation as resolved.
IvanGodinez21 marked this conversation as resolved.
|
||
|
|
||
| function getBgColor(days: number) { | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| if (days < 7) return 'bg-red-400'; | ||
| if (days < 30) return 'bg-yellow-400'; | ||
| if (days < 183) return 'bg-green-400'; | ||
| if (days >= 365) return 'bg-blue-400'; | ||
| return 'bg-green-500'; | ||
| } | ||
|
|
||
| function timeAgo({ | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| pastDate, | ||
| targetDate, | ||
| alwaysRelative, | ||
| }: { | ||
| pastDate: Temporal.Instant; | ||
| targetDate: Temporal.Instant; | ||
| alwaysRelative?: boolean; | ||
| }) { | ||
| const dateDiff = targetDate.since(pastDate, { largestUnit: 'auto' }); | ||
| const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; | ||
| const locale = Intl.DateTimeFormat().resolvedOptions().locale; | ||
|
|
||
| const relativeTimeFormat = new Intl.RelativeTimeFormat(locale, { | ||
| numeric: 'auto', | ||
| }); | ||
| const units: [Intl.RelativeTimeFormatUnit, number][] = [ | ||
| ['second', 60], | ||
| ['minute', 60], | ||
| ['hour', 24], | ||
| ['day', 30], | ||
| ['month', 12], | ||
| ['year', Number.POSITIVE_INFINITY], | ||
| ]; | ||
| let delta = (targetDate.epochMilliseconds - pastDate.epochMilliseconds) / 1000; | ||
|
|
||
| if (alwaysRelative) { | ||
| let value = delta; | ||
| for (const [unit, limit] of units) { | ||
| if (Math.abs(value) < limit) { | ||
| return relativeTimeFormat.format(-Math.round(value), unit); | ||
| } | ||
| value /= limit; | ||
| } | ||
| } else { | ||
| setDaysWithoutIncidents(0); | ||
| if (dateDiff.months >= 1 || dateDiff.years >= 1) { | ||
| const date = pastDate.toZonedDateTimeISO(timeZone); | ||
| return date.toLocaleString(locale, { | ||
| month: 'short', | ||
| day: 'numeric', | ||
| year: 'numeric', | ||
| weekday: undefined, | ||
| }); | ||
| } | ||
| for (const [unit, limit] of units.slice(0, 4)) { | ||
| if (Math.abs(delta) < limit) { | ||
| return relativeTimeFormat.format(-Math.round(delta), unit); | ||
| } | ||
| delta /= limit; | ||
| } | ||
| } | ||
| }, []); | ||
|
|
||
| const variantClass = | ||
| daysWithoutIncidents === 0 | ||
| ? "bg-red-600 text-white" | ||
| : daysWithoutIncidents > 10 | ||
| ? "bg-green-600 text-white" | ||
| : daysWithoutIncidents > 5 | ||
| ? "bg-yellow-400 text-black" | ||
| : "bg-blue-600 text-white"; | ||
| const date = pastDate.toZonedDateTimeISO(timeZone); | ||
| return date.toLocaleString(locale, { | ||
| month: 'short', | ||
| day: 'numeric', | ||
| year: 'numeric', | ||
| }); | ||
| } | ||
|
|
||
| function longestDaysRecord({ history, now }: { history: Temporal.Instant[]; now: Temporal.Instant }) { | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| if (history.length === 0) return 0; | ||
| if (history.length === 1) { | ||
| const onlyDatePlain = Temporal.PlainDate.from(history[0].toString().slice(0, 10)); | ||
| const nowPlain = Temporal.PlainDate.from(now.toString().slice(0, 10)); | ||
| return Math.max(0, onlyDatePlain.until(nowPlain).days); | ||
| } | ||
| const sortedReversedHistory = [...sortedHistory].reverse(); | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| const toPlainDate = (inst: Temporal.Instant) => Temporal.PlainDate.from(inst.toString().slice(0, 10)); | ||
|
|
||
| let maxGap = 0; | ||
| for (let i = 0; i < sortedReversedHistory.length - 1; i++) { | ||
| const a = toPlainDate(sortedReversedHistory[i]); | ||
| const b = toPlainDate(sortedReversedHistory[i + 1]); | ||
| const gap = a.until(b).days; | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| if (gap > maxGap) maxGap = gap; | ||
| } | ||
|
|
||
| const lastPlain = toPlainDate(sortedReversedHistory[sortedReversedHistory.length - 1]); | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| const nowPlain = Temporal.PlainDate.from(now.toString().slice(0, 10)); | ||
| const lastGap = lastPlain.until(nowPlain).days; | ||
| if (lastGap > maxGap) maxGap = lastGap; | ||
|
|
||
| return Math.max(0, Math.floor(maxGap)); | ||
| } | ||
|
|
||
| const relative = timeAgo({ pastDate: shownDate, targetDate: now }); | ||
| const lastIncidentPlainDate = Temporal.PlainDate.from(shownDate.toString().slice(0, 10)); | ||
| const todayPlainDate = Temporal.PlainDate.from(now.toString().slice(0, 10)); | ||
| const days = lastIncidentPlainDate.until(todayPlainDate).days; | ||
| const daysString = Math.max(0, days).toString().padStart(8, '0'); | ||
| const bgColor = getBgColor(days); | ||
|
|
||
| return ( | ||
| <div className={`${variantClass} px-6 py-4 rounded-lg shadow-md text-center w-full max-w-sm`}> | ||
| <span className="text-xs block">Days without incidents</span> | ||
| <span className="text-3xl font-bold">{daysWithoutIncidents}</span> | ||
| <div className='bg-black text-white rounded-lg max-w-3xl w-full shadow-xl divide-y-2 divide-gray-900'> | ||
| <div className='relative bg-black text-center rounded-t-lg py-3'> | ||
| <div className='absolute left-4 top-1/2 -translate-y-1/2'> | ||
| <span | ||
| className={['block w-3.5 h-3.5 rounded-full animate-ping opacity-40 absolute', bgColor].join(' ')} | ||
| ></span> | ||
| <span className={['block w-3.5 h-3.5 rounded-full relative', bgColor].join(' ')}></span> | ||
| </div> | ||
|
|
||
| <span className='opacity-60 mr-2'>Days since</span> | ||
| <span className='font-bold text-l'>{title}</span> | ||
|
IvanGodinez21 marked this conversation as resolved.
|
||
| <span className='relative group cursor-pointer' tabIndex={0} aria-label='Info'> | ||
| <Info className='ml-1 text-blue-500' /> | ||
| <span | ||
| className='absolute left-1/2 top-full z-10 mt-2 w-40 -translate-x-1/2 rounded bg-black px-2 py-1 text-xs text-white opacity-0 group-hover:opacity-100 group-focus:opacity-100 pointer-events-none transition-opacity' | ||
| role='tooltip' | ||
| > | ||
| {description} | ||
| </span> | ||
| </span> | ||
|
|
||
| <div className='absolute right-4 top-1/2 -translate-y-1/2'> | ||
| <span | ||
| className={['block w-3.5 h-3.5 rounded-full animate-ping opacity-40 absolute', bgColor].join(' ')} | ||
| ></span> | ||
| <span className={['block w-3.5 h-3.5 rounded-full relative', bgColor].join(' ')}></span> | ||
| </div> | ||
| </div> | ||
|
|
||
| <div className='bg-white flex justify-center'> | ||
| <div className='flex w-full divide-x-2 divide-gray-900'> | ||
| {daysString.split('').map((digit, index) => ( | ||
| <span | ||
| key={index} | ||
| className={[ | ||
| WdxlLubrifontJpN.className, | ||
| 'bg-white text-black text-6xl leading-none flex items-center justify-center w-16 h-24 flex-1', | ||
| ].join(' ')} | ||
| > | ||
| {digit} | ||
| </span> | ||
| ))} | ||
| </div> | ||
| </div> | ||
| <div | ||
| className={[ | ||
| 'bg-yellow-200 overflow-hidden transition-[max-height,padding,overflow] duration-300', | ||
| showAccordion ? 'max-h-48 overflow-y-auto px-4 py-3' : 'max-h-0 p-0 pointer-events-none', | ||
| ].join(' ')} | ||
| > | ||
| {(() => { | ||
| const sortedReversedHistory = [...sortedHistory].reverse(); | ||
| const entriesToShow = sortedReversedHistory.length > 1 ? sortedReversedHistory.slice(1) : []; | ||
|
|
||
| if (!entriesToShow.length) { | ||
| return <p className='text-center text-gray-600'>No history yet.</p>; | ||
| } | ||
| return ( | ||
| <ol className='relative border-s border-gray-200 dark:border-gray-700 space-y-3'> | ||
| {entriesToShow.map((value, index) => ( | ||
| <li key={index} className='ms-4'> | ||
| <div className='absolute w-3 h-3 bg-gray-200 rounded-full mt-1.5 -start-1.5 border border-white dark:border-gray-900 dark:bg-gray-700'></div> | ||
| <time className='mb-1 text-sm font-normal leading-none text-gray-700 '> | ||
| {value.toLocaleString()} ( | ||
| <span>{timeAgo({ pastDate: value, targetDate: now, alwaysRelative: true })}</span>) | ||
| </time> | ||
| </li> | ||
| ))} | ||
| </ol> | ||
| ); | ||
| })()} | ||
| </div> | ||
| <div className='bg-yellow-400 rounded-b-lg text-black text-center py-3 px-4 text-base flex'> | ||
| <div className='flex-3 grow-3 flex flex-col items-start justify-center space-y-1'> | ||
| <div className='flex items-center'> | ||
| <span className='opacity-60 mr-1'>Last:</span> | ||
| <span>{relative}</span> | ||
| </div> | ||
| {sortedHistory.length > 1 && ( | ||
| <div className='flex items-center'> | ||
| <span className='opacity-60 mr-1'>Record:</span> | ||
| <span>{longestDaysRecord({ history: sortedHistory, now })} days</span> | ||
| </div> | ||
| )} | ||
| </div> | ||
| <div className='flex-1 grow flex items-center justify-end gap-2'> | ||
| <button aria-label='Delete' className='bg-black text-red-400 px-3 py-1 rounded hover:bg-gray-800 transition'> | ||
| <span aria-hidden='true'> | ||
| <DeleteForever /> | ||
| </span> | ||
| </button> | ||
|
IvanGodinez21 marked this conversation as resolved.
IvanGodinez21 marked this conversation as resolved.
|
||
| <button | ||
| aria-label='Reset' | ||
| className='bg-black text-blue-400 px-3 py-1 rounded hover:bg-gray-800 transition' | ||
| onClick={() => resetDate()} | ||
| > | ||
| <span aria-hidden='true'> | ||
| <RestartAlt /> | ||
| </span> | ||
| </button> | ||
| <button | ||
| aria-label={showAccordion ? 'Collapse section' : 'Expand section'} | ||
| aria-expanded={showAccordion} | ||
| className='bg-black text-white px-3 py-1 rounded hover:bg-gray-800 transition' | ||
| onClick={() => setShowAccordion(!showAccordion)} | ||
| > | ||
| <span aria-hidden='true'>{showAccordion ? <ExpandLess /> : <ExpandMore />}</span> | ||
| </button> | ||
| </div> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| export default Counter; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,20 +1,19 @@ | ||
| import { Incident } from "@/types/incident"; | ||
|
|
||
| import { Incident } from '@/types/global'; | ||
| interface Props { | ||
| incident: Incident; | ||
| } | ||
|
|
||
| export function IncidentCard({ incident }: Props) { | ||
| // Compute a deterministic date in DD-MM-YYYY using the ISO string to avoid hydration differences | ||
| const isoDate = new Date(incident.date).toISOString().split("T")[0]; | ||
| const [year, month, day] = isoDate.split("-"); | ||
| const isoDate = incident.history[0]?.toString().split('T')[0]; | ||
| const [year, month, day] = isoDate.split('-'); | ||
| const formattedDate = `${day}-${month}-${year}`; | ||
|
|
||
| return ( | ||
| <div className="bg-white p-4 rounded-lg shadow-sm border"> | ||
| <h3 className="font-semibold text-black">{incident.title}</h3> | ||
| <p className="text-sm text-gray-600 mt-1">{incident.description}</p> | ||
| <span className="text-xs text-red-600 mt-2 block">{formattedDate}</span> | ||
| <div className='bg-white p-4 rounded-lg shadow-sm border'> | ||
| <h3 className='font-semibold text-black'>{incident.title}</h3> | ||
| <p className='text-sm text-gray-600 mt-1'>{incident.description}</p> | ||
| <span className='text-xs text-red-600 mt-2 block'>{formattedDate}</span> | ||
| </div> | ||
| ); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.