Skip to content
Closed
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
39 changes: 39 additions & 0 deletions client/app/components/modals/DashboardSettings.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { useAppContext } from "~/providers/AppProvider";
import { defaults, sections, sectionKeys } from "~/hooks/useDashboardPreferences";

export default function DashboardSettings() {
const { dashboard } = useAppContext();
const { visible, ready, storageError, updateVisibility } = dashboard;
return (
<section>
<h2 className="text-xl font-semibold">Dashboard</h2>
<p className="text-sm mt-3 text-(--color-fg-secondary)">
Choose which sections to show. Saved in this browser.
</p>
<fieldset disabled={!ready} className="mt-4">
<legend className="sr-only">Visible dashboard sections</legend>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{sectionKeys.map(key => (
<label key={key} className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={visible[key]}
onChange={event => updateVisibility({ ...visible, [key]: event.target.checked })}
className="h-4 w-4 accent-(--color-primary)"
/>
{sections[key]}
</label>
))}
</div>
<button className="default mt-4" type="button" onClick={() => updateVisibility({ ...defaults })}>
Reset to defaults
</button>
</fieldset>
{storageError && (
<p role="status" className="text-sm mt-3">
Browser preferences could not be loaded or saved. You can still customize this page for this visit.
</p>
)}
</section>
);
}
7 changes: 7 additions & 0 deletions client/app/components/modals/SettingsModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ApiKeysModal from "./ApiKeysModal";
import { AsyncButton } from "../AsyncButton";
import ExportModal from "./ExportModal";
import About from "./About";
import DashboardSettings from "./DashboardSettings";

interface Props {
open: boolean;
Expand Down Expand Up @@ -35,6 +36,9 @@ export default function SettingsModal({ open, setOpen }: Props) {
<TabsTrigger className={triggerClasses} value="Appearance">
Appearance
</TabsTrigger>
<TabsTrigger className={triggerClasses} value="Dashboard">
Dashboard
</TabsTrigger>
<TabsTrigger className={triggerClasses} value="Account">
Account
</TabsTrigger>
Expand All @@ -59,6 +63,9 @@ export default function SettingsModal({ open, setOpen }: Props) {
</TabsTrigger>
</TabsList>

<TabsContent value="Dashboard" className={contentClasses}>
<DashboardSettings />
</TabsContent>
<TabsContent value="Account" className={contentClasses}>
<AccountPage />
</TabsContent>
Expand Down
55 changes: 55 additions & 0 deletions client/app/hooks/useDashboardPreferences.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect, useState } from "react";

export const sections = {
stats: "All time stats",
activity: "Activity",
artists: "Top artists",
albums: "Top albums",
tracks: "Top tracks",
recent: "Last played",
} as const;
type Section = keyof typeof sections;
type Visibility = Record<Section, boolean>;
export const sectionKeys = Object.keys(sections) as Section[];
export const defaults: Visibility = {
stats: true, activity: true, artists: true,
albums: true, tracks: true, recent: true,
};
const storageKey = "koito.dashboard.visibility.v1";

export function useDashboardPreferences() {
const [visible, setVisible] = useState<Visibility>(defaults);
const [ready, setReady] = useState(false);
const [storageError, setStorageError] = useState(false);

// Read after mounting so browser preferences do not cause hydration mismatches.
useEffect(() => {
try {
const raw = localStorage.getItem(storageKey);
const saved: unknown = raw ? JSON.parse(raw) : null;
if (saved && typeof saved === "object" && !Array.isArray(saved)) {
const next = { ...defaults };
for (const key of sectionKeys) {
const value = (saved as Record<string, unknown>)[key];
if (typeof value === "boolean") next[key] = value;
}
setVisible(next);
}
} catch {
setStorageError(true);
}
setReady(true);
}, []);

function updateVisibility(next: Visibility) {
setVisible(next);
try {
localStorage.setItem(storageKey, JSON.stringify(next));
setStorageError(false);
} catch {
setStorageError(true);
}
}

return { visible, ready, storageError, updateVisibility };
}
4 changes: 4 additions & 0 deletions client/app/providers/AppProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import { getCfg, type User } from "api/api";
import { createContext, useContext, useEffect, useState } from "react";
import pkg from "../../package.json";
import semver from "semver";
import { useDashboardPreferences } from "~/hooks/useDashboardPreferences";

function isNewerVersion(current: string, latest: string): boolean {
return semver.gt(latest, current);
}

interface AppContextType {
dashboard: ReturnType<typeof useDashboardPreferences>;
user: User | null | undefined;
configurableHomeActivity: boolean;
homeItems: number;
Expand All @@ -31,6 +33,7 @@ export const useAppContext = () => {
};

export const AppProvider = ({ children }: { children: React.ReactNode }) => {
const dashboard = useDashboardPreferences();
const [user, setUser] = useState<User | null | undefined>(undefined);
const [defaultTheme, setDefaultTheme] = useState<string | undefined>(
undefined,
Expand Down Expand Up @@ -96,6 +99,7 @@ export const AppProvider = ({ children }: { children: React.ReactNode }) => {
}

const contextValue: AppContextType = {
dashboard,
user,
configurableHomeActivity,
homeItems,
Expand Down
58 changes: 36 additions & 22 deletions client/app/routes/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,56 @@ import ActivityGrid from "~/components/ActivityGrid";
import TopArtistsCard from "~/components/TopArtistsCard";
import AllTimeStats from "~/components/AllTimeStats";
import { useState } from "react";
import PeriodSelector from "~/components/PeriodSelector";
import { useAppContext } from "~/providers/AppProvider";
import { sectionKeys } from "~/hooks/useDashboardPreferences";
import PeriodSelector from "~/components/PeriodSelector";
import TopAlbumsCard from "~/components/TopAlbumsCard";
import PinnedItemGrid from "~/components/PinnedItemGrid";

export function meta({}: Route.MetaArgs) {
return [{ title: "Koito" }, { name: "description", content: "Koito" }];
}

export default function Home() {
const [period, setPeriod] = useState("week");
const { dashboard } = useAppContext();
const { visible, ready } = dashboard;

const { homeItems } = useAppContext();

const gradientClasses =
"bg-linear-to-b to-(--color-bg) from-(--color-bg-secondary) to-60%";
const showRankings = visible.artists || visible.albums || visible.tracks;
const showAny = sectionKeys.some(key => visible[key]);

return (
<main className="flex grow justify-center pb-4 w-full">
<div className="flex-1 flex flex-col items-center gap-10 md:gap-12 min-h-0 mt-8 sm:mt-10 mx-4 sm:mx-10">
<div className="flex flex-col lg:flex-row gap-10 md:gap-20">
<AllTimeStats />
<ActivityGrid configurable />
</div>
<PeriodSelector setter={setPeriod} current={period} />
<div className="container justify-center flex flex-wrap gap-10">
{/*<PinnedItemGrid />*/}
<TopArtistsCard period={period} />
<TopAlbumsCard period={period} />
<TopTracks
period={period}
limit={10}
className="min-w-[350px] w-full max-w-[750px] 2xl:max-w-[450px]"
/>
<LastPlayed showNowPlaying={true} limit={28} showSeeMore />
</div>
{ready && (
<>
{!showAny && (
<p role="status" className="text-(--color-fg-secondary) text-center">
All sections are hidden. Open Settings → Dashboard in the sidebar to show a section or reset to defaults.
</p>
)}
{(visible.stats || visible.activity) && (
<div className="flex flex-col lg:flex-row gap-10 md:gap-20">
{visible.stats && <AllTimeStats />}
{visible.activity && <ActivityGrid configurable />}
</div>
)}
{showRankings && <PeriodSelector setter={setPeriod} current={period} />}
{(showRankings || visible.recent) && (
<div className="container justify-center flex flex-wrap gap-10">
{visible.artists && <TopArtistsCard period={period} />}
{visible.albums && <TopAlbumsCard period={period} />}
{visible.tracks && (
<TopTracks
period={period}
limit={10}
className="min-w-[350px] w-full max-w-[750px] 2xl:max-w-[450px]"
/>
)}
{visible.recent && <LastPlayed showNowPlaying={true} limit={28} showSeeMore />}
</div>
)}
</>
)}
</div>
</main>
);
Expand Down
78 changes: 58 additions & 20 deletions client/app/routes/RewindPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Rewind from "~/components/rewind/Rewind";
import { type RewindStats } from "api/api";
import { useState } from "react";
import { useEffect, useState } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData, useLocation, useNavigate } from "react-router";
import { getRewindParams } from "~/utils/utils";
Expand Down Expand Up @@ -42,33 +42,48 @@ const parseParams = (

export async function clientLoader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
const { year, month } = parseParams(url.searchParams);

const res = await fetch(`/apis/web/v1/summary?year=${year}&month=${month}`);
const isYtd = url.searchParams.get("period") === "ytd";
const now = new Date();
const { year, month } = isYtd
? { year: now.getFullYear(), month: undefined }
: parseParams(url.searchParams);
const params = new URLSearchParams();
if (isYtd) {
params.set("from", String(Math.floor(new Date(year, 0, 1).getTime() / 1000)));
params.set("to", String(Math.floor(now.getTime() / 1000)));
} else {
params.set("year", String(year));
if (month) params.set("month", String(month));
}
const res = await fetch(`/apis/web/v1/summary?${params}`);
if (!res.ok) throw new Response("Failed to load summary", { status: 500 });

const stats: RewindStats = await res.json();
stats.title = `Your ${month && month > 0 ? months[month - 1] : ""} ${year} Rewind`;
return { stats };
stats.title = isYtd
? `Your ${year} Year to Date`
: `Your ${month && month > 0 ? months[month - 1] + " " : ""}${year} Rewind`;
return { stats, year, month, isYtd, asOf: now.toISOString() };
}

export default function RewindPage() {
const location = useLocation();
const navigate = useNavigate();
const { stats } = useLoaderData<{ stats: RewindStats }>();
const { stats, year: loadedYear, month: loadedMonth, isYtd, asOf } = useLoaderData<typeof clientLoader>();
const { firstActivity } = useAppContext();

const { year: loadedYear, month: loadedMonth } = parseParams(
new URLSearchParams(location.search),
);

const [year, setYear] = useState(loadedYear);
const [month, setMonth] = useState(loadedMonth);
const [showYearly, setShowYearly] = useState(
!loadedMonth || loadedMonth === 0,
);
const [showTime, setShowTime] = useState(false);

useEffect(() => {
setYear(loadedYear);
setMonth(loadedMonth);
setShowYearly(!loadedMonth);
}, [loadedYear, loadedMonth, isYtd]);

const updateParams = (updates: Record<string, string | null>) => {
const nextParams = new URLSearchParams(location.search);
for (const [key, val] of Object.entries(updates)) {
Expand All @@ -79,7 +94,7 @@ export default function RewindPage() {

const navigateMonth = (newMonth: number) => {
setMonth(newMonth);
updateParams({ year: year.toString(), month: newMonth.toString() });
updateParams({ period: null, year: year.toString(), month: newMonth.toString() });
};

const navigateYear = (direction: "prev" | "next") => {
Expand Down Expand Up @@ -111,7 +126,7 @@ export default function RewindPage() {
<div className="flex flex-col lg:flex-row items-center lg:items-start lg:mt-15 mt-5 gap-10 w-19/20 mx-auto px-5 md:px-10">
<div className="flex flex-col items-start gap-4">
<div className="flex flex-col items-center gap-4 mt-4 sm:mt-14 w-[250px] mx-auto">
{!showYearly && (
{!isYtd && !showYearly && (
<>
<div className="flex items-center gap-6 justify-around">
<button
Expand Down Expand Up @@ -157,7 +172,7 @@ export default function RewindPage() {
</div>
</>
)}
{showYearly && firstActivity && (
{!isYtd && showYearly && firstActivity && (
<div className="grid grid-cols-2 gap-2">
{Array.from(
{
Expand All @@ -174,7 +189,7 @@ export default function RewindPage() {
onClick={() => {
setYear(y);
setMonth(undefined);
updateParams({ year: y.toString(), month: null });
updateParams({ period: null, year: y.toString(), month: null });
}}
disabled={(!month || month === 0) && y === year}
>
Expand All @@ -195,22 +210,45 @@ export default function RewindPage() {
</div>
</div>
<div className="flex flex-col items-center gap-4">
<div className="flex justify-around w-2/3 mb-4">
<div className="flex flex-wrap justify-center gap-6 w-full mb-4">
<button
className="period-selector"
onClick={() => setShowYearly(false)}
disabled={!showYearly}
onClick={() => {
setShowYearly(false);
if (isYtd) {
const now = new Date();
const previous = new Date(now.getFullYear(), now.getMonth() - 1, 1);
updateParams({ period: null, year: String(previous.getFullYear()), month: String(previous.getMonth() + 1) });
}
}}
disabled={!isYtd && !showYearly}
>
MONTHLY
</button>
<button
className="period-selector"
onClick={() => setShowYearly(true)}
disabled={showYearly}
onClick={() => {
setShowYearly(true);
if (isYtd) updateParams({ period: null, year: String(new Date().getFullYear() - 1), month: null });
}}
disabled={!isYtd && showYearly}
>
YEARLY
</button>
<button
className="period-selector"
onClick={() => navigate("/rewind?period=ytd")}
disabled={isYtd}
>
YEAR TO DATE
</button>
</div>
{isYtd && (
<p className="text-sm text-(--color-fg-secondary) text-center">
January 1 – {new Date(asOf).toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" })}
{" · Your local timezone · Through the time this summary loaded"}
</p>
)}
{stats && <Rewind stats={stats} includeTime={showTime} />}
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@types/node": "^25.6.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@types/semver": "^7.8.0",
"@vanilla-extract/vite-plugin": "^5.2.2",
"tailwindcss": "^4.3.0",
"typescript": "^6.0.3",
Expand Down
Loading