changed unit paths, added links to unit page

This commit is contained in:
liyunze 2026-09-02 15:46:01 +08:00
parent 90e21c436b
commit cd616218d6
17 changed files with 236 additions and 65 deletions

View file

@ -1,4 +1,5 @@
<script lang="ts">
import { unitPath } from "$lib/paths";
import VoteStack from "./VoteStack.svelte";
let {
@ -24,20 +25,21 @@
<article class="border-rule flex gap-4 border-b py-5">
<VoteStack count={voteCount} {targetType} {targetId} />
<a {href} class="group min-w-0 flex-1">
<div class="group min-w-0 flex-1">
{#if tag}
<p class="text-secondary mb-1 text-[10px] font-semibold tracking-[0.16em] uppercase">
{tag}
</p>
{/if}
{#if unitCode}
<p class="kicker">{unitCode}</p>
<a href={unitPath(unitCode.split(" / ")[0])} class="kicker">{unitCode}</a><br />
{/if}
<h3
class="text-ink group-hover:text-primary mt-1 font-sans text-[15px] leading-snug font-semibold"
<a
{href}
class="text-ink hover:text-primary mt-1 font-sans text-[15px] leading-snug font-semibold"
>
{title}
</h3>
<p class="kicker mt-1.5">{meta}</p>
</a>
<p class="kicker mt-1.5">{meta}</p>
</div>
</article>

View file

@ -28,6 +28,8 @@
if (!token) return;
try {
pinnedIds = (await query("units:getPinned", { token })) as string[];
selectedUnitId =
units.find((unit) => pinnedIds.includes(unit._id))?._id ?? units[0]?._id ?? "";
} catch {
// ignore
}
@ -35,6 +37,8 @@
const isPinned = (id: string) => pinnedIds.includes(id);
const canPinMore = $derived(pinnedIds.length < MAX_PINS);
const pinnedUnits = $derived(units.filter((u) => pinnedIds.includes(u._id)));
const unpinnedUnits = $derived(units.filter((u) => !pinnedIds.includes(u._id)));
async function togglePin(unit: UnitDoc) {
const token = getToken();
@ -79,7 +83,41 @@
{/snippet}
<div class="unit-rail">
{#each units as unit (unit._id)}
{#each pinnedUnits as unit (unit._id)}
<div class="unit-card {selectedUnitId === unit._id ? 'unit-card-active' : ''}">
<button
type="button"
class="flex h-full w-full flex-col items-start gap-1 text-left"
onclick={() => (selectedUnitId = unit._id)}
aria-label="Select {unit.code}"
>
<span class="text-ink font-serif text-base leading-tight"
>{unit.code}{unit.code2 ? ` / ${unit.code2}` : ""}</span
>
<span class="text-muted line-clamp-2 text-xs leading-snug">{unit.name}</span>
</button>
{#if authed}
<button
type="button"
class="pin-btn {isPinned(unit._id)
? 'pin-btn-active'
: ''} absolute top-1.5 right-1.5 z-10"
onclick={() => togglePin(unit)}
disabled={busy || (!isPinned(unit._id) && !canPinMore)}
title={isPinned(unit._id)
? "Unpin unit"
: canPinMore
? "Pin unit"
: "You can pin up to 10 units"}
aria-label={isPinned(unit._id) ? "Unpin unit" : "Pin unit"}
>
{@render pinIcon()}
</button>
{/if}
</div>
{/each}
{#each unpinnedUnits as unit (unit._id)}
<div class="unit-card {selectedUnitId === unit._id ? 'unit-card-active' : ''}">
<button
type="button"

7
src/lib/paths.ts Normal file
View file

@ -0,0 +1,7 @@
export function unitPath(code: string): string {
return `/${encodeURIComponent(code)}`;
}
export function postPath(code: string, postId: string): string {
return `${unitPath(code)}/${encodeURIComponent(postId)}`;
}

View file

@ -88,6 +88,21 @@ function mapQuestion(row: Record<string, any>): Record<string, any> {
return { ...row, solved: !!row.solved };
}
function addUnits(db: Db, rows: Record<string, any>[]): Record<string, any>[] {
const units = new Map<string, Record<string, any>>();
const getUnit = db.prepare(
"SELECT id AS _id, code, code2, name, description FROM units WHERE id = ?",
);
return rows.map((row) => {
if (!units.has(row.unitId)) {
const unit = getUnit.get(row.unitId) as Record<string, any> | undefined;
if (unit) units.set(row.unitId, unit);
}
return { ...row, unit: units.get(row.unitId) ?? null };
});
}
// ---- users ----
function issueSession(db: Db, user: { _id: string; name: string; role?: string }) {
@ -375,22 +390,31 @@ function notesCreate(
function notesList(db: Db, args: { topicId?: string; unitId?: string; limit?: number }) {
const limit = args.limit ?? 50;
if (args.topicId) {
return db
return addUnits(
db,
db
.prepare(
`SELECT ${NOTE_COLUMNS} FROM notes WHERE topicId = ? ORDER BY createdAt DESC LIMIT ?`,
)
.all(args.topicId, limit);
.all(args.topicId, limit) as Record<string, any>[],
);
}
if (args.unitId) {
return db
return addUnits(
db,
db
.prepare(
`SELECT ${NOTE_COLUMNS} FROM notes WHERE unitId = ? ORDER BY createdAt DESC LIMIT ?`,
)
.all(args.unitId, limit);
.all(args.unitId, limit) as Record<string, any>[],
);
}
return db
return addUnits(
db,
db
.prepare(`SELECT ${NOTE_COLUMNS} FROM notes ORDER BY createdAt DESC LIMIT ?`)
.all(limit);
.all(limit) as Record<string, any>[],
);
}
function notesSearch(db: Db, args: { query: string; limit?: number }) {
@ -398,10 +422,13 @@ function notesSearch(db: Db, args: { query: string; limit?: number }) {
.prepare(`SELECT ${NOTE_COLUMNS} FROM notes ORDER BY createdAt DESC LIMIT ?`)
.all(args.limit ?? 200) as Record<string, any>[];
const q = args.query.toLowerCase();
return all.filter(
return addUnits(
db,
all.filter(
(n) =>
String(n.title).toLowerCase().includes(q) ||
String(n.content).toLowerCase().includes(q),
),
);
}
@ -499,7 +526,7 @@ function questionsList(db: Db, args: { topicId?: string; unitId?: string; limit?
)
.all(limit)
) as Record<string, any>[];
return rows.map(mapQuestion);
return addUnits(db, rows.map(mapQuestion));
}
function questionsGetById(db: Db, args: { id: string }) {
@ -514,13 +541,16 @@ function questionsSearch(db: Db, args: { query: string; limit?: number }) {
.prepare(`SELECT ${QUESTION_COLUMNS} FROM questions ORDER BY createdAt DESC LIMIT ?`)
.all(args.limit ?? 200) as Record<string, any>[];
const q = args.query.toLowerCase();
return all
return addUnits(
db,
all
.filter(
(qr) =>
String(qr.title).toLowerCase().includes(q) ||
String(qr.content).toLowerCase().includes(q),
)
.map(mapQuestion);
.map(mapQuestion),
);
}
function searchAll(db: Db, args: { query: string; limit?: number }) {

View file

@ -36,6 +36,7 @@ export type NoteDoc = Doc<"notes"> & {
updatedAt: number;
voteCount: number;
commentCount: number;
unit?: UnitDoc;
};
export type QuestionDoc = Doc<"questions"> & {
@ -50,6 +51,7 @@ export type QuestionDoc = Doc<"questions"> & {
voteCount: number;
answerCount: number;
solved: boolean;
unit?: UnitDoc;
};
export type SearchResult = (NoteDoc & { type: "note" }) | (QuestionDoc & { type: "question" });

View file

@ -1,5 +1,6 @@
<script lang="ts">
import { query } from "$lib/api";
import { unitPath } from "$lib/paths";
import { onMount } from "svelte";
import type { UnitDoc } from "$lib/types";
@ -49,7 +50,7 @@
{:else}
<div class="unit-rail">
{#each units as unit}
<a href="/units/{unit.code}" class="unit-card group flex flex-col gap-1">
<a href={unitPath(unit.code)} class="unit-card group flex flex-col gap-1">
<span
class="text-ink group-hover:text-primary font-serif text-base leading-tight"
>{unit.code}{unit.code2 ? ` / ${unit.code2}` : ""}</span

View file

@ -0,0 +1,5 @@
<script lang="ts">
import UnitPage from "../units/[code]/+page.svelte";
</script>
<UnitPage />

View file

@ -0,0 +1,44 @@
<script lang="ts">
import { page } from "$app/state";
import { query } from "$lib/api";
import { onMount } from "svelte";
import NotePage from "../../notes/[id]/+page.svelte";
import QuestionPage from "../../questions/[id]/+page.svelte";
let postType: "note" | "question" | null = $state(null);
let loading = $state(true);
onMount(async () => {
const note = await query("details:getNoteWithDetails", { id: page.params.id });
const result =
note ?? (await query("details:getQuestionWithDetails", { id: page.params.id }));
const unit = result?.unit;
const requestedCode = (page.params.code ?? "").toLowerCase();
if (
result &&
unit &&
[unit.code, unit.code2].some((code) => code?.toLowerCase() === requestedCode)
) {
postType = note ? "note" : "question";
}
loading = false;
});
</script>
{#if loading}
<div class="page">
<p class="kicker py-16">Loading</p>
</div>
{:else if postType === "note"}
<NotePage />
{:else if postType === "question"}
<QuestionPage />
{:else}
<div class="page">
<h1 class="text-ink font-serif text-3xl">Post not found</h1>
<a href="/" class="text-secondary hover:text-secondary-dark mt-2 inline-block text-sm"
>Home</a
>
</div>
{/if}

View file

@ -3,6 +3,7 @@
import { onMount } from "svelte";
import FeedRow from "$lib/components/FeedRow.svelte";
import UnitFilter from "$lib/components/UnitFilter.svelte";
import { postPath } from "$lib/paths";
import { timeAgo } from "$lib/time";
import type { NoteDoc, UnitDoc } from "$lib/types";
@ -79,7 +80,7 @@
{:else}
{#each visible as note}
<FeedRow
href="/notes/{note._id}"
href={postPath(note.unit!.code, note._id)}
title={note.title}
unitCode={note.unit
? note.unit.code + (note.unit.code2 ? ` / ${note.unit.code2}` : "")

View file

@ -44,7 +44,9 @@
});
async function reloadComments() {
const updated = await query("details:getNoteWithDetails", { id: page.params.id });
const updated = await query("details:getNoteWithDetails", {
id: page.params.id,
});
if (updated) comments = (updated as any).comments ?? [];
}
@ -123,7 +125,9 @@
title: editTitle.trim(),
content: editContent.trim(),
});
const updated = await query("details:getNoteWithDetails", { id: note._id });
const updated = await query("details:getNoteWithDetails", {
id: note._id,
});
if (updated) {
note = updated as NoteDoc;
topic = (updated as any).topic ?? null;
@ -150,13 +154,19 @@
<div class="flex gap-5">
<VoteStack count={note.voteCount} targetType="note" targetId={note._id} />
<div class="min-w-0 flex-1">
<p class="kicker">
{#if unit}{unit.code}{unit.code2
? ` / ${unit.code2}`
: ""}{/if}{#if unit && topic}
·
{/if}{#if topic}{topic.name}{/if}
</p>
<div class="kicker">
{#if unit}
<a href={`/${unit.code}`} class="hover:text-primary">
{unit.code}{unit.code2 ? ` / ${unit.code2}` : ""}
</a>
{/if}
{#if unit && topic}
{" · "}
{/if}
{#if topic}
{topic.name}
{/if}
</div>
{#if editMode}
<input
type="text"

View file

@ -5,6 +5,7 @@
import { onMount } from "svelte";
import { get } from "svelte/store";
import MarkdownEditor from "$lib/components/MarkdownEditor.svelte";
import { postPath } from "$lib/paths";
import type { TopicDoc, UnitDoc } from "$lib/types";
let topics: TopicDoc[] = $state([]);
@ -51,16 +52,19 @@
loading = true;
try {
let unitId = selectedUnitId;
let unitCode = units.find((unit) => unit._id === unitId)?.code ?? "";
if (useCustomUnit && customUnit.trim()) {
const existing = units.find(
(u) => u.code.toLowerCase() === customUnit.trim().toUpperCase(),
unitCode = customUnit.trim().toUpperCase();
const existing = units.find((u) =>
[u.code, u.code2].some((code) => code?.toUpperCase() === unitCode),
);
if (existing) {
unitId = existing._id;
unitCode = existing.code;
} else {
unitId = (await mutation("units:createCustom", {
code: customUnit.trim().toUpperCase(),
name: customUnit.trim().toUpperCase(),
code: unitCode,
name: unitCode,
})) as string;
}
}
@ -73,7 +77,7 @@
unitId,
})) as string;
goto(`/notes/${id}`);
goto(postPath(unitCode, id));
} catch (err: any) {
error = err.message ?? "Failed to publish note";
} finally {

View file

@ -5,6 +5,7 @@
import { onMount } from "svelte";
import { get } from "svelte/store";
import MarkdownEditor from "$lib/components/MarkdownEditor.svelte";
import { postPath } from "$lib/paths";
import type { TopicDoc, UnitDoc } from "$lib/types";
let topics: TopicDoc[] = $state([]);
@ -51,16 +52,19 @@
loading = true;
try {
let unitId = selectedUnitId;
let unitCode = units.find((unit) => unit._id === unitId)?.code ?? "";
if (useCustomUnit && customUnit.trim()) {
const existing = units.find(
(u) => u.code.toLowerCase() === customUnit.trim().toUpperCase(),
unitCode = customUnit.trim().toUpperCase();
const existing = units.find((u) =>
[u.code, u.code2].some((code) => code?.toUpperCase() === unitCode),
);
if (existing) {
unitId = existing._id;
unitCode = existing.code;
} else {
unitId = (await mutation("units:createCustom", {
code: customUnit.trim().toUpperCase(),
name: customUnit.trim().toUpperCase(),
code: unitCode,
name: unitCode,
})) as string;
}
}
@ -73,7 +77,7 @@
unitId,
})) as string;
goto(`/questions/${id}`);
goto(postPath(unitCode, id));
} catch (err: any) {
error = err.message ?? "Failed to post question";
} finally {

View file

@ -3,6 +3,7 @@
import { onMount } from "svelte";
import FeedRow from "$lib/components/FeedRow.svelte";
import UnitFilter from "$lib/components/UnitFilter.svelte";
import { postPath } from "$lib/paths";
import { timeAgo } from "$lib/time";
import type { QuestionDoc, UnitDoc } from "$lib/types";
@ -86,7 +87,7 @@
{:else}
{#each visible as question}
<FeedRow
href="/questions/{question._id}"
href={postPath(question.unit!.code, question._id)}
title={question.title}
unitCode={question.unit
? question.unit.code + (question.unit.code2 ? ` / ${question.unit.code2}` : "")

View file

@ -2,6 +2,7 @@
import { query } from "$lib/api";
import { onMount } from "svelte";
import FeedRow from "$lib/components/FeedRow.svelte";
import { postPath } from "$lib/paths";
import { timeAgo } from "$lib/time";
import type { SearchResult } from "$lib/types";
@ -51,8 +52,11 @@
{#each results as result}
{#if result.type === "note"}
<FeedRow
href="/notes/{result._id}"
href={postPath(result.unit!.code, result._id)}
title={result.title}
unitCode={result.unit
? result.unit.code + (result.unit.code2 ? ` / ${result.unit.code2}` : "")
: undefined}
meta="{result.authorName} · {timeAgo(
result.createdAt,
)} · {result.commentCount} comment{result.commentCount === 1 ? '' : 's'}"
@ -63,8 +67,11 @@
/>
{:else}
<FeedRow
href="/questions/{result._id}"
href={postPath(result.unit!.code, result._id)}
title={result.title}
unitCode={result.unit
? result.unit.code + (result.unit.code2 ? ` / ${result.unit.code2}` : "")
: undefined}
meta="{result.authorName} · {timeAgo(
result.createdAt,
)} · {result.answerCount} answer{result.answerCount === 1 ? '' : 's'}"

View file

@ -3,6 +3,7 @@
import { page } from "$app/state";
import { onMount } from "svelte";
import FeedRow from "$lib/components/FeedRow.svelte";
import { postPath } from "$lib/paths";
import { timeAgo } from "$lib/time";
import type { NoteDoc, QuestionDoc, TopicDoc } from "$lib/types";
@ -45,8 +46,11 @@
<p class="kicker border-rule mt-10 border-t pt-8">Notes</p>
{#each notes as note}
<FeedRow
href="/notes/{note._id}"
href={postPath(note.unit!.code, note._id)}
title={note.title}
unitCode={note.unit
? note.unit.code + (note.unit.code2 ? ` / ${note.unit.code2}` : "")
: undefined}
meta="{note.authorName} · {timeAgo(
note.createdAt,
)} · {note.commentCount} comment{note.commentCount === 1 ? '' : 's'}"
@ -61,8 +65,12 @@
<p class="kicker border-rule mt-10 border-t pt-8">Questions</p>
{#each questions as question}
<FeedRow
href="/questions/{question._id}"
href={postPath(question.unit!.code, question._id)}
title={question.title}
unitCode={question.unit
? question.unit.code +
(question.unit.code2 ? ` / ${question.unit.code2}` : "")
: undefined}
meta="{question.authorName} · {timeAgo(
question.createdAt,
)} · {question.answerCount} answer{question.answerCount === 1 ? '' : 's'}"

View file

@ -3,6 +3,7 @@
import { onMount } from "svelte";
import FeedRow from "$lib/components/FeedRow.svelte";
import UnitRail from "$lib/components/UnitRail.svelte";
import { postPath } from "$lib/paths";
import { timeAgo } from "$lib/time";
import type { NoteDoc, QuestionDoc, UnitDoc } from "$lib/types";
@ -70,13 +71,18 @@
{#if selectedUnit}
<div class="pt-6">
<div class="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
<h2 class="text-ink font-serif text-2xl font-medium">
<a
href={`/${selectedUnit.code}`}
class="text-ink hover:text-primary font-serif text-2xl font-medium"
>
{selectedUnit.code}{selectedUnit.code2 ? ` / ${selectedUnit.code2}` : ""}
</h2>
</a>
<p class="text-muted text-sm">{selectedUnit.name}</p>
</div>
{#if selectedUnit.description}
<p class="text-muted mt-1 text-sm">{selectedUnit.description}</p>
<p class="text-muted mt-1 text-sm">
{selectedUnit.description}
</p>
{/if}
{#if contentLoading}
@ -86,7 +92,7 @@
<p class="kicker border-rule mt-8 border-t pt-8">Notes</p>
{#each notes as note}
<FeedRow
href="/notes/{note._id}"
href={postPath(selectedUnit.code, note._id)}
title={note.title}
unitCode={selectedUnit.code +
(selectedUnit.code2 ? ` / ${selectedUnit.code2}` : "")}
@ -106,7 +112,7 @@
<p class="kicker border-rule mt-8 border-t pt-8">Questions</p>
{#each questions as question}
<FeedRow
href="/questions/{question._id}"
href={postPath(selectedUnit.code, question._id)}
title={question.title}
unitCode={selectedUnit.code +
(selectedUnit.code2 ? ` / ${selectedUnit.code2}` : "")}

View file

@ -3,6 +3,7 @@
import { page } from "$app/state";
import { onMount } from "svelte";
import FeedRow from "$lib/components/FeedRow.svelte";
import { postPath } from "$lib/paths";
import { timeAgo } from "$lib/time";
import type { NoteDoc, QuestionDoc, UnitDoc } from "$lib/types";
@ -48,7 +49,7 @@
<p class="kicker border-rule mt-10 border-t pt-8">Notes</p>
{#each notes as note}
<FeedRow
href="/notes/{note._id}"
href={postPath(unit.code, note._id)}
title={note.title}
unitCode={unit.code + (unit.code2 ? ` / ${unit.code2}` : "")}
meta="{note.authorName} · {timeAgo(
@ -65,7 +66,7 @@
<p class="kicker border-rule mt-10 border-t pt-8">Questions</p>
{#each questions as question}
<FeedRow
href="/questions/{question._id}"
href={postPath(unit.code, question._id)}
title={question.title}
unitCode={unit.code + (unit.code2 ? ` / ${unit.code2}` : "")}
meta="{question.authorName} · {timeAgo(