Initial Commit

This commit is contained in:
2025-02-07 22:14:11 +00:00
commit 167e51bfce
15 changed files with 5612 additions and 0 deletions

11
src/Duration.jsx Normal file
View File

@@ -0,0 +1,11 @@
export default function Duration({ label, id, name, errors, register}) {
return (
<>
<div class="field-row-stacked">
<label for={id}>{label}</label>
<input type="text" id={id} {...register(name)} autocomplete="off" />
</div>
{errors && <p class="error-message">{errors.message}</p>}
</>
)
}

25
src/calc.js Normal file
View File

@@ -0,0 +1,25 @@
import {convertTime, timeToMins} from "./time.js";
import {convertDuration} from "./duration.js";
export default function calculateRemaining(data) {
const startNormalised = timeToMins(convertTime(data.startTime));
const target = convertDuration(data.target);
const breakLength = convertDuration(data.break);
const recorded = convertDuration(data.recorded);
const today = new Date();
let now = today.getHours() * 60 + today.getMinutes();
if (data.breakTaken) {
now -= breakLength;
}
let remaining = now - startNormalised;
if (remaining > target) {
remaining = target;
}
remaining -= recorded;
return remaining;
}

41
src/duration.js Normal file
View File

@@ -0,0 +1,41 @@
/**
* allows for minutes, hh:mm, 1h 1m formats
* @type {RegExp}
*/
export const durationRe = /(^\d+|^([012]?\d:\d{2})|((?:^|\s)\d+(?:\.\d+)?[hm])+)$/i;
export function convertDuration(value) {
if (!value) {
return value;
}
if (/^\d+$/.test(value)) {
return parseInt(value, 10);
}
const timeMatch = /^(?<hour>[012]?\d):(?<min>\d{2}$)/.exec(value);
if (timeMatch != null) {
const hours = parseInt(timeMatch.groups.hour, 10);
const mins = parseInt(timeMatch.groups.min, 10);
return (hours * 60) + mins;
}
if (/((?:^|\s)\d+(?:\.\d+)?[hm])+$/i.test(value)) {
let mins = 0;
const parts = value.split(/\s+/);
for (const part of parts) {
const {groups: {amount, spec}} = /^(?<amount>\d+(?:\.\d+)?)(?<spec>[hm])$/i.exec(part);
switch (spec.toLowerCase()) {
case 'h':
mins += parseFloat(amount) * 60;
break;
case 'm':
mins += parseFloat(amount);
break;
}
}
return mins;
}
return 0;
}

121
src/index.jsx Normal file
View File

@@ -0,0 +1,121 @@
import { useForm } from "react-hook-form";
import { render } from 'preact';
import {useEffect, useState} from "preact/hooks";
import { yupResolver } from "@hookform/resolvers/yup"
import * as yup from "yup";
import {convertTime, minsToTime, timeRe, timeToMins} from "./time.js";
import 'xp.css/dist/XP.css';
import './style.css';
import {convertDuration, durationRe} from "./duration.js";
import Duration from "./Duration.jsx";
import calculateRemaining from "./calc.js";
const schema = yup.object({
startTime: yup.string().matches(timeRe, {message: '12 or 24 hr time format required'}).required(),
target: yup.string().matches(durationRe, {message: 'duration in hh:mm or hrs and mins required'}).required(),
break: yup.string().matches(durationRe, {message: 'duration in hh:mm or hrs and mins required'}).required(),
breakTaken: yup.bool().required(),
recorded: yup.string().matches(durationRe, {message: 'duration in hh:mm or hrs and mins required'}).required()
}).required();
export function App() {
const {
handleSubmit,
register,
formState: { errors },
watch
} = useForm({
defaultValues: {
startTime: '09:00',
target: '7.5h',
break: '1h',
recorded: ''
},
resolver: yupResolver(schema)
});
const [currentData, setCurrentData] = useState(null);
const [remaining, setRemaining] = useState(0);
const onSubmit = (data) => {
setCurrentData({...data});
};
// update remaining when data changes and re-calc every minute
useEffect(() => {
if (!currentData) {
return;
}
setRemaining(calculateRemaining(currentData));
const interval = setInterval(() => {
setRemaining(calculateRemaining(currentData));
}, 60000);
return () => clearInterval(interval);
}, [currentData]);
// submit form when field changes
useEffect(() => {
const sub = watch(handleSubmit(onSubmit));
return () => sub.unsubscribe();
}, [handleSubmit, watch]);
return (
<div class="window" style={{margin: "32px auto", width: "250px"}}>
<div class="title-bar">
<div class="title-bar-text">
Daily Time Tracking
</div>
<div class="title-bar-controls">
<button type="button" aria-label="Close" />
</div>
</div>
<div class="window-body">
<form onSubmit={handleSubmit(onSubmit)}>
<div class="field-row-stacked">
<label for="StartTime">Start Time</label>
<input type="text" id="StartTime" {...register("startTime", { })} />
</div>
{errors?.startTime && <p class="error-message">{errors.startTime.message}</p>}
<Duration
label="Target Duration"
id="TargetDuration"
name="target"
errors={errors?.target}
register={register}
/>
<Duration
label="Break Duration"
id="BreakDuration"
name="break"
errors={errors?.break}
register={register}
/>
<div class="field-row">
<input type="checkbox" id="BreakTaken" {...register("breakTaken")} />
<label for="BreakTaken">Break Taken</label>
</div>
<Duration
label="Recorded Duration"
id="RecordedDuration"
name="recorded"
errors={errors?.recorded}
register={register}
/>
<p>
<button type="submit">Calculate</button>
</p>
<div class="field-row-stacked">
<label for="RemainingTime">Remaining Time</label>
<input type="text" id="RemainingTime" value={minsToTime(remaining)} readonly />
</div>
</form>
</div>
</div>
);
}
render(<App />, document.getElementById('app'));

8
src/style.css Normal file
View File

@@ -0,0 +1,8 @@
p.error-message {
color: #9c0000;
margin: 0 0 10px 0;
}
input[readonly] {
background-color: #eaeaea;
}

49
src/time.js Normal file
View File

@@ -0,0 +1,49 @@
export const timeRe = /^(?:[012]?\d:\d{2}|1?\d(?::\d{2})?(?:am|pm))$/i
export function convertTime(value) {
if (/^[012]?\d:\d{2}$/.test(value)) {
return value;
}
const twelveHour = /^(?<hour>[01]?\d)(?::(?<min>\d{2}))?(?<ampm>am|pm)$/i.exec(value);
if (twelveHour != null) {
let hour = parseInt(twelveHour.groups['hour'], 10);
const minute = parseInt(twelveHour.groups['min'] ?? '0', 10);
const ampm = twelveHour.groups['ampm'].toLowerCase();
if (hour === 12) {
if (ampm === 'am') {
hour = 0;
}
} else if (ampm === 'pm') {
if (hour < 12) {
hour += 12;
}
}
return `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
}
return value;
}
export function timeToMins(value) {
const match = /^(?<hour>[012]?\d):(?<min>\d{2})$/.exec(value);
if (match) {
const hour = parseInt(match.groups.hour, 10);
const min = parseInt(match.groups.min, 10);
return (hour * 60) + min;
}
return 0;
}
export function minsToTime(totalMinutes) {
let prefix = totalMinutes < 0 ? '- ' : '';
let absMinutes = Math.abs(totalMinutes);
let hours = Math.floor(absMinutes / 60);
let minutes = absMinutes % 60;
if (minutes > 0) {
return `${prefix}${hours}h ${minutes}m`;
}
if (hours > 0) {
return `${hours}h`;
}
return '0m';
}