diff --git a/apps/AGENTS.md b/apps/AGENTS.md index 3e3217e89..6decea71c 100644 --- a/apps/AGENTS.md +++ b/apps/AGENTS.md @@ -10,7 +10,8 @@ Local ports: `www` 3000, `dash` 3001, `service` 3005, `workflow` 3008. `apps/fun ## `www` - `src/libs/orpc/client.rsc.ts` is server-only and may attach `CH_API_KEY`; the browser client must never receive an API key. -- Content pages have no revalidate timer. `src/libs/orpc/client.rsc.ts` tags each server read with `WwwCacheTag` or `wwwFeedCacheTag`, and `workflow` invalidates those tags through the Vercel API, one five-minute window per tag; nothing calls into www. A write that changes what www renders must end in `scheduleFeedRevalidationStep` (in a workflow) or `workflow.startSiteRevalidation(tag)`. +- A mode is a URL space with its own frame, so the route decides it and nothing stores it. `src/app/[locale]/layout.tsx` renders the document and what every mode shares (providers, the page container, the chat dock); tech pages live under `(tech)` with the ruled frame, hobby pages under `hobby` with theirs. A frame that brings its own palette marks itself with `data-site-mode`: `@chia/themes/hobby.css` keys off it through `:root:has()` and the reader palette steps aside there. The hobby stage is the only writer of `--media-color`, on ``, and every hobby token derives from it. A work's page, `/hobby/[kind]/[slug]`, is intercepted into the `[locale]/@modal` slot when it is reached from inside the site; the page and the sheet render the same component. +- Content pages have no revalidate timer. `src/libs/orpc/client.rsc.ts` tags each server read with `WwwCacheTag` or `wwwFeedCacheTag`, and `workflow` invalidates those tags through the Vercel API, one five-minute window per tag; nothing calls into www. A write that changes what www renders must end in `scheduleFeedRevalidationStep` (in a workflow) or `workflow.startSiteRevalidation(tag)`. Hobby pages read only `media.list` and `media.get`, tagged `WwwCacheTag.Media`. - The blog navigation and related posts load in the browser, so no cached page depends on a post other than its own. Home and projects keep a timer because Spotify and GitHub send no change event. - Pages set canonical, hreflang and `og:url` through `localizedMetadata` in `src/libs/i18n/alternates.ts`; the middleware sends no alternate links. Every URL the site emits (links, sitemap, RSS, `feedUrl`) leaves the default locale unprefixed, because `/zh-TW/…` redirects. - Browser requests use the Better Auth session cookie and may access only public or caller-owned procedures. Shared reads (`@chia/services/shared/shared-reads`) go without credentials so a CDN can serve them. diff --git a/apps/dash/.next/dev/types/link.d.ts b/apps/dash/.next/dev/types/link.d.ts index 177195414..1f636c3a0 100644 --- a/apps/dash/.next/dev/types/link.d.ts +++ b/apps/dash/.next/dev/types/link.d.ts @@ -45,6 +45,7 @@ declare namespace __next_route_internal_types__ { | `/feed/notes` // ../../../src/app/(workspace)/(operator)/feed/(manage)/notes/page.tsx | `/feed/posts` // ../../../src/app/(workspace)/(operator)/feed/(manage)/posts/page.tsx | `/icon.png` // ../../../src/app/icon.png + | `/media` // ../../../src/app/(workspace)/(operator)/media/page.tsx | `/memory` // ../../../src/app/(workspace)/(operator)/memory/page.tsx | `/profile` // ../../../src/app/(workspace)/(operator)/profile/page.tsx | `/rag` // ../../../src/app/(workspace)/(operator)/rag/page.tsx diff --git a/apps/dash/.next/dev/types/routes.d.ts b/apps/dash/.next/dev/types/routes.d.ts index 2c5705143..6e9c17a2a 100644 --- a/apps/dash/.next/dev/types/routes.d.ts +++ b/apps/dash/.next/dev/types/routes.d.ts @@ -1,10 +1,10 @@ // This file is generated automatically by Next.js // Do not edit this file manually -type AppRoutes = "/" | "/agents" | "/api-keys" | "/assets" | "/auth/callback/sent-success" | "/auth/login" | "/feed" | "/feed/draft/[id]" | "/feed/drafts" | "/feed/edit/[id]" | "/feed/notes" | "/feed/posts" | "/memory" | "/profile" | "/rag" | "/rag/chunks" | "/rag/maintenance" | "/rag/runs" | "/reports" | "/reports/[id]" | "/settings" | "/settings/spotify" | "/tags" | "/users" +type AppRoutes = "/" | "/agents" | "/api-keys" | "/assets" | "/auth/callback/sent-success" | "/auth/login" | "/feed" | "/feed/draft/[id]" | "/feed/drafts" | "/feed/edit/[id]" | "/feed/notes" | "/feed/posts" | "/media" | "/memory" | "/profile" | "/rag" | "/rag/chunks" | "/rag/maintenance" | "/rag/runs" | "/reports" | "/reports/[id]" | "/settings" | "/settings/spotify" | "/tags" | "/users" type AppRouteHandlerRoutes = "/api/v1/health" | "/favicon.ico" | "/icon.png" | "/robots.txt" type PageRoutes = never -type LayoutRoutes = "/" | "/agents" | "/auth" | "/feed" | "/memory" | "/profile" | "/rag" | "/reports" | "/settings" | "/tags" +type LayoutRoutes = "/" | "/agents" | "/auth" | "/feed" | "/media" | "/memory" | "/profile" | "/rag" | "/reports" | "/settings" | "/tags" type RedirectRoutes = never type RewriteRoutes = never type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes | AppRouteHandlerRoutes @@ -27,6 +27,7 @@ interface ParamMap { "/feed/notes": {} "/feed/posts": {} "/icon.png": {} + "/media": {} "/memory": {} "/profile": {} "/rag": {} @@ -50,6 +51,7 @@ interface LayoutSlotMap { "/agents": never "/auth": never "/feed": never + "/media": never "/memory": never "/profile": never "/rag": never diff --git a/apps/dash/__tests__/media-form.test.ts b/apps/dash/__tests__/media-form.test.ts new file mode 100644 index 000000000..5a63c863d --- /dev/null +++ b/apps/dash/__tests__/media-form.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; + +import { Locale, MediaStatus } from "@chia/db/types"; + +import { mediaFormSchema } from "@/components/media/form"; +import type { MediaFormInput } from "@/components/media/form"; + +const fields = (overrides: Partial = {}): MediaFormInput => ({ + status: MediaStatus.Completed, + rating: 8, + favorite: false, + startedOn: "", + finishedOn: "2026-11-01", + originalTitle: " 葬送のフリーレン ", + releaseYear: 2023, + color: " #D6E4A1 ", + steamAppId: null, + playtimeHours: 87.5, + achievementsUnlocked: 31, + achievementsTotal: 42, + translations: { + [Locale.ZhTW]: { title: "葬送的芙莉蓮", comment: " 很好看 " }, + [Locale.En]: { title: "", comment: "ignored without a title" }, + }, + ...overrides, +}); + +describe("mediaFormSchema", () => { + it("turns blank fields into nulls and drops a locale without a title", () => { + expect(mediaFormSchema.parse(fields())).toEqual({ + status: MediaStatus.Completed, + rating: 8, + favorite: false, + startedOn: null, + finishedOn: "2026-11-01", + originalTitle: "葬送のフリーレン", + releaseYear: 2023, + color: "#D6E4A1", + steamAppId: null, + playtimeMinutes: 5250, + achievementsUnlocked: 31, + achievementsTotal: 42, + translations: { + [Locale.ZhTW]: { title: "葬送的芙莉蓮", comment: "很好看" }, + }, + }); + }); + + it("requires a title in at least one locale", () => { + const result = mediaFormSchema.safeParse( + fields({ + translations: { + [Locale.ZhTW]: { title: " ", comment: "" }, + [Locale.En]: { title: "", comment: "" }, + }, + }) + ); + expect(result.success).toBe(false); + }); + + it("refuses a colour that is not #rrggbb and accepts a blank one", () => { + expect(mediaFormSchema.safeParse(fields({ color: "teal" })).success).toBe( + false + ); + expect(mediaFormSchema.parse(fields({ color: "" })).color).toBeNull(); + }); + + it("refuses more unlocked achievements than the game has", () => { + const result = mediaFormSchema.safeParse( + fields({ achievementsUnlocked: 43 }) + ); + expect(result.error?.issues[0]?.path).toEqual(["achievementsUnlocked"]); + }); + + it("refuses a finish date before the start date", () => { + const result = mediaFormSchema.safeParse( + fields({ startedOn: "2026-11-02" }) + ); + expect(result.error?.issues[0]?.path).toEqual(["finishedOn"]); + }); +}); diff --git a/apps/dash/src/app/(workspace)/(operator)/media/layout.tsx b/apps/dash/src/app/(workspace)/(operator)/media/layout.tsx new file mode 100644 index 000000000..f1b78ee1b --- /dev/null +++ b/apps/dash/src/app/(workspace)/(operator)/media/layout.tsx @@ -0,0 +1,12 @@ +import type { ReactNode } from "react"; +import { ViewTransition } from "react"; + +const Layout = ({ children }: { children: ReactNode }) => { + return ( + +
{children}
+
+ ); +}; + +export default Layout; diff --git a/apps/dash/src/app/(workspace)/(operator)/media/page.tsx b/apps/dash/src/app/(workspace)/(operator)/media/page.tsx new file mode 100644 index 000000000..1e1224708 --- /dev/null +++ b/apps/dash/src/app/(workspace)/(operator)/media/page.tsx @@ -0,0 +1,24 @@ +import "server-only"; +import { Suspense } from "react"; + +import { Spinner } from "@heroui/react"; + +import { MediaManager } from "@/components/media/media-manager"; + +export const dynamic = "force-dynamic"; + +const MediaPage = () => ( +
+

Media log

+ + + + }> + + +
+); + +export default MediaPage; diff --git a/apps/dash/src/components/assets/file-explorer.tsx b/apps/dash/src/components/assets/file-explorer.tsx index b7e78616b..3c1a9d570 100644 --- a/apps/dash/src/components/assets/file-explorer.tsx +++ b/apps/dash/src/components/assets/file-explorer.tsx @@ -7,6 +7,8 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { FolderOpen, Info } from "lucide-react"; import { toast } from "sonner"; +import { STORAGE_BASE_URL } from "@chia/utils/config"; + import { orpc } from "@/libs/orpc/client"; import { DeleteConfirmModal } from "./delete-confirm-modal"; @@ -14,7 +16,6 @@ import { ExplorerToolbar } from "./explorer-toolbar"; import { FileDetailPanel } from "./file-detail-panel"; import { FileTreeDrawer } from "./file-tree-drawer"; import { FileTreePanel } from "./file-tree-panel"; -import { STORAGE_BASE_URL } from "./utils"; export const FileExplorer = () => { const [selectedPath, setSelectedPath] = useState(null); diff --git a/apps/dash/src/components/assets/utils.ts b/apps/dash/src/components/assets/utils.ts index a4d5855ac..f8467af7c 100644 --- a/apps/dash/src/components/assets/utils.ts +++ b/apps/dash/src/components/assets/utils.ts @@ -1,5 +1,3 @@ -export const STORAGE_BASE_URL = "https://storage.chia1104.dev"; - export function formatBytes(bytes: number, decimals = 2): string { if (bytes === 0) return "0 Bytes"; const k = 1024; diff --git a/apps/dash/src/components/media/add-drawer.tsx b/apps/dash/src/components/media/add-drawer.tsx new file mode 100644 index 000000000..2073eb601 --- /dev/null +++ b/apps/dash/src/components/media/add-drawer.tsx @@ -0,0 +1,209 @@ +"use client"; + +import { useState } from "react"; + +import { + Button, + Drawer, + Input, + Label, + ListBox, + Select, + Spinner, + TextField, +} from "@heroui/react"; +import { useDebouncedValue } from "@tanstack/react-pacer"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { toast } from "sonner"; + +import { MediaStatus } from "@chia/db/types"; +import type { MediaKind } from "@chia/db/types"; +import { isEnumValue } from "@chia/utils/is"; +import { Image } from "@chiastack/ui/image"; + +import { DrawerPanel } from "@/components/commons/drawer-panel"; +import { orpc } from "@/libs/orpc/client"; + +import { KIND_LABEL, STATUS_OPTIONS } from "./form"; +import type { MediaCandidate, MediaEntryView } from "./form"; + +const SEARCH_DEBOUNCE_MS = 400; +const MIN_QUERY_CHARS = 2; + +const SOURCE_LABEL = { + "tmdb:movie": "TMDB", + "tmdb:tv": "TMDB", + anilist: "AniList", + igdb: "IGDB", +} satisfies Record; + +/** + * Searches the catalogues of `kind` and logs the picked work. The catalogue supplies the titles + * and cover, so only the status is asked here; `onAdded` opens the new entry for the rest. + */ +export const AddDrawer = ({ + isOpen, + kind, + onAdded, + onClose, +}: { + isOpen: boolean; + kind: MediaKind; + onAdded: (entry: MediaEntryView) => void; + onClose: () => void; +}) => { + const [query, setQuery] = useState(""); + const [status, setStatus] = useState(MediaStatus.Completed); + const [debouncedQuery] = useDebouncedValue(query.trim(), { + wait: SEARCH_DEBOUNCE_MS, + }); + const canSearch = debouncedQuery.length >= MIN_QUERY_CHARS; + + const search = useQuery( + orpc.media.search.queryOptions({ + input: { kind, query: debouncedQuery }, + enabled: isOpen && canSearch, + retry: false, + }) + ); + + const create = useMutation( + orpc.media.create.mutationOptions({ + onSuccess({ entry }) { + setQuery(""); + onAdded(entry); + toast.success("Logged; add your rating and dates"); + }, + onError(error) { + toast.error(error.message); + }, + }) + ); + + const candidates = canSearch ? (search.data?.items ?? []) : []; + + return ( + !open && onClose()}> + + + + {`Log ${KIND_LABEL[kind].toLowerCase()}`} + + +
+ + + + + +
+ + {search.isError ? ( +

+ The catalogue did not answer: {search.error.message} +

+ ) : null} + {canSearch && search.isFetching ? ( +
+ +
+ ) : null} + {canSearch && search.isSuccess && candidates.length === 0 ? ( +

+ Nothing matches “{debouncedQuery}”. Try the original title. +

+ ) : null} + +
    + {candidates.map((candidate) => ( +
  • +
    + {candidate.posterUrl ? ( + + + + ) : null} +
    +
    + + {candidate.title} + + + {[ + candidate.releaseYear, + candidate.originalTitle === candidate.title + ? null + : candidate.originalTitle, + SOURCE_LABEL[candidate.source], + ] + .filter((part) => part !== null) + .join(" · ")} + +
    + +
  • + ))} +
+
+
+
+ ); +}; diff --git a/apps/dash/src/components/media/entry-form.tsx b/apps/dash/src/components/media/entry-form.tsx new file mode 100644 index 000000000..0407b0aac --- /dev/null +++ b/apps/dash/src/components/media/entry-form.tsx @@ -0,0 +1,461 @@ +"use client"; + +import { + Button, + Calendar, + DateField, + DatePicker, + Description, + FieldError, + Form, + Input, + Label, + ListBox, + NumberField, + Select, + Switch, + Tabs, + TextArea, + TextField, +} from "@heroui/react"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { parseDate } from "@internationalized/date"; +import { Controller, useForm } from "react-hook-form"; +import type { Control } from "react-hook-form"; + +import { Locale, MediaKind, MediaStatus } from "@chia/db/types"; +import { + MEDIA_COMMENT_MAX_CHARS, + MEDIA_RATING_MAX, +} from "@chia/db/validator/media"; +import { isEnumValue } from "@chia/utils/is"; + +import { LOCALES, STATUS_OPTIONS, formValuesOf, mediaFormSchema } from "./form"; +import type { + MediaEntryUpdate, + MediaEntryView, + MediaFormInput, + MediaFormOutput, +} from "./form"; + +const LOCALE_LABEL = { + [Locale.ZhTW]: "中文", + [Locale.En]: "English", +} satisfies Record; + +type FormControl = Control; + +/** Fields sit on the drawer's overlay surface; `secondary` is the variant that stays visible there in dark mode. */ +const FIELD_VARIANT = "secondary"; + +const DateInput = ({ + control, + description, + isDisabled, + label, + name, +}: { + control: FormControl; + description: string; + isDisabled: boolean; + label: string; + name: "startedOn" | "finishedOn"; +}) => ( + ( + field.onChange(date?.toString() ?? "")} + value={field.value === "" ? null : parseDate(field.value)}> + + + + {(segment) => } + + + + + + + + {description} + {fieldState.error?.message} + + + + + + + + + + + + + {(day) => {day}} + + + {(date) => } + + + + + {({ year }) => ( + + )} + + + + + + )} + /> +); + +/** An emptied number field reports `NaN`; the stored value for "not set" is `null`. */ +const NullableNumberInput = ({ + control, + description, + isDisabled, + label, + maxValue, + minValue, + name, + step = 1, +}: { + control: FormControl; + description: string; + isDisabled: boolean; + label: string; + maxValue: number; + minValue: number; + name: + | "rating" + | "releaseYear" + | "steamAppId" + | "playtimeHours" + | "achievementsUnlocked" + | "achievementsTotal"; + step?: number; +}) => ( + ( + field.onChange(Number.isNaN(next) ? null : next)} + step={step} + value={field.value ?? Number.NaN} + variant={FIELD_VARIANT}> + + + + + + + {description} + {fieldState.error?.message} + + )} + /> +); + +export const EntryForm = ({ + entry, + isPending, + onSubmit, +}: { + entry: MediaEntryView; + isPending: boolean; + onSubmit: (update: MediaEntryUpdate) => void; +}) => { + const { control, formState, handleSubmit } = useForm< + MediaFormInput, + unknown, + MediaFormOutput + >({ + resolver: zodResolver(mediaFormSchema), + defaultValues: formValuesOf(entry), + }); + + const submit = handleSubmit((update) => onSubmit(update)); + const translationsError = formState.errors.translations?.message; + + return ( +
+
+ ( + + )} + /> + + ( + + +
+ + + Shown with a sticker and on the favorites shelf. + +
+ + + +
+
+ )} + /> +
+ +
+ + +
+ + + + + {LOCALES.map((locale) => ( + + {LOCALE_LABEL[locale]} + + + ))} + + + {LOCALES.map((locale) => ( + + ( + + + + + Leave blank to show the other locale's title. + + {fieldState.error?.message} + + )} + /> + ( + + +