feat: add tabbed Settings, 10 themes with custom accent/text color pickers, main project directory selector, and export filename/directory controls

This commit is contained in:
Schwitzz
2026-10-30 14:06:46 -05:00
parent fa22a755ee
commit 1d209fedd2
8 changed files with 1660 additions and 648 deletions
+109 -1
View File
@@ -373,6 +373,7 @@ export const api = {
port: number; port: number;
activePort?: number; activePort?: number;
startOnBoot: boolean; startOnBoot: boolean;
projectDirectory?: string;
}> => { }> => {
const endpoints = [ const endpoints = [
"/api/system/server-config", "/api/system/server-config",
@@ -388,6 +389,7 @@ export const api = {
port: number; port: number;
activePort?: number; activePort?: number;
startOnBoot: boolean; startOnBoot: boolean;
projectDirectory?: string;
}; };
return { return {
online: true, online: true,
@@ -395,6 +397,7 @@ export const api = {
port: data.port, port: data.port,
...(data.activePort !== undefined ? { activePort: data.activePort } : {}), ...(data.activePort !== undefined ? { activePort: data.activePort } : {}),
startOnBoot: data.startOnBoot, startOnBoot: data.startOnBoot,
...(data.projectDirectory ? { projectDirectory: data.projectDirectory } : {}),
}; };
} }
} catch { } catch {
@@ -410,7 +413,12 @@ export const api = {
}, },
updateServerConfig: async ( updateServerConfig: async (
patch: { enabled?: boolean; port?: number; startOnBoot?: boolean }, patch: {
enabled?: boolean;
port?: number;
startOnBoot?: boolean;
projectDirectory?: string;
},
portHint?: number, portHint?: number,
): Promise<{ ): Promise<{
online: boolean; online: boolean;
@@ -418,6 +426,7 @@ export const api = {
port: number; port: number;
activePort?: number; activePort?: number;
startOnBoot: boolean; startOnBoot: boolean;
projectDirectory?: string;
}> => { }> => {
const endpoints = [ const endpoints = [
"/api/system/server-config", "/api/system/server-config",
@@ -438,6 +447,7 @@ export const api = {
port: number; port: number;
activePort?: number; activePort?: number;
startOnBoot: boolean; startOnBoot: boolean;
projectDirectory?: string;
}; };
return { return {
online: true, online: true,
@@ -445,6 +455,7 @@ export const api = {
port: data.port, port: data.port,
...(data.activePort !== undefined ? { activePort: data.activePort } : {}), ...(data.activePort !== undefined ? { activePort: data.activePort } : {}),
startOnBoot: data.startOnBoot, startOnBoot: data.startOnBoot,
...(data.projectDirectory ? { projectDirectory: data.projectDirectory } : {}),
}; };
} }
} catch { } catch {
@@ -456,6 +467,103 @@ export const api = {
enabled: patch.enabled ?? true, enabled: patch.enabled ?? true,
port: patch.port ?? portHint ?? 8081, port: patch.port ?? portHint ?? 8081,
startOnBoot: patch.startOnBoot ?? false, startOnBoot: patch.startOnBoot ?? false,
...(patch.projectDirectory ? { projectDirectory: patch.projectDirectory } : {}),
}; };
}, },
listSystemDirectories: async (
dirPath?: string,
portHint?: number,
): Promise<{
online: boolean;
currentPath: string;
parentPath: string | null;
homePath: string;
directories: { name: string; path: string }[];
}> => {
const query = dirPath ? `?path=${encodeURIComponent(dirPath)}` : "";
const endpoints = [
`/api/system/list-dirs${query}`,
...(portHint ? [`http://localhost:${portHint}/api/system/list-dirs${query}`] : []),
];
for (const url of endpoints) {
try {
const res = await fetch(url, { credentials: "include" });
const ct = res.headers.get("content-type") ?? "";
if (res.ok && ct.includes("application/json")) {
const data = (await res.json()) as {
currentPath: string;
parentPath: string | null;
homePath: string;
directories: { name: string; path: string }[];
};
return {
online: true,
currentPath: data.currentPath,
parentPath: data.parentPath,
homePath: data.homePath,
directories: data.directories,
};
}
} catch {
/* try next */
}
}
return {
online: false,
currentPath: dirPath || "~/Documents/PubScript",
parentPath: null,
homePath: "~",
directories: [],
};
},
saveExportToDirectory: async (
params: {
directory: string;
fileName: string;
data: Uint8Array | string;
},
portHint?: number,
): Promise<{ savedOnServer: boolean; savedPath?: string }> => {
const bytes =
typeof params.data === "string"
? new TextEncoder().encode(params.data)
: params.data;
let binary = "";
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
const base64Data = btoa(binary);
const endpoints = [
"/api/system/save-export",
...(portHint ? [`http://localhost:${portHint}/api/system/save-export`] : []),
];
for (const url of endpoints) {
try {
const res = await fetch(url, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
directory: params.directory,
fileName: params.fileName,
base64Data,
}),
});
const ct = res.headers.get("content-type") ?? "";
if (res.ok && ct.includes("application/json")) {
const out = (await res.json()) as { ok?: boolean; savedPath?: string };
if (out.ok && out.savedPath) {
return { savedOnServer: true, savedPath: out.savedPath };
}
}
} catch {
/* try next */
}
}
return { savedOnServer: false };
},
}; };
@@ -0,0 +1,173 @@
import { useEffect, useState } from "react";
import { Modal, Button } from "@pubscript/ui";
import { api } from "../api.js";
import { useSettings } from "../store/settings.js";
export interface DirectoryBrowserModalProps {
open: boolean;
initialPath: string;
title?: string;
onSelect: (selectedPath: string) => void;
onClose: () => void;
}
export function DirectoryBrowserModal({
open,
initialPath,
title = "Select Directory",
onSelect,
onClose,
}: DirectoryBrowserModalProps) {
const serverPort = useSettings((s) => s.serverPort);
const [currentPath, setCurrentPath] = useState<string>(initialPath || "~/Documents/PubScript");
const [parentPath, setParentPath] = useState<string | null>(null);
const [homePath, setHomePath] = useState<string>("~");
const [directories, setDirectories] = useState<{ name: string; path: string }[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const loadPath = async (targetPath: string) => {
setLoading(true);
try {
const res = await api.listSystemDirectories(targetPath, serverPort);
setCurrentPath(res.currentPath);
setParentPath(res.parentPath);
setHomePath(res.homePath);
setDirectories(res.directories);
} finally {
setLoading(false);
}
};
useEffect(() => {
if (!open) return;
void loadPath(initialPath || "~/Documents/PubScript");
}, [open, initialPath]);
return (
<Modal
title={title}
open={open}
onClose={onClose}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button
variant="primary"
onClick={() => {
onSelect(currentPath.trim() || "~/Documents/PubScript");
onClose();
}}
>
Select This Folder
</Button>
</>
}
>
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
<div style={{ display: "flex", gap: 6, alignItems: "center" }}>
<input
type="text"
className="ps-input"
style={{ flex: 1, fontFamily: "var(--ps-font-mono)", fontSize: 12.5 }}
value={currentPath}
onChange={(e) => setCurrentPath(e.target.value)}
placeholder="/path/to/directory"
/>
<Button
variant="secondary"
size="sm"
onClick={() => void loadPath(currentPath)}
disabled={loading}
>
Go
</Button>
</div>
<div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
{parentPath && (
<Button
variant="secondary"
size="sm"
onClick={() => void loadPath(parentPath)}
disabled={loading}
>
⬆ Parent Folder
</Button>
)}
<Button
variant="secondary"
size="sm"
onClick={() => void loadPath(homePath || "~")}
disabled={loading}
>
🏠 Home
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => void loadPath("~/Documents")}
disabled={loading}
>
📄 Documents
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => void loadPath("~/Documents/PubScript")}
disabled={loading}
>
📚 PubScript
</Button>
</div>
<div
style={{
maxHeight: 260,
overflowY: "auto",
border: "1px solid var(--ps-border)",
borderRadius: 8,
background: "var(--ps-bg)",
padding: 6,
}}
>
{loading ? (
<div style={{ padding: 14, fontSize: 12.5, color: "var(--ps-text-muted)" }}>
Loading folders…
</div>
) : directories.length === 0 ? (
<div style={{ padding: 14, fontSize: 12.5, color: "var(--ps-text-muted)" }}>
No subfolders in this directory (you can click &ldquo;Select This Folder&rdquo; or enter any path above).
</div>
) : (
directories.map((dir) => (
<button
key={dir.path}
type="button"
onClick={() => void loadPath(dir.path)}
style={{
display: "flex",
alignItems: "center",
gap: 8,
width: "100%",
textAlign: "left",
padding: "7px 10px",
border: "none",
borderRadius: 6,
background: "transparent",
color: "var(--ps-text)",
cursor: "pointer",
fontSize: 13,
}}
>
<span>📁</span>
<span style={{ fontWeight: 500 }}>{dir.name}</span>
</button>
))
)}
</div>
</div>
</Modal>
);
}
File diff suppressed because it is too large Load Diff
+195 -104
View File
@@ -1,11 +1,10 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Modal, Button } from "@pubscript/ui"; import { Modal, Button, toast } from "@pubscript/ui";
import { import { exportProjectData, type ExportFormat } from "@pubscript/exporters";
THEMES,
exportProjectData,
type ExportFormat,
} from "@pubscript/exporters";
import { useProjectStore } from "../../store/project-store.js"; import { useProjectStore } from "../../store/project-store.js";
import { useSettings } from "../../store/settings.js";
import { api } from "../../api.js";
import { DirectoryBrowserModal } from "../../components/DirectoryBrowserModal.js";
import { buildExportProject } from "./buildExportProject.js"; import { buildExportProject } from "./buildExportProject.js";
import { downloadFile } from "./download.js"; import { downloadFile } from "./download.js";
import { EXPORT_FORMATS, type FormatInfo } from "./formats.js"; import { EXPORT_FORMATS, type FormatInfo } from "./formats.js";
@@ -19,27 +18,65 @@ type Scope = "project" | "chapter";
/** Collapse a string into a filesystem-safe slug. */ /** Collapse a string into a filesystem-safe slug. */
function slug(value: string): string { function slug(value: string): string {
return value return (
.trim() value
.replace(/[^\w-]+/g, "-") .trim()
.replace(/-+/g, "-") .toLowerCase()
.replace(/^-+|-+$/g, "") .replace(/[^\w-]+/g, "-")
.slice(0, 60) || "project"; .replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60) || "manuscript"
);
} }
export function ExportDialog({ open, onClose }: ExportDialogProps) { export function ExportDialog({ open, onClose }: ExportDialogProps) {
const adapter = useProjectStore((s) => s.adapter); const adapter = useProjectStore((s) => s.adapter);
const projectId = useProjectStore((s) => s.project?.projectId); const project = useProjectStore((s) => s.project);
const projectId = project?.id;
const chapters = useProjectStore((s) => s.chapters); const chapters = useProjectStore((s) => s.chapters);
const [format, setFormat] = useState<ExportFormat>("markdown"); const projectDirectory = useSettings((s) => s.projectDirectory);
const [themeId, setThemeId] = useState("ink"); const serverPort = useSettings((s) => s.serverPort);
const [format, setFormat] = useState<ExportFormat>("epub");
const [scope, setScope] = useState<Scope>("project"); const [scope, setScope] = useState<Scope>("project");
const [chapterId, setChapterId] = useState<string>(""); const [chapterId, setChapterId] = useState<string>("");
const [fileName, setFileName] = useState<string>("");
const [saveDir, setSaveDir] = useState<string>(projectDirectory || "~/Documents/PubScript");
const [browseOpen, setBrowseOpen] = useState<boolean>(false);
const [books, setBooks] = useState<{ id: string; title: string }[]>([]); const [books, setBooks] = useState<{ id: string; title: string }[]>([]);
const [exporting, setExporting] = useState(false); const [exporting, setExporting] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const formatInfo: FormatInfo | undefined = useMemo(
() => EXPORT_FORMATS.find((f) => f.id === format),
[format],
);
// Initialize default fileName and saveDir when dialog opens
useEffect(() => {
if (!open) return;
const ext = formatInfo?.extension ?? "epub";
const base = slug(project?.title || "manuscript");
setFileName(`${base}.${ext}`);
setSaveDir(projectDirectory || "~/Documents/PubScript");
setError(null);
}, [open, project?.title, projectDirectory]);
// Update file extension when conversion format changes
const handleFormatChange = (nextFormat: ExportFormat) => {
setFormat(nextFormat);
const nextExt = EXPORT_FORMATS.find((f) => f.id === nextFormat)?.extension ?? "bin";
setFileName((prev) => {
const trimmed = prev.trim();
if (!trimmed) {
return `${slug(project?.title || "manuscript")}.${nextExt}`;
}
const withoutExt = trimmed.replace(/\.[a-z0-9]+$/i, "");
return `${withoutExt}.${nextExt}`;
});
};
// Populate the book/chapter selectors when the dialog opens. // Populate the book/chapter selectors when the dialog opens.
useEffect(() => { useEffect(() => {
if (!open || !adapter || !projectId) return; if (!open || !adapter || !projectId) return;
@@ -48,7 +85,6 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
const allBooks = await adapter.listBooks(projectId); const allBooks = await adapter.listBooks(projectId);
if (!active) return; if (!active) return;
setBooks(allBooks); setBooks(allBooks);
// Resolve the first chapter across books so the selector has a default.
let firstChapterId = ""; let firstChapterId = "";
for (const book of allBooks) { for (const book of allBooks) {
const cs = await adapter.listChapters(book.id); const cs = await adapter.listChapters(book.id);
@@ -69,30 +105,48 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
const chapterOptions = useMemo(() => { const chapterOptions = useMemo(() => {
const byBook = new Map<string, { id: string; title: string }[]>(); const byBook = new Map<string, { id: string; title: string }[]>();
for (const book of books) { for (const book of books) {
byBook.set(book.id, chapters.filter((c) => c.bookId === book.id)); byBook.set(
book.id,
chapters.filter((c) => c.bookId === book.id),
);
} }
return byBook; return byBook;
}, [books, chapters]); }, [books, chapters]);
const formatInfo: FormatInfo | undefined = useMemo(
() => EXPORT_FORMATS.find((f) => f.id === format),
[format]
);
const handleExport = async () => { const handleExport = async () => {
if (!adapter || !projectId) return; if (!adapter || !projectId) return;
setExporting(true); setExporting(true);
setError(null); setError(null);
try { try {
const project = await buildExportProject(adapter, projectId); const exportProj = await buildExportProject(adapter, projectId);
const options: Parameters<typeof exportProjectData>[2] = { const options: Parameters<typeof exportProjectData>[2] = {
scope: scope === "chapter" ? "chapter" : "project", scope: scope === "chapter" ? "chapter" : "project",
theme: themeId,
}; };
if (scope === "chapter") options.scopeId = chapterId; if (scope === "chapter") options.scopeId = chapterId;
const data = await exportProjectData(project, format, options); const data = await exportProjectData(exportProj, format, options);
const ext = formatInfo?.extension ?? "bin"; const ext = formatInfo?.extension ?? "bin";
downloadFile(`${slug(projectId)}.${ext}`, data, formatInfo?.mime ?? "application/octet-stream"); const rawName = fileName.trim() || `${slug(project?.title || "manuscript")}.${ext}`;
const finalFileName = rawName.includes(".") ? rawName : `${rawName}.${ext}`;
const saved = await api.saveExportToDirectory(
{
directory: saveDir.trim() || projectDirectory || "~/Documents/PubScript",
fileName: finalFileName,
data,
},
serverPort,
);
if (saved.savedOnServer && saved.savedPath) {
toast.success(`Exported to ${saved.savedPath}`);
} else {
downloadFile(
finalFileName,
data,
formatInfo?.mime ?? "application/octet-stream",
);
toast.success(`Downloaded ${finalFileName}`);
}
onClose(); onClose();
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : String(err)); setError(err instanceof Error ? err.message : String(err));
@@ -102,89 +156,126 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
}; };
return ( return (
<Modal <>
title="Export project" <Modal
open={open} title="Export Manuscript"
onClose={onClose} open={open}
footer={ onClose={onClose}
<> footer={
<Button variant="ghost" onClick={onClose} disabled={exporting}> <>
Cancel <Button variant="ghost" onClick={onClose} disabled={exporting}>
</Button> Cancel
<Button onClick={handleExport} disabled={exporting || !formatInfo}> </Button>
{exporting ? "Exporting…" : "Export"} <Button
</Button> variant="primary"
</> onClick={() => void handleExport()}
} disabled={exporting || !formatInfo}
> >
<div className="ps-export-grid"> {exporting ? "Exporting…" : "Export"}
<label className="ps-export-field"> </Button>
<span>Format</span> </>
<select }
className="ps-select" >
value={format} <div className="ps-export-grid" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
onChange={(e) => setFormat(e.target.value as ExportFormat)} <label className="ps-export-field" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
disabled={exporting} <span style={{ fontSize: 12.5, fontWeight: 600 }}>File Type / Conversion Format</span>
>
{EXPORT_FORMATS.map((f) => (
<option key={f.id} value={f.id}>
{f.label}
</option>
))}
</select>
</label>
<label className="ps-export-field">
<span>Theme</span>
<select
className="ps-select"
value={themeId}
onChange={(e) => setThemeId(e.target.value)}
disabled={exporting}
>
{Object.entries(THEMES).map(([id, t]) => (
<option key={id} value={id}>
{t.name}
</option>
))}
</select>
</label>
<label className="ps-export-field">
<span>Scope</span>
<select
className="ps-select"
value={scope}
onChange={(e) => setScope(e.target.value as Scope)}
disabled={exporting}
>
<option value="project">Entire book</option>
<option value="chapter">Selected chapter</option>
</select>
</label>
{scope === "chapter" && (
<label className="ps-export-field">
<span>Chapter</span>
<select <select
className="ps-select" className="ps-select"
value={chapterId} value={format}
onChange={(e) => setChapterId(e.target.value)} onChange={(e) => handleFormatChange(e.target.value as ExportFormat)}
disabled={exporting || chapterOptions.size === 0} disabled={exporting}
> >
{Array.from(chapterOptions.values()).flatMap((cs) => {EXPORT_FORMATS.map((f) => (
cs.map((c) => ( <option key={f.id} value={f.id}>
<option key={c.id} value={c.id}> {f.label} (.{f.extension})
{c.title} </option>
</option> ))}
))
)}
</select> </select>
</label> </label>
)}
</div>
{error && <p className="ps-export-error" role="alert">{error}</p>} <label className="ps-export-field" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
</Modal> <span style={{ fontSize: 12.5, fontWeight: 600 }}>Scope</span>
<select
className="ps-select"
value={scope}
onChange={(e) => setScope(e.target.value as Scope)}
disabled={exporting}
>
<option value="project">Entire book</option>
<option value="chapter">Selected chapter</option>
</select>
</label>
{scope === "chapter" && (
<label className="ps-export-field" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
<span style={{ fontSize: 12.5, fontWeight: 600 }}>Chapter</span>
<select
className="ps-select"
value={chapterId}
onChange={(e) => setChapterId(e.target.value)}
disabled={exporting || chapterOptions.size === 0}
>
{Array.from(chapterOptions.values()).flatMap((cs) =>
cs.map((c) => (
<option key={c.id} value={c.id}>
{c.title}
</option>
)),
)}
</select>
</label>
)}
<label className="ps-export-field" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
<span style={{ fontSize: 12.5, fontWeight: 600 }}>Exported File Name</span>
<input
type="text"
className="ps-input"
value={fileName}
onChange={(e) => setFileName(e.target.value)}
placeholder={`manuscript.${formatInfo?.extension ?? "epub"}`}
disabled={exporting}
/>
</label>
<div className="ps-export-field" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
<span style={{ fontSize: 12.5, fontWeight: 600 }}>Save Directory</span>
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<input
type="text"
className="ps-input"
style={{ flex: 1, fontFamily: "var(--ps-font-mono)", fontSize: 12.5 }}
value={saveDir}
onChange={(e) => setSaveDir(e.target.value)}
placeholder="~/Documents/PubScript"
disabled={exporting}
/>
<Button
variant="secondary"
size="sm"
onClick={() => setBrowseOpen(true)}
disabled={exporting}
>
📁 Browse…
</Button>
</div>
</div>
</div>
{error && (
<p className="ps-export-error" role="alert" style={{ color: "var(--ps-danger)", marginTop: 10 }}>
{error}
</p>
)}
</Modal>
<DirectoryBrowserModal
open={browseOpen}
initialPath={saveDir}
title="Choose Export Save Directory"
onSelect={(dir) => setSaveDir(dir)}
onClose={() => setBrowseOpen(false)}
/>
</>
); );
} }
+24 -2
View File
@@ -1,5 +1,12 @@
import { create } from "zustand"; import { create } from "zustand";
import { applyDensity, applyFontSettings, applyTheme, type ThemeId } from "@pubscript/ui"; import {
applyColorOverrides,
applyDensity,
applyFontSettings,
applyTheme,
THEME_TOKENS,
type ThemeId,
} from "@pubscript/ui";
import { discoverLocalProviders, type ProviderKind, type ThinkingEffort } from "@pubscript/ai"; import { discoverLocalProviders, type ProviderKind, type ThinkingEffort } from "@pubscript/ai";
import { createUlid } from "@pubscript/core"; import { createUlid } from "@pubscript/core";
@@ -238,6 +245,7 @@ export const DEFAULT_AI_AGENTS: AIAgentConfig[] = [
export interface AppSettings { export interface AppSettings {
theme: ThemeId; theme: ThemeId;
accentColor: string; accentColor: string;
textColor: string;
density: Density; density: Density;
fontFamily: FontFamily; fontFamily: FontFamily;
fontSize: number; fontSize: number;
@@ -247,6 +255,7 @@ export interface AppSettings {
wordCountGoal: number; wordCountGoal: number;
autoSave: boolean; autoSave: boolean;
focusMode: boolean; focusMode: boolean;
projectDirectory: string;
// Navigation & AI Sidebars // Navigation & AI Sidebars
navCollapsed: boolean; navCollapsed: boolean;
aiSidebarOpen: boolean; aiSidebarOpen: boolean;
@@ -272,6 +281,7 @@ export interface AppSettings {
export const DEFAULT_SETTINGS: AppSettings = { export const DEFAULT_SETTINGS: AppSettings = {
theme: "ink", theme: "ink",
accentColor: "#7c8bf5", accentColor: "#7c8bf5",
textColor: "",
density: "comfortable", density: "comfortable",
fontFamily: "serif", fontFamily: "serif",
fontSize: 16, fontSize: 16,
@@ -281,6 +291,7 @@ export const DEFAULT_SETTINGS: AppSettings = {
wordCountGoal: 80_000, wordCountGoal: 80_000,
autoSave: true, autoSave: true,
focusMode: false, focusMode: false,
projectDirectory: "~/Documents/PubScript",
navCollapsed: false, navCollapsed: false,
aiSidebarOpen: false, aiSidebarOpen: false,
aiSidebarWidth: 370, aiSidebarWidth: 370,
@@ -351,6 +362,10 @@ export interface SettingsStore extends AppSettings {
export const useSettings = create<SettingsStore>((set, get) => { export const useSettings = create<SettingsStore>((set, get) => {
const initial = loadSettings(); const initial = loadSettings();
applyTheme(initial.theme); applyTheme(initial.theme);
applyColorOverrides({
accentColor: initial.accentColor,
textColor: initial.textColor,
});
applyDensity(initial.density); applyDensity(initial.density);
applyFontSettings({ applyFontSettings({
size: initial.fontSize, size: initial.fontSize,
@@ -371,6 +386,12 @@ export const useSettings = create<SettingsStore>((set, get) => {
if (patch.theme != null) { if (patch.theme != null) {
applyTheme(next.theme); applyTheme(next.theme);
} }
if (patch.theme != null || patch.accentColor != null || patch.textColor != null) {
applyColorOverrides({
accentColor: next.accentColor,
textColor: next.textColor,
});
}
if (patch.density != null) { if (patch.density != null) {
applyDensity(next.density); applyDensity(next.density);
} }
@@ -391,7 +412,8 @@ export const useSettings = create<SettingsStore>((set, get) => {
}, },
setTheme: (theme) => { setTheme: (theme) => {
applyTheme(theme); applyTheme(theme);
get().set({ theme }); const themeDefaultAccent = THEME_TOKENS[theme]?.css["--ps-accent"] ?? "#7c8bf5";
get().set({ theme, accentColor: themeDefaultAccent, textColor: "" });
}, },
updateProvider: (id, patch) => { updateProvider: (id, patch) => {
const nextProviders = get().aiProviders.map((p) => const nextProviders = get().aiProviders.map((p) =>
+14 -3
View File
@@ -2,9 +2,20 @@ import { describe, it, expect } from "vitest";
import { THEME_IDS, THEME_LABELS, THEME_TOKENS, getThemeTokens, applyTheme, getActiveTheme } from "./theme.js"; import { THEME_IDS, THEME_LABELS, THEME_TOKENS, getThemeTokens, applyTheme, getActiveTheme } from "./theme.js";
describe("theme token map", () => { describe("theme token map", () => {
it("defines exactly four themes", () => { it("defines ten themes including the core four", () => {
expect(THEME_IDS).toEqual(["ink", "parchment", "nocturne", "terminal"]); expect(THEME_IDS).toEqual([
expect(Object.keys(THEME_TOKENS)).toHaveLength(4); "ink",
"parchment",
"nocturne",
"terminal",
"espresso",
"forest",
"nordic",
"paperback",
"sepia",
"synthwave",
]);
expect(Object.keys(THEME_TOKENS)).toHaveLength(10);
}); });
it("labels every theme", () => { it("labels every theme", () => {
+179 -28
View File
@@ -1,20 +1,47 @@
/** /**
* Theme engine — CSS-variable token map. See PLAN.md §4.7 and CHUNK #1 step 3. * Theme engine — CSS-variable token map.
* *
* Four themes ship as token objects; `applyTheme(id)` sets * Ten themes ship as token objects; `applyTheme(id)` sets
* `document.documentElement.dataset.theme`. Accent color and density are * `document.documentElement.dataset.theme`. Accent color, text color, and
* runtime overrides layered on top. * density are runtime overrides layered on top.
*/ */
export type ThemeId = "ink" | "parchment" | "nocturne" | "terminal"; export type ThemeId =
| "ink"
| "parchment"
| "nocturne"
| "terminal"
| "espresso"
| "forest"
| "nordic"
| "paperback"
| "sepia"
| "synthwave";
export const THEME_IDS: ThemeId[] = ["ink", "parchment", "nocturne", "terminal"]; export const THEME_IDS: ThemeId[] = [
"ink",
"parchment",
"nocturne",
"terminal",
"espresso",
"forest",
"nordic",
"paperback",
"sepia",
"synthwave",
];
export const THEME_LABELS: Record<ThemeId, string> = { export const THEME_LABELS: Record<ThemeId, string> = {
ink: "Ink", ink: "Ink (Dark)",
parchment: "Parchment", parchment: "Parchment (Warm Light)",
nocturne: "Nocturne", nocturne: "Nocturne (Midnight Indigo)",
terminal: "Terminal", terminal: "Terminal (Phosphor Mono)",
espresso: "Espresso (Dark Roast)",
forest: "Evergreen (Deep Pine)",
nordic: "Nordic Frost (Slate Blue)",
paperback: "Paperback (Crisp Daylight)",
sepia: "Vintage Sepia (Aged Manuscript)",
synthwave: "Synthwave (Neon Dusk)",
}; };
export interface ThemeTokens { export interface ThemeTokens {
@@ -23,13 +50,9 @@ export interface ThemeTokens {
css: Record<string, string>; css: Record<string, string>;
} }
/**
* The four themes. Ink is the default (dark). Parchment is warm light,
* Nocturne is deep indigo, Terminal is monochrome monospace.
*/
export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = { export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
ink: { ink: {
label: "Ink", label: "Ink (Dark)",
css: { css: {
"--ps-bg": "#0e0f13", "--ps-bg": "#0e0f13",
"--ps-surface": "#17181f", "--ps-surface": "#17181f",
@@ -45,7 +68,7 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
}, },
}, },
parchment: { parchment: {
label: "Parchment", label: "Parchment (Warm Light)",
css: { css: {
"--ps-bg": "#f6f1e7", "--ps-bg": "#f6f1e7",
"--ps-surface": "#fffdf7", "--ps-surface": "#fffdf7",
@@ -61,7 +84,7 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
}, },
}, },
nocturne: { nocturne: {
label: "Nocturne", label: "Nocturne (Midnight Indigo)",
css: { css: {
"--ps-bg": "#0c0b1e", "--ps-bg": "#0c0b1e",
"--ps-surface": "#171533", "--ps-surface": "#171533",
@@ -77,7 +100,7 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
}, },
}, },
terminal: { terminal: {
label: "Terminal", label: "Terminal (Phosphor Mono)",
css: { css: {
"--ps-bg": "#05070a", "--ps-bg": "#05070a",
"--ps-surface": "#0a0f14", "--ps-surface": "#0a0f14",
@@ -92,6 +115,102 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
"--ps-warning": "#ffd93d", "--ps-warning": "#ffd93d",
}, },
}, },
espresso: {
label: "Espresso (Dark Roast)",
css: {
"--ps-bg": "#14100e",
"--ps-surface": "#1e1815",
"--ps-surface-2": "#2a211d",
"--ps-border": "#3b2f29",
"--ps-text": "#f2e8df",
"--ps-text-muted": "#b39f91",
"--ps-accent": "#d98a4e",
"--ps-accent-contrast": "#14100e",
"--ps-danger": "#e86868",
"--ps-success": "#6ac48a",
"--ps-warning": "#e6b450",
},
},
forest: {
label: "Evergreen (Deep Pine)",
css: {
"--ps-bg": "#0b1410",
"--ps-surface": "#12201a",
"--ps-surface-2": "#1a2e25",
"--ps-border": "#264236",
"--ps-text": "#e3f2ea",
"--ps-text-muted": "#8fb09e",
"--ps-accent": "#52c48c",
"--ps-accent-contrast": "#0b1410",
"--ps-danger": "#f07178",
"--ps-success": "#52c48c",
"--ps-warning": "#e5c07b",
},
},
nordic: {
label: "Nordic Frost (Slate Blue)",
css: {
"--ps-bg": "#1e222a",
"--ps-surface": "#282c34",
"--ps-surface-2": "#323844",
"--ps-border": "#3e4656",
"--ps-text": "#eceff4",
"--ps-text-muted": "#9aa5b8",
"--ps-accent": "#88c0d0",
"--ps-accent-contrast": "#1e222a",
"--ps-danger": "#bf616a",
"--ps-success": "#a3be8c",
"--ps-warning": "#ebcb8b",
},
},
paperback: {
label: "Paperback (Crisp Daylight)",
css: {
"--ps-bg": "#f5f7fa",
"--ps-surface": "#ffffff",
"--ps-surface-2": "#ebeef5",
"--ps-border": "#d6dce8",
"--ps-text": "#1a202c",
"--ps-text-muted": "#5a6578",
"--ps-accent": "#3b6ef6",
"--ps-accent-contrast": "#ffffff",
"--ps-danger": "#d93848",
"--ps-success": "#1f8a58",
"--ps-warning": "#c47f17",
},
},
sepia: {
label: "Vintage Sepia (Aged Manuscript)",
css: {
"--ps-bg": "#efe4ce",
"--ps-surface": "#f7eedb",
"--ps-surface-2": "#e5d6b8",
"--ps-border": "#cfc0a1",
"--ps-text": "#362819",
"--ps-text-muted": "#6e5840",
"--ps-accent": "#9c4b27",
"--ps-accent-contrast": "#f7eedb",
"--ps-danger": "#b3362a",
"--ps-success": "#367347",
"--ps-warning": "#a67314",
},
},
synthwave: {
label: "Synthwave (Neon Dusk)",
css: {
"--ps-bg": "#12091c",
"--ps-surface": "#1c0f2b",
"--ps-surface-2": "#28163d",
"--ps-border": "#3c225c",
"--ps-text": "#f8e9ff",
"--ps-text-muted": "#b695cc",
"--ps-accent": "#ff4fd8",
"--ps-accent-contrast": "#12091c",
"--ps-danger": "#ff5c77",
"--ps-success": "#36f9b3",
"--ps-warning": "#ffe261",
},
},
}; };
/** The active theme id, persisted by the settings store. */ /** The active theme id, persisted by the settings store. */
@@ -126,13 +245,54 @@ export function applyTheme(id: ThemeId): ThemeId {
return id; return id;
} }
/**
* Apply custom user overrides for accent color and/or primary text color on top
* of the active theme. Passing an empty string for `textColor` or `accentColor`
* restores the active theme's default token value.
*/
export function applyColorOverrides(overrides: {
accentColor?: string | undefined;
textColor?: string | undefined;
}): void {
const root = typeof document !== "undefined" ? document.documentElement : undefined;
if (!root) return;
const themeCss = THEME_TOKENS[activeTheme]?.css ?? THEME_TOKENS.ink.css;
if (overrides.accentColor !== undefined) {
const acc = overrides.accentColor.trim();
if (acc) {
root.style.setProperty("--ps-accent", acc);
} else if (themeCss["--ps-accent"]) {
root.style.setProperty("--ps-accent", themeCss["--ps-accent"]!);
}
}
if (overrides.textColor !== undefined) {
const txt = overrides.textColor.trim();
if (txt) {
root.style.setProperty("--ps-text", txt);
root.style.setProperty(
"--ps-text-muted",
`color-mix(in srgb, ${txt} 68%, var(--ps-bg))`,
);
} else {
if (themeCss["--ps-text"]) {
root.style.setProperty("--ps-text", themeCss["--ps-text"]!);
}
if (themeCss["--ps-text-muted"]) {
root.style.setProperty("--ps-text-muted", themeCss["--ps-text-muted"]!);
}
}
}
}
/** The currently active theme id. */ /** The currently active theme id. */
export function getActiveTheme(): ThemeId { export function getActiveTheme(): ThemeId {
return activeTheme; return activeTheme;
} }
/** /**
* Runtime font overrides for the writing surface. See PLAN.md §4.1/§4.7. * Runtime font overrides for the writing surface.
* These layer on top of the theme's base font families. * These layer on top of the theme's base font families.
*/ */
export interface FontSettings { export interface FontSettings {
@@ -153,11 +313,6 @@ export const DEFAULT_FONT_SETTINGS: FontSettings = {
measure: 720, measure: 720,
}; };
/**
* Apply font settings by writing CSS variables to :root. The prose column
* (`.ps-content`) reads these; an empty `family` leaves the theme's body font
* in place. Safe to call before the DOM exists (no-op).
*/
export function applyFontSettings(s: Partial<FontSettings>): void { export function applyFontSettings(s: Partial<FontSettings>): void {
const root = typeof document !== "undefined" ? document.documentElement : undefined; const root = typeof document !== "undefined" ? document.documentElement : undefined;
if (!root) return; if (!root) return;
@@ -167,10 +322,6 @@ export function applyFontSettings(s: Partial<FontSettings>): void {
if (s.family != null && s.family !== "") root.style.setProperty("--ps-font-body", s.family); if (s.family != null && s.family !== "") root.style.setProperty("--ps-font-body", s.family);
} }
/**
* Apply UI density ("compact" | "comfortable") by setting `data-density` on
* `:root` and updating `--ps-density` and `--ps-topbar-h`.
*/
export function applyDensity(density: "compact" | "comfortable"): void { export function applyDensity(density: "compact" | "comfortable"): void {
const root = typeof document !== "undefined" ? document.documentElement : undefined; const root = typeof document !== "undefined" ? document.documentElement : undefined;
if (!root) return; if (!root) return;
+100 -2
View File
@@ -1,7 +1,15 @@
import { execFileSync } from "node:child_process"; import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path"; import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import Fastify from "fastify"; import Fastify from "fastify";
import cors from "@fastify/cors"; import cors from "@fastify/cors";
@@ -80,10 +88,21 @@ export async function buildApp() {
const systemdUserDir = join(homedir(), ".config", "systemd", "user"); const systemdUserDir = join(homedir(), ".config", "systemd", "user");
const systemdServicePath = join(systemdUserDir, "pubscript-server.service"); const systemdServicePath = join(systemdUserDir, "pubscript-server.service");
const defaultProjectDir = join(homedir(), "Documents", "PubScript");
function expandTilde(inputPath: string): string {
const trimmed = inputPath.trim();
if (!trimmed) return defaultProjectDir;
if (trimmed === "~") return homedir();
if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2));
return resolve(trimmed);
}
interface PersistedServerSysConfig { interface PersistedServerSysConfig {
enabled: boolean; enabled: boolean;
port: number; port: number;
startOnBoot: boolean; startOnBoot: boolean;
projectDirectory: string;
} }
function loadPersistedServerSysConfig(): PersistedServerSysConfig { function loadPersistedServerSysConfig(): PersistedServerSysConfig {
@@ -100,6 +119,10 @@ export async function buildApp() {
typeof raw.startOnBoot === "boolean" typeof raw.startOnBoot === "boolean"
? raw.startOnBoot ? raw.startOnBoot
: existsSync(autostartDesktopPath) || existsSync(systemdServicePath), : existsSync(autostartDesktopPath) || existsSync(systemdServicePath),
projectDirectory:
typeof raw.projectDirectory === "string" && raw.projectDirectory.trim()
? raw.projectDirectory.trim()
: defaultProjectDir,
}; };
} }
} catch { } catch {
@@ -109,6 +132,7 @@ export async function buildApp() {
enabled: true, enabled: true,
port: config.port, port: config.port,
startOnBoot: existsSync(autostartDesktopPath) || existsSync(systemdServicePath), startOnBoot: existsSync(autostartDesktopPath) || existsSync(systemdServicePath),
projectDirectory: defaultProjectDir,
}; };
} }
@@ -116,6 +140,11 @@ export async function buildApp() {
try { try {
mkdirSync(sysConfigDir, { recursive: true }); mkdirSync(sysConfigDir, { recursive: true });
writeFileSync(sysConfigPath, JSON.stringify(cfg, null, 2), "utf8"); writeFileSync(sysConfigPath, JSON.stringify(cfg, null, 2), "utf8");
try {
mkdirSync(expandTilde(cfg.projectDirectory), { recursive: true });
} catch {
/* ignore if read-only */
}
const dataDir = join(homedir(), ".local", "share", "pubscript"); const dataDir = join(homedir(), ".local", "share", "pubscript");
const dbFile = join(dataDir, "pubscript.sqlite"); const dbFile = join(dataDir, "pubscript.sqlite");
@@ -197,6 +226,7 @@ export async function buildApp() {
port: persisted.port, port: persisted.port,
activePort: config.port, activePort: config.port,
startOnBoot: persisted.startOnBoot, startOnBoot: persisted.startOnBoot,
projectDirectory: persisted.projectDirectory,
autostartPath: autostartDesktopPath, autostartPath: autostartDesktopPath,
systemdServicePath, systemdServicePath,
}; };
@@ -210,11 +240,16 @@ export async function buildApp() {
if (!Number.isFinite(nextPort) || nextPort < 1024 || nextPort > 65535) { if (!Number.isFinite(nextPort) || nextPort < 1024 || nextPort > 65535) {
return reply.code(400).send({ error: "invalid_port" }); return reply.code(400).send({ error: "invalid_port" });
} }
const nextProjectDir =
typeof body.projectDirectory === "string" && body.projectDirectory.trim()
? body.projectDirectory.trim()
: current.projectDirectory;
const next: PersistedServerSysConfig = { const next: PersistedServerSysConfig = {
enabled: typeof body.enabled === "boolean" ? body.enabled : current.enabled, enabled: typeof body.enabled === "boolean" ? body.enabled : current.enabled,
port: nextPort, port: nextPort,
startOnBoot: startOnBoot:
typeof body.startOnBoot === "boolean" ? body.startOnBoot : current.startOnBoot, typeof body.startOnBoot === "boolean" ? body.startOnBoot : current.startOnBoot,
projectDirectory: nextProjectDir,
}; };
const configured = applySystemStartupFiles(next); const configured = applySystemStartupFiles(next);
return { return {
@@ -223,12 +258,75 @@ export async function buildApp() {
port: next.port, port: next.port,
activePort: config.port, activePort: config.port,
startOnBoot: next.startOnBoot, startOnBoot: next.startOnBoot,
projectDirectory: next.projectDirectory,
autostartConfigured: configured, autostartConfigured: configured,
autostartPath: autostartDesktopPath, autostartPath: autostartDesktopPath,
systemdServicePath, systemdServicePath,
}; };
}); });
app.get("/api/system/list-dirs", async (req) => {
const query = (req.query ?? {}) as { path?: string };
const rawTarget = query.path ? expandTilde(query.path) : homedir();
const target = existsSync(rawTarget) ? rawTarget : homedir();
const parentPath = dirname(target);
const directories: { name: string; path: string }[] = [];
try {
const entries = readdirSync(target, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith(".")) continue;
try {
const full = join(target, entry.name);
if (entry.isDirectory() || (entry.isSymbolicLink() && statSync(full).isDirectory())) {
directories.push({ name: entry.name, path: full });
}
} catch {
/* skip unreadable entry */
}
}
directories.sort((a, b) => a.name.localeCompare(b.name));
} catch {
/* ignore */
}
return {
ok: true,
currentPath: target,
parentPath: parentPath !== target ? parentPath : null,
homePath: homedir(),
directories,
};
});
app.post("/api/system/save-export", async (req, reply) => {
const body = (req.body ?? {}) as {
directory?: string;
fileName?: string;
base64Data?: string;
};
const safeName = basename((body.fileName ?? "").trim());
if (!safeName) {
return reply.code(400).send({ error: "invalid_file_name" });
}
if (typeof body.base64Data !== "string") {
return reply.code(400).send({ error: "missing_data" });
}
const targetDir = expandTilde(
body.directory?.trim() || loadPersistedServerSysConfig().projectDirectory,
);
try {
mkdirSync(targetDir, { recursive: true });
const fullPath = join(targetDir, safeName);
const buf = Buffer.from(body.base64Data, "base64");
writeFileSync(fullPath, buf);
return { ok: true, savedPath: fullPath };
} catch (err) {
return reply.code(500).send({
error: "save_failed",
message: err instanceof Error ? err.message : String(err),
});
}
});
registerAuthHook(app); registerAuthHook(app);
registerAuthRoutes(app); registerAuthRoutes(app);
registerRoutes(app); registerRoutes(app);