Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions apps/server/src/db/seeds/08_short_sessions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { PageStat } from '@koinsight/common/types/page-stat';
import { setHours, setMinutes, setSeconds, startOfDay, subDays } from 'date-fns';
import { Knex } from 'knex';
import { db } from '../../knex';
import { createPageStat } from '../factories/page-stat-factory';
import { SEEDED_DEVICES } from './01_devices';
import { SEEDED_BOOKS } from './02_books';
import { SEEDED_BOOK_DEVICES } from './03_book_devices';

// Simulates "accidental opens" in KOReader: a book is opened briefly and
// shows up on the calendar with a 00:00 total. Lets us exercise the
// "Hide entries under a minute" toggle on the calendar views.
export async function seed(_knex: Knex): Promise<void> {
const today = new Date();
const promises: Promise<PageStat>[] = [];

const targetBooks = SEEDED_BOOKS.slice(0, 6);

targetBooks.forEach((book, bookIndex) => {
const bookDevice = SEEDED_BOOK_DEVICES.find((bd) => bd.book_md5 === book.md5);
const device = SEEDED_DEVICES.find((d) => d.id === bookDevice?.device_id);
if (!bookDevice || !device) return;

// Spread short sessions across the last 14 days, one per book per day,
// so multiple short entries appear on the same days too.
for (let dayOffset = 1; dayOffset <= 14; dayOffset++) {
if ((dayOffset + bookIndex) % 3 !== 0) continue;

const day = subDays(startOfDay(today), dayOffset);
const startTime = setSeconds(setMinutes(setHours(day, 9 + bookIndex), 15), 0);

promises.push(
createPageStat(db, book, bookDevice, device, {
page: 1,
start_time: startTime.valueOf() / 1000,
duration: 5 + ((dayOffset + bookIndex) % 20), // 5-24 seconds
total_pages: bookDevice.pages,
})
);
}
});

const stats = await Promise.all(promises);
console.log(`✓ Seeded ${stats.length} short (under a minute) reading sessions`);
}
67 changes: 48 additions & 19 deletions apps/web/src/pages/book-page/book-page-calendar.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { BookWithData, PageStat } from '@koinsight/common/types';
import { Flex, Switch } from '@mantine/core';
import { IconClock } from '@tabler/icons-react';
import { startOfDay } from 'date-fns/startOfDay';
import { sum } from 'ramda';
import { JSX } from 'react';
import { JSX, useMemo, useState } from 'react';
import { Calendar, CalendarEvent } from '../../components/calendar/calendar';
import { getDuration, shortDuration } from '../../utils/dates';

Expand All @@ -15,26 +16,54 @@ type DayData = {
};

export function BookPageCalendar({ book }: BookPageCalendarProps): JSX.Element {
const calendarEvents = book.stats.reduce<Record<string, CalendarEvent<DayData>>>((acc, event) => {
const date = startOfDay(event.start_time);
const key = date.toISOString();
acc[key] = acc[key] || { date, data: { events: [] } };
acc[key].data = acc[key]?.data?.events
? { events: [...acc[key].data.events, event] }
: { events: [event] };
const [hideEmpty, setHideEmpty] = useState(false);

Comment on lines +19 to 20
return acc;
}, {});
const calendarEvents = useMemo(() => {
const grouped = book.stats.reduce<Record<string, CalendarEvent<DayData>>>((acc, event) => {
const date = startOfDay(event.start_time);
const key = date.toISOString();
acc[key] = acc[key] || { date, data: { events: [] } };
acc[key].data = acc[key]?.data?.events
? { events: [...acc[key].data.events, event] }
: { events: [event] };

return acc;
}, {});

if (!hideEmpty) {
return grouped;
}

return Object.entries(grouped).reduce<Record<string, CalendarEvent<DayData>>>(
(acc, [key, entry]) => {
const total = sum(entry.data!.events.map((event) => event.duration));
if (total >= 60) {
acc[key] = entry;
Comment on lines +39 to +41
}
return acc;
},
{}
);
}, [book.stats, hideEmpty]);

return (
<Calendar<DayData>
events={calendarEvents}
dayRenderer={(data) => (
<>
<IconClock size={14} />{' '}
{shortDuration(getDuration(sum(data.events.map((event) => event.duration))))}
</>
)}
/>
<>
<Flex justify="flex-end" mb="sm">
<Switch
label="Hide entries under a minute"
checked={hideEmpty}
onChange={(e) => setHideEmpty(e.currentTarget.checked)}
/>
</Flex>
<Calendar<DayData>
events={calendarEvents}
dayRenderer={(data) => (
<>
<IconClock size={14} />{' '}
{shortDuration(getDuration(sum(data.events.map((event) => event.duration))))}
</>
)}
/>
</>
);
}
42 changes: 37 additions & 5 deletions apps/web/src/pages/calendar-page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { PageStat } from '@koinsight/common/types';
import { Book } from '@koinsight/common/types/book';
import { Anchor, Flex, Loader, Title } from '@mantine/core';
import { Anchor, Flex, Loader, Switch, Title } from '@mantine/core';
import { IconClock } from '@tabler/icons-react';
import { startOfDay } from 'date-fns/startOfDay';
import { sum, uniq } from 'ramda';
import { JSX, useCallback, useMemo } from 'react';
import { JSX, useCallback, useMemo, useState } from 'react';
import { Link } from 'react-router';
import { useBooks } from '../api/books';
import { usePageStats } from '../api/use-page-stats';
Expand All @@ -23,6 +23,8 @@ export function CalendarPage(): JSX.Element {
isLoading: eventsLoading,
} = usePageStats();

const [hideEmpty, setHideEmpty] = useState(false);

Comment on lines +26 to +27
const calendarEvents = useMemo<Record<string, CalendarEvent<DayData>>>(() => {
if (eventsLoading || !events) {
return {};
Expand All @@ -42,8 +44,31 @@ export function CalendarPage(): JSX.Element {
return acc;
}, {});

return eventsList;
}, [events, eventsLoading]);
if (!hideEmpty) {
return eventsList;
}

return Object.entries(eventsList).reduce<Record<string, CalendarEvent<DayData>>>(
(acc, [key, entry]) => {
const totalsByBook = entry.data!.events.reduce<Record<string, number>>((totals, event) => {
totals[event.book_md5] = (totals[event.book_md5] ?? 0) + event.duration;
return totals;
}, {});

const filtered = entry.data!.events.filter(
(event) => totalsByBook[event.book_md5] >= 60
);
Comment on lines +58 to +60

if (filtered.length === 0) {
return acc;
}

acc[key] = { ...entry, data: { events: filtered } };
return acc;
},
{}
);
}, [events, eventsLoading, hideEmpty]);

const getBookByMd5 = useCallback(
(md5: Book['md5']) => books?.find((book) => book.md5 === md5),
Expand Down Expand Up @@ -88,7 +113,14 @@ export function CalendarPage(): JSX.Element {

return (
<>
<Title mb="xl">Calendar</Title>
<Flex justify="space-between" align="center" mb="xl" wrap="wrap" gap="md">
<Title>Calendar</Title>
<Switch
label="Hide entries under a minute"
checked={hideEmpty}
onChange={(e) => setHideEmpty(e.currentTarget.checked)}
/>
</Flex>
<Calendar<DayData>
events={calendarEvents}
dayRenderer={(data) => getBookNames(data).map((el) => <div>{el}</div>)}
Expand Down
Loading