Download more, file labels, split-file grouping, settings for labels and tags
- Files tab: "Download more" adds files to a model's selection and queues them - Colored file labels (Model, MTP, Vision/mmproj, imatrix, Config, …) - Split GGUF/safetensors parts shown and selected as one entry everywhere - Settings page with a Labels section: file label names/colors, tag rename/recolor/delete; new settings table and tags.color - Quants only count model weights Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5211ec9064
commit
df18415e02
34 files changed
+2256
-132
No files matched your search
@@ -0,0 +1,79 @@
|
||||
// Named label colors. Class strings are spelled out in full so Tailwind generates them.
|
||||
|
||||
export const LABEL_COLORS = [
|
||||
"gray",
|
||||
"red",
|
||||
"orange",
|
||||
"amber",
|
||||
"yellow",
|
||||
"lime",
|
||||
"green",
|
||||
"emerald",
|
||||
"teal",
|
||||
"cyan",
|
||||
"sky",
|
||||
"blue",
|
||||
"indigo",
|
||||
"violet",
|
||||
"purple",
|
||||
"fuchsia",
|
||||
"pink",
|
||||
"rose",
|
||||
] as const;
|
||||
export type LabelColor = (typeof LABEL_COLORS)[number];
|
||||
|
||||
export function isLabelColor(v: unknown): v is LabelColor {
|
||||
return typeof v === "string" && (LABEL_COLORS as readonly string[]).includes(v);
|
||||
}
|
||||
|
||||
/** Pill: border + tinted background + readable text in both themes. */
|
||||
export const BADGE_CLASS: Record<LabelColor, string> = {
|
||||
gray: "border-zinc-500/30 bg-zinc-500/10 text-zinc-700 dark:text-zinc-300",
|
||||
red: "border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-300",
|
||||
orange: "border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-300",
|
||||
amber: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
|
||||
yellow: "border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300",
|
||||
lime: "border-lime-500/30 bg-lime-500/10 text-lime-700 dark:text-lime-300",
|
||||
green: "border-green-500/30 bg-green-500/10 text-green-700 dark:text-green-300",
|
||||
emerald: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
|
||||
teal: "border-teal-500/30 bg-teal-500/10 text-teal-700 dark:text-teal-300",
|
||||
cyan: "border-cyan-500/30 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300",
|
||||
sky: "border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",
|
||||
blue: "border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300",
|
||||
indigo: "border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300",
|
||||
violet: "border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",
|
||||
purple: "border-purple-500/30 bg-purple-500/10 text-purple-700 dark:text-purple-300",
|
||||
fuchsia: "border-fuchsia-500/30 bg-fuchsia-500/10 text-fuchsia-700 dark:text-fuchsia-300",
|
||||
pink: "border-pink-500/30 bg-pink-500/10 text-pink-700 dark:text-pink-300",
|
||||
rose: "border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300",
|
||||
};
|
||||
|
||||
export const DOT_CLASS: Record<LabelColor, string> = {
|
||||
gray: "bg-zinc-500",
|
||||
red: "bg-red-500",
|
||||
orange: "bg-orange-500",
|
||||
amber: "bg-amber-500",
|
||||
yellow: "bg-yellow-500",
|
||||
lime: "bg-lime-500",
|
||||
green: "bg-green-500",
|
||||
emerald: "bg-emerald-500",
|
||||
teal: "bg-teal-500",
|
||||
cyan: "bg-cyan-500",
|
||||
sky: "bg-sky-500",
|
||||
blue: "bg-blue-500",
|
||||
indigo: "bg-indigo-500",
|
||||
violet: "bg-violet-500",
|
||||
purple: "bg-purple-500",
|
||||
fuchsia: "bg-fuchsia-500",
|
||||
pink: "bg-pink-500",
|
||||
rose: "bg-rose-500",
|
||||
};
|
||||
|
||||
/** Colors used for tags that have no color set: picked from the name so they stay stable. */
|
||||
const AUTO_TAG_COLORS: LabelColor[] = ["sky", "emerald", "amber", "rose", "violet", "cyan", "lime", "orange", "fuchsia", "teal"];
|
||||
|
||||
export function autoTagColor(name: string): LabelColor {
|
||||
let h = 0;
|
||||
for (const ch of name.trim().toLowerCase()) h = (h * 31 + ch.codePointAt(0)!) >>> 0;
|
||||
return AUTO_TAG_COLORS[h % AUTO_TAG_COLORS.length];
|
||||
}
|
||||
+13
-1
@@ -107,6 +107,8 @@ export const tags = sqliteTable(
|
||||
name: text("name").notNull(),
|
||||
/** Lowercased, trimmed name; unique. */
|
||||
slug: text("slug").notNull(),
|
||||
/** One of LABEL_COLORS; null = automatic color derived from the name. */
|
||||
color: text("color"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("tags_slug_uq").on(t.slug)],
|
||||
@@ -183,7 +185,7 @@ export const modelFiles = sqliteTable(
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
|
||||
export type JobKind = (typeof JOB_KINDS)[number];
|
||||
|
||||
export const JOB_PURPOSES = ["initial", "repair", "update"] as const;
|
||||
export const JOB_PURPOSES = ["initial", "add", "repair", "update"] as const;
|
||||
export type JobPurpose = (typeof JOB_PURPOSES)[number];
|
||||
|
||||
export const JOB_STATES = [
|
||||
@@ -278,6 +280,16 @@ export const jobLogs = sqliteTable(
|
||||
(t) => [index("job_logs_job_idx").on(t.jobId, t.id)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// App settings (key/value, edited on the Settings page)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const settings = sqliteTable("settings", {
|
||||
key: text("key").primaryKey(),
|
||||
value: text("value", { mode: "json" }).notNull(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Worker liveness
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Group split files ("model-00001-of-00003.gguf", …) into one entry for display and selection.
|
||||
|
||||
const SPLIT = /^(.*)-(\d{5})-of-(\d{5})(\.[^./]+)$/;
|
||||
|
||||
export type SplitInfo = { base: string; part: number; total: number };
|
||||
|
||||
/** "BF16/X-BF16-00001-of-00002.gguf" → { base: "BF16/X-BF16.gguf", part: 1, total: 2 }. */
|
||||
export function splitInfo(path: string): SplitInfo | null {
|
||||
const m = path.match(SPLIT);
|
||||
if (!m) return null;
|
||||
return { base: `${m[1]}${m[4]}`, part: Number(m[2]), total: Number(m[3]) };
|
||||
}
|
||||
|
||||
export type FileGroup<T> = {
|
||||
/** Display path: the file itself, or the shared name of a split file without the part suffix. */
|
||||
path: string;
|
||||
/** Files in this entry, in part order. */
|
||||
parts: T[];
|
||||
size: number;
|
||||
/** Number of parts the split file has in total (1 for normal files). */
|
||||
totalParts: number;
|
||||
};
|
||||
|
||||
/** Merge split parts into one entry; other files stay as they are. Keeps first-seen order. */
|
||||
export function groupSplitFiles<T extends { path: string; size: number }>(files: T[]): FileGroup<T>[] {
|
||||
const groups: FileGroup<T>[] = [];
|
||||
const byBase = new Map<string, FileGroup<T>>();
|
||||
for (const f of files) {
|
||||
const info = splitInfo(f.path);
|
||||
if (!info) {
|
||||
groups.push({ path: f.path, parts: [f], size: f.size, totalParts: 1 });
|
||||
continue;
|
||||
}
|
||||
const key = `${info.base}#${info.total}`;
|
||||
let g = byBase.get(key);
|
||||
if (!g) {
|
||||
g = { path: info.base, parts: [], size: 0, totalParts: info.total };
|
||||
byBase.set(key, g);
|
||||
groups.push(g);
|
||||
}
|
||||
g.parts.push(f);
|
||||
g.size += f.size;
|
||||
}
|
||||
for (const g of groups) {
|
||||
if (g.parts.length > 1) g.parts.sort((a, b) => (splitInfo(a.path)?.part ?? 0) - (splitInfo(b.path)?.part ?? 0));
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export type JobFileEntry = { path: string; expectedBytes: number; doneBytes: number; failed: boolean; parts: number };
|
||||
|
||||
/** Job progress per entry: split parts summed into one line. */
|
||||
export function groupJobFiles(files: { path: string; expectedBytes: number; doneBytes: number; state: string }[]): JobFileEntry[] {
|
||||
return groupSplitFiles(files.map((f) => ({ ...f, size: f.expectedBytes }))).map((g) => ({
|
||||
path: g.path,
|
||||
expectedBytes: g.size,
|
||||
doneBytes: g.parts.reduce((s, p) => s + p.doneBytes, 0),
|
||||
failed: g.parts.some((p) => p.state === "failed"),
|
||||
parts: g.totalParts,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// What a file in a model repo is for, guessed from its path. Shared by UI and server.
|
||||
|
||||
import type { LabelColor } from "./colors";
|
||||
|
||||
export type FileRole =
|
||||
| "model"
|
||||
| "mtp"
|
||||
| "vision"
|
||||
| "draft"
|
||||
| "adapter"
|
||||
| "imatrix"
|
||||
| "config"
|
||||
| "tokenizer"
|
||||
| "template"
|
||||
| "docs"
|
||||
| "image"
|
||||
| "git"
|
||||
| "other";
|
||||
|
||||
/** Defaults; label and color can be changed in Settings. */
|
||||
export const FILE_ROLES: Record<FileRole, { label: string; color: LabelColor; description: string }> = {
|
||||
model: { label: "Model", color: "indigo", description: "Model weights" },
|
||||
mtp: { label: "MTP", color: "amber", description: "Multi-token prediction head (speculative decoding draft)" },
|
||||
vision: { label: "Vision", color: "fuchsia", description: "Multimodal projector (mmproj) for image input" },
|
||||
draft: { label: "Draft", color: "orange", description: "Draft model for speculative decoding" },
|
||||
adapter: { label: "Adapter", color: "violet", description: "LoRA / adapter weights" },
|
||||
imatrix: { label: "imatrix", color: "gray", description: "Importance matrix used to make the quants; not needed to run the model" },
|
||||
config: { label: "Config", color: "sky", description: "Model or generation config" },
|
||||
tokenizer: { label: "Tokenizer", color: "teal", description: "Tokenizer / vocabulary" },
|
||||
template: { label: "Template", color: "cyan", description: "Chat template" },
|
||||
docs: { label: "Docs", color: "gray", description: "Documentation or license" },
|
||||
image: { label: "Image", color: "pink", description: "Image (e.g. for the model card)" },
|
||||
git: { label: "Git", color: "gray", description: "Git metadata" },
|
||||
other: { label: "Other", color: "gray", description: "Other file" },
|
||||
};
|
||||
|
||||
export const FILE_ROLE_ORDER = Object.keys(FILE_ROLES) as FileRole[];
|
||||
|
||||
export type FileRoleStyle = { label: string; color: LabelColor };
|
||||
export type FileRoleStyles = Record<FileRole, FileRoleStyle>;
|
||||
|
||||
const WEIGHTS = /\.(gguf|safetensors|bin|pt|pth|ckpt|onnx|ggml|mlmodel|npz|h5)$/i;
|
||||
|
||||
export function fileRole(path: string): FileRole {
|
||||
const lower = path.toLowerCase();
|
||||
const name = lower.slice(lower.lastIndexOf("/") + 1);
|
||||
const dirs = lower.split("/").slice(0, -1);
|
||||
|
||||
if (name.startsWith(".git")) return "git";
|
||||
if (name.includes("imatrix")) return "imatrix";
|
||||
if (name.includes("mmproj") || dirs.includes("mmproj")) return "vision";
|
||||
if (name.startsWith("mtp-") || name.startsWith("mtp_") || dirs.includes("mtp")) return "mtp";
|
||||
if (WEIGHTS.test(name)) {
|
||||
if (name.includes("adapter")) return "adapter";
|
||||
if (/(^|[-_.])draft([-_.]|$)/.test(name)) return "draft";
|
||||
return "model";
|
||||
}
|
||||
if (/^tokenizer|^vocab|^merges\.txt$|^special_tokens_map\.json$|^added_tokens\.json$|\.tiktoken$|^tokenizer\.model$/.test(name)) {
|
||||
return "tokenizer";
|
||||
}
|
||||
if (name.endsWith(".jinja") || name.includes("chat_template") || name === "template") return "template";
|
||||
if (name.endsWith(".json") || name === "params" || name.endsWith(".yaml") || name.endsWith(".yml")) return "config";
|
||||
if (/\.(md|txt|rst)$/.test(name) || name.startsWith("license") || name.startsWith("notice")) return "docs";
|
||||
if (/\.(png|jpe?g|gif|webp|svg)$/.test(name)) return "image";
|
||||
return "other";
|
||||
}
|
||||
+5
-3
@@ -3,6 +3,7 @@ import { and, asc, desc, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { fileRole } from "@/lib/file-roles";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import type { Tag } from "@/lib/tags";
|
||||
|
||||
@@ -38,15 +39,16 @@ export async function listLibrary() {
|
||||
.select({ modelId: modelFiles.modelId, path: modelFiles.path })
|
||||
.from(modelFiles)
|
||||
.where(eq(modelFiles.selected, true));
|
||||
const quants = groupBy(selected, (f) => f.modelId, (f) => quantGroup(f.path));
|
||||
// Only model weights count as a quant (not MTP heads, mmproj or imatrix files).
|
||||
const quants = groupBy(selected, (f) => f.modelId, (f) => (fileRole(f.path) === "model" ? quantGroup(f.path) : null));
|
||||
|
||||
const tagRows = await d
|
||||
.select({ modelId: modelTags.modelId, id: tags.id, name: tags.name })
|
||||
.select({ modelId: modelTags.modelId, id: tags.id, name: tags.name, color: tags.color })
|
||||
.from(modelTags)
|
||||
.innerJoin(tags, eq(tags.id, modelTags.tagId))
|
||||
.orderBy(asc(tags.slug));
|
||||
const tagsByModel = new Map<string, Tag[]>();
|
||||
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name }]);
|
||||
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
|
||||
|
||||
return rows.map((r) => ({
|
||||
...r,
|
||||
|
||||
+41
-3
@@ -1,16 +1,17 @@
|
||||
import "server-only";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { isSelected, type SelectionRule } from "@/lib/selection";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
|
||||
import { deleteUnusedTags } from "@/lib/tags";
|
||||
|
||||
export class ModelError extends Error {
|
||||
constructor(
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable",
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -107,3 +108,40 @@ function chunk<T>(items: T[], size: number): T[][] {
|
||||
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add files to a model's selection and queue a download. The paths are added to the selection
|
||||
* rule as exact includes; exclude patterns that would block one of them are dropped, then the
|
||||
* rule is re-applied to the whole file list so `selected` always matches the stored rule.
|
||||
*/
|
||||
export async function addFilesToModel(modelId: string, paths: string[]): Promise<{ jobId: string; added: number }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
|
||||
const open = await d.query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", "downloading", "verifying"])),
|
||||
});
|
||||
if (open) throw new ModelError("busy", "A download for this model is still queued or running. Add files when it has finished.", 409);
|
||||
|
||||
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
|
||||
const known = new Map(files.map((f) => [f.path, f]));
|
||||
const wanted = [...new Set(paths)].filter((p) => known.has(p) && !known.get(p)!.selected);
|
||||
if (wanted.length === 0) throw new ModelError("empty_selection", "No new files selected.", 400);
|
||||
|
||||
const rule: SelectionRule = {
|
||||
include: [...model.includePatterns, ...wanted.map(escapeGlob)],
|
||||
exclude: model.excludePatterns.filter((p) => !wanted.some((path) => matchesAny(path, [p]))),
|
||||
};
|
||||
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
|
||||
|
||||
await d.batch([
|
||||
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude }).where(eq(models.id, modelId)),
|
||||
...changed.map((f) =>
|
||||
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
|
||||
),
|
||||
]);
|
||||
const { jobId } = await queueDownload(modelId, "add");
|
||||
return { jobId, added: changed.filter((f) => !f.selected).length };
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { groupSplitFiles, splitInfo } from "./file-groups";
|
||||
import { fileRole } from "./file-roles";
|
||||
import { modelFamilies, parseRepoMetadata } from "./hub/metadata";
|
||||
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, type SearchableModel } from "./search";
|
||||
|
||||
@@ -89,3 +91,60 @@ describe("filters and facet counts", () => {
|
||||
assert.deepEqual(facetCounts(models, "family", "", f), [["google", 1], ["Qwen", 1]]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("fileRole", () => {
|
||||
it("classifies typical GGUF repo files", () => {
|
||||
const cases: [string, string][] = [
|
||||
["Qwen3.8-27B-UD-Q4_K_M.gguf", "model"],
|
||||
["Q4_K_M/Qwen3-235B-A22B-Q4_K_M-00001-of-00003.gguf", "model"],
|
||||
["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "mtp"],
|
||||
["mmproj-BF16.gguf", "vision"],
|
||||
["mmproj-model-f16.gguf", "vision"],
|
||||
["imatrix_unsloth.gguf", "imatrix"],
|
||||
["imatrix_unsloth.dat", "imatrix"],
|
||||
["Qwen_Qwen3-8B.imatrix", "imatrix"],
|
||||
["config.json", "config"],
|
||||
["generation_config.json", "config"],
|
||||
["params", "config"],
|
||||
["tokenizer.json", "tokenizer"],
|
||||
["tokenizer_config.json", "tokenizer"],
|
||||
["merges.txt", "tokenizer"],
|
||||
["chat_template.jinja", "template"],
|
||||
["template", "template"],
|
||||
["README.md", "docs"],
|
||||
["LICENSE", "docs"],
|
||||
[".gitattributes", "git"],
|
||||
["model-00001-of-00004.safetensors", "model"],
|
||||
["adapter_model.safetensors", "adapter"],
|
||||
["images/banner.png", "image"],
|
||||
];
|
||||
for (const [path, role] of cases) assert.equal(fileRole(path), role, path);
|
||||
});
|
||||
});
|
||||
|
||||
describe("groupSplitFiles", () => {
|
||||
it("merges split parts into one entry and leaves other files alone", () => {
|
||||
const files = [
|
||||
{ path: ".gitattributes", size: 1 },
|
||||
{ path: "BF16/Qwen3.8-27B-BF16-00002-of-00002.gguf", size: 20 },
|
||||
{ path: "BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf", size: 50 },
|
||||
{ path: "Qwen3.8-27B-Q4_0.gguf", size: 16 },
|
||||
];
|
||||
const groups = groupSplitFiles(files);
|
||||
assert.deepEqual(
|
||||
groups.map((g) => [g.path, g.size, g.totalParts, g.parts.map((p) => p.path.slice(-18))]),
|
||||
[
|
||||
[".gitattributes", 1, 1, [".gitattributes"]],
|
||||
["BF16/Qwen3.8-27B-BF16.gguf", 70, 2, ["00001-of-00002.gguf", "00002-of-00002.gguf"].map((s) => s.slice(-18))],
|
||||
["Qwen3.8-27B-Q4_0.gguf", 16, 1, ["Qwen3.8-27B-Q4_0.gguf".slice(-18)]],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("parses part numbers", () => {
|
||||
assert.deepEqual(splitInfo("Q4_K_M/X-Q4_K_M-00003-of-00010.gguf"), { base: "Q4_K_M/X-Q4_K_M.gguf", part: 3, total: 10 });
|
||||
assert.equal(splitInfo("model-00001-of-00004.safetensors")?.base, "model.safetensors");
|
||||
assert.equal(splitInfo("Qwen3-8B-Q4_K_M.gguf"), null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import "server-only";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { settings } from "@/lib/db/schema";
|
||||
import { isLabelColor } from "@/lib/colors";
|
||||
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
|
||||
|
||||
const FILE_ROLES_KEY = "labels.fileRoles";
|
||||
export const FILE_ROLE_LABEL_MAX = 24;
|
||||
|
||||
type StoredRoles = Partial<Record<FileRole, { label?: string; color?: string }>>;
|
||||
|
||||
async function read<T>(key: string): Promise<T | null> {
|
||||
try {
|
||||
const row = await db().query.settings.findFirst({ where: eq(settings.key, key) });
|
||||
return (row?.value as T) ?? null;
|
||||
} catch {
|
||||
return null; // table missing before the first migration
|
||||
}
|
||||
}
|
||||
|
||||
async function write(key: string, value: unknown) {
|
||||
await db()
|
||||
.insert(settings)
|
||||
.values({ key, value })
|
||||
.onConflictDoUpdate({ target: settings.key, set: { value, updatedAt: new Date() } });
|
||||
}
|
||||
|
||||
/** Label text and color per file role: defaults merged with what was saved in Settings. */
|
||||
export async function getFileRoleStyles(): Promise<FileRoleStyles> {
|
||||
const stored = (await read<StoredRoles>(FILE_ROLES_KEY)) ?? {};
|
||||
const out = {} as FileRoleStyles;
|
||||
for (const role of FILE_ROLE_ORDER) {
|
||||
const s = stored[role] ?? {};
|
||||
out[role] = {
|
||||
label: typeof s.label === "string" && s.label.trim() ? s.label.trim() : FILE_ROLES[role].label,
|
||||
color: isLabelColor(s.color) ? s.color : FILE_ROLES[role].color,
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export class SettingsError extends Error {
|
||||
status = 400;
|
||||
code = "invalid";
|
||||
}
|
||||
|
||||
/** Save label/color overrides. Values equal to the default are not stored. */
|
||||
export async function saveFileRoleStyles(input: Record<string, { label?: unknown; color?: unknown }>): Promise<FileRoleStyles> {
|
||||
const stored: StoredRoles = {};
|
||||
for (const [role, v] of Object.entries(input)) {
|
||||
if (!(role in FILE_ROLES)) throw new SettingsError(`Unknown file label "${role}".`);
|
||||
const def = FILE_ROLES[role as FileRole];
|
||||
const entry: { label?: string; color?: string } = {};
|
||||
if (v.label !== undefined) {
|
||||
if (typeof v.label !== "string" || !v.label.trim() || v.label.trim().length > FILE_ROLE_LABEL_MAX) {
|
||||
throw new SettingsError(`Label for "${role}" must be 1–${FILE_ROLE_LABEL_MAX} characters.`);
|
||||
}
|
||||
if (v.label.trim() !== def.label) entry.label = v.label.trim();
|
||||
}
|
||||
if (v.color !== undefined) {
|
||||
if (!isLabelColor(v.color)) throw new SettingsError(`Unknown color "${String(v.color)}".`);
|
||||
if (v.color !== def.color) entry.color = v.color;
|
||||
}
|
||||
if (entry.label || entry.color) stored[role as FileRole] = entry;
|
||||
}
|
||||
await write(FILE_ROLES_KEY, stored);
|
||||
return getFileRoleStyles();
|
||||
}
|
||||
+32
-4
@@ -2,6 +2,7 @@ import "server-only";
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { isLabelColor } from "@/lib/colors";
|
||||
import { modelTags, models, tags } from "@/lib/db/schema";
|
||||
|
||||
export const TAG_MAX_LENGTH = 40;
|
||||
@@ -16,7 +17,7 @@ export class TagError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type Tag = { id: string; name: string };
|
||||
export type Tag = { id: string; name: string; color: string | null };
|
||||
|
||||
/** Trim and collapse whitespace; the slug (lowercase) decides uniqueness. */
|
||||
export function normalizeTagName(raw: string): { name: string; slug: string } {
|
||||
@@ -29,7 +30,7 @@ export function normalizeTagName(raw: string): { name: string; slug: string } {
|
||||
/** All tags with how many models use them (for autocomplete). */
|
||||
export async function listTags(): Promise<(Tag & { count: number })[]> {
|
||||
return db()
|
||||
.select({ id: tags.id, name: tags.name, count: sql<number>`count(${modelTags.modelId})` })
|
||||
.select({ id: tags.id, name: tags.name, color: tags.color, count: sql<number>`count(${modelTags.modelId})` })
|
||||
.from(tags)
|
||||
.leftJoin(modelTags, eq(modelTags.tagId, tags.id))
|
||||
.groupBy(tags.id)
|
||||
@@ -38,7 +39,7 @@ export async function listTags(): Promise<(Tag & { count: number })[]> {
|
||||
|
||||
export async function modelTagList(modelId: string): Promise<Tag[]> {
|
||||
return db()
|
||||
.select({ id: tags.id, name: tags.name })
|
||||
.select({ id: tags.id, name: tags.name, color: tags.color })
|
||||
.from(modelTags)
|
||||
.innerJoin(tags, eq(tags.id, modelTags.tagId))
|
||||
.where(eq(modelTags.modelId, modelId))
|
||||
@@ -53,7 +54,7 @@ export async function addTag(modelId: string, rawName: string): Promise<Tag> {
|
||||
if (!model) throw new TagError("not_found", "Model not found.", 404);
|
||||
|
||||
await d.insert(tags).values({ id: ulid(), name, slug }).onConflictDoNothing({ target: tags.slug });
|
||||
const tag = await d.query.tags.findFirst({ columns: { id: true, name: true }, where: eq(tags.slug, slug) });
|
||||
const tag = await d.query.tags.findFirst({ columns: { id: true, name: true, color: true }, where: eq(tags.slug, slug) });
|
||||
if (!tag) throw new Error("tag vanished after insert");
|
||||
await d.insert(modelTags).values({ modelId, tagId: tag.id }).onConflictDoNothing();
|
||||
return tag;
|
||||
@@ -69,3 +70,30 @@ export async function removeTag(modelId: string, tagId: string): Promise<void> {
|
||||
export async function deleteUnusedTags(): Promise<void> {
|
||||
await db().run(sql`delete from ${tags} where ${tags.id} not in (select ${modelTags.tagId} from ${modelTags})`);
|
||||
}
|
||||
|
||||
/** Rename a tag and/or set its color (null = automatic). */
|
||||
export async function updateTag(id: string, input: { name?: string; color?: string | null }): Promise<Tag> {
|
||||
const d = db();
|
||||
const tag = await d.query.tags.findFirst({ where: eq(tags.id, id) });
|
||||
if (!tag) throw new TagError("not_found", "Tag not found.", 404);
|
||||
const set: { name?: string; slug?: string; color?: string | null } = {};
|
||||
if (input.name !== undefined) {
|
||||
const { name, slug } = normalizeTagName(input.name);
|
||||
const clash = await d.query.tags.findFirst({ columns: { id: true }, where: eq(tags.slug, slug) });
|
||||
if (clash && clash.id !== id) throw new TagError("invalid", `A tag named "${name}" already exists.`, 409);
|
||||
Object.assign(set, { name, slug });
|
||||
}
|
||||
if (input.color !== undefined) {
|
||||
if (input.color !== null && !isLabelColor(input.color)) throw new TagError("invalid", "Unknown color.", 400);
|
||||
set.color = input.color;
|
||||
}
|
||||
if (Object.keys(set).length > 0) await d.update(tags).set(set).where(eq(tags.id, id));
|
||||
const updated = await d.query.tags.findFirst({ columns: { id: true, name: true, color: true }, where: eq(tags.id, id) });
|
||||
return updated!;
|
||||
}
|
||||
|
||||
/** Delete a tag and remove it from all models. */
|
||||
export async function deleteTag(id: string): Promise<void> {
|
||||
const d = db();
|
||||
await d.batch([d.delete(modelTags).where(eq(modelTags.tagId, id)), d.delete(tags).where(eq(tags.id, id))]);
|
||||
}
|
||||
Reference in new issue
Block a user