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;
activePort?: number;
startOnBoot: boolean;
projectDirectory?: string;
}> => {
const endpoints = [
"/api/system/server-config",
@@ -388,6 +389,7 @@ export const api = {
port: number;
activePort?: number;
startOnBoot: boolean;
projectDirectory?: string;
};
return {
online: true,
@@ -395,6 +397,7 @@ export const api = {
port: data.port,
...(data.activePort !== undefined ? { activePort: data.activePort } : {}),
startOnBoot: data.startOnBoot,
...(data.projectDirectory ? { projectDirectory: data.projectDirectory } : {}),
};
}
} catch {
@@ -410,7 +413,12 @@ export const api = {
},
updateServerConfig: async (
patch: { enabled?: boolean; port?: number; startOnBoot?: boolean },
patch: {
enabled?: boolean;
port?: number;
startOnBoot?: boolean;
projectDirectory?: string;
},
portHint?: number,
): Promise<{
online: boolean;
@@ -418,6 +426,7 @@ export const api = {
port: number;
activePort?: number;
startOnBoot: boolean;
projectDirectory?: string;
}> => {
const endpoints = [
"/api/system/server-config",
@@ -438,6 +447,7 @@ export const api = {
port: number;
activePort?: number;
startOnBoot: boolean;
projectDirectory?: string;
};
return {
online: true,
@@ -445,6 +455,7 @@ export const api = {
port: data.port,
...(data.activePort !== undefined ? { activePort: data.activePort } : {}),
startOnBoot: data.startOnBoot,
...(data.projectDirectory ? { projectDirectory: data.projectDirectory } : {}),
};
}
} catch {
@@ -456,6 +467,103 @@ export const api = {
enabled: patch.enabled ?? true,
port: patch.port ?? portHint ?? 8081,
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>
);
}
+565 -207
View File
@@ -6,6 +6,7 @@ import {
type AppSettings,
} from "../store/settings.js";
import { api } from "../api.js";
import { DirectoryBrowserModal } from "./DirectoryBrowserModal.js";
import {
Select,
Button,
@@ -19,6 +20,34 @@ import {
} from "@pubscript/ui";
import type { ProviderKind, ThinkingEffort } from "@pubscript/ai";
type SettingsTab = "appearance" | "writing" | "ai" | "server";
const ACCENT_PRESETS = [
"#7c8bf5",
"#9d7bff",
"#3b6ef6",
"#88c0d0",
"#52c48c",
"#33ff9b",
"#d98a4e",
"#b5793a",
"#ff4fd8",
"#f16d7a",
"#f0b754",
];
const TEXT_COLOR_PRESETS = [
{ label: "Soft White", color: "#e6e8ee" },
{ label: "Pure White", color: "#ffffff" },
{ label: "Warm Cream", color: "#f2e8df" },
{ label: "Lavender Mist", color: "#e8e6ff" },
{ label: "Terminal Green", color: "#33ff9b" },
{ label: "Amber Phosphor", color: "#ffb84d" },
{ label: "Charcoal Ink", color: "#2c2720" },
{ label: "Deep Slate", color: "#1a202c" },
{ label: "Vintage Sepia", color: "#362819" },
];
export function Settings() {
const s = useSettings();
const set = useSettings((st) => st.set);
@@ -32,12 +61,17 @@ export function Settings() {
const probeProviderModels = useSettings((st) => st.probeProviderModels);
const reset = useSettings((st) => st.reset);
const [activeTab, setActiveTab] = useState<SettingsTab>("appearance");
const [selectedProviderId, setSelectedProviderId] = useState<string>(s.activeProviderId);
const [selectedAgentId, setSelectedAgentId] = useState<string>(s.activeAgentId);
const [probing, setProbing] = useState(false);
// Server settings state
// Server & Project Directory state
const [portDraft, setPortDraft] = useState<string>(String(s.serverPort));
const [projectDirDraft, setProjectDirDraft] = useState<string>(
s.projectDirectory || "~/Documents/PubScript",
);
const [browseProjectDirOpen, setBrowseProjectDirOpen] = useState<boolean>(false);
const [serverOnline, setServerOnline] = useState<boolean>(false);
const [activeRunningPort, setActiveRunningPort] = useState<number | null>(null);
const [savingServerCfg, setSavingServerCfg] = useState<boolean>(false);
@@ -50,10 +84,14 @@ export function Settings() {
setActiveRunningPort(res.activePort ?? res.port);
if (res.online) {
setPortDraft(String(res.port));
if (res.projectDirectory) {
setProjectDirDraft(res.projectDirectory);
}
set({
serverEnabled: res.enabled,
serverPort: res.port,
serverStartOnBoot: res.startOnBoot,
...(res.projectDirectory ? { projectDirectory: res.projectDirectory } : {}),
});
}
});
@@ -62,6 +100,29 @@ export function Settings() {
};
}, []);
const currentProvider =
s.aiProviders.find((p) => p.id === selectedProviderId) ?? s.aiProviders[0]!;
const currentAgent =
s.aiAgents.find((a) => a.id === selectedAgentId) ?? s.aiAgents[0]!;
const activeThemeDefaultText =
THEME_TOKENS[s.theme]?.css["--ps-text"] ?? "#e6e8ee";
const activeThemeDefaultAccent =
THEME_TOKENS[s.theme]?.css["--ps-accent"] ?? "#7c8bf5";
const handleSaveProjectDirectory = async (dirPath?: string) => {
const target = (dirPath ?? projectDirDraft).trim() || "~/Documents/PubScript";
setProjectDirDraft(target);
set({ projectDirectory: target });
setSavingServerCfg(true);
try {
await api.updateServerConfig({ projectDirectory: target }, s.serverPort);
toast.success(`Main project directory set to ${target}`);
} finally {
setSavingServerCfg(false);
}
};
const handleToggleServerEnabled = async (enabled: boolean) => {
set({ serverEnabled: enabled });
setSavingServerCfg(true);
@@ -112,11 +173,6 @@ export function Settings() {
}
};
const currentProvider =
s.aiProviders.find((p) => p.id === selectedProviderId) ?? s.aiProviders[0]!;
const currentAgent =
s.aiAgents.find((a) => a.id === selectedAgentId) ?? s.aiAgents[0]!;
const handleProbeModels = async () => {
if (!currentProvider) return;
setProbing(true);
@@ -166,108 +222,486 @@ export function Settings() {
const def = DEFAULT_AI_AGENTS.find((a) => a.id === currentAgent.id);
if (def) {
updateAgent(currentAgent.id, {
systemPrompt: def.systemPrompt,
temperature: def.temperature,
contextWindow: def.contextWindow,
maxTokens: def.maxTokens,
thinkingEnabled: def.thinkingEnabled,
thinkingEffort: def.thinkingEffort,
systemPrompt: def.systemPrompt,
});
toast.info(`Reset ${currentAgent.name} to default settings`);
toast.info(`Reset ${def.name} to default settings`);
}
};
return (
<div className="ps-page-container">
<div style={{ marginBottom: 24 }}>
<h1 className="heading">Settings</h1>
<p className="muted">
Configure appearance, UI density, AI providers &amp; agents, and writing preferences.
Typography, line numbers, and formatting are managed directly on the Write toolbar.
</p>
</div>
{/* APPEARANCE */}
<div className="ps-settings-group">
<h3>Appearance &amp; Layout</h3>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Theme</div>
<div className="ps-settings-desc">
Choose a color theme for the studio. UI typography is locked to System Sans.
</div>
</div>
<div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
<Select
aria-label="Theme"
value={s.theme}
onChange={(e) => setTheme(e.target.value as ThemeId)}
options={THEME_IDS.map((id) => ({ value: id, label: THEME_LABELS[id] }))}
/>
<div className="ps-swatches">
{THEME_IDS.map((id) => {
const tokens = THEME_TOKENS[id].css;
const isActive = s.theme === id;
<section className="ps-content ps-page-container" aria-label="Settings">
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14, flexWrap: "wrap", gap: 10 }}>
<h2 style={{ margin: 0 }}>Settings</h2>
<div className="ps-tabs" role="tablist" aria-label="Settings Categories" style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
{(
[
{ id: "appearance", label: "🎨 Appearance & Themes" },
{ id: "writing", label: "📁 Projects & Writing" },
{ id: "ai", label: "✨ AI Providers & Agents" },
{ id: "server", label: "🖧 Server & System" },
] as const
).map((tab) => {
const isActive = activeTab === tab.id;
return (
<button
key={id}
key={tab.id}
type="button"
className={`ps-swatch${isActive ? " is-active" : ""}`}
role="tab"
aria-selected={isActive}
onClick={() => setActiveTab(tab.id)}
style={{
background: tokens["--ps-bg"],
borderColor: isActive ? tokens["--ps-accent"] : tokens["--ps-border"],
color: tokens["--ps-text"],
padding: "7px 14px",
borderRadius: 8,
border: isActive
? "1.5px solid var(--ps-accent)"
: "1px solid var(--ps-border)",
background: isActive
? "color-mix(in srgb, var(--ps-accent) 16%, var(--ps-surface-2))"
: "var(--ps-surface)",
color: "var(--ps-text)",
fontWeight: isActive ? 600 : 500,
fontSize: 13,
cursor: "pointer",
}}
title={THEME_LABELS[id]}
onClick={() => setTheme(id)}
>
<span
className="ps-swatch-accent"
style={{ background: tokens["--ps-accent"] }}
/>
<span className="ps-swatch-label">{THEME_LABELS[id]}</span>
{tab.label}
</button>
);
})}
</div>
</div>
{/* TAB 1: APPEARANCE & THEMES */}
{activeTab === "appearance" && (
<div className="ps-settings-group">
<h3>Appearance &amp; Themes</h3>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Theme</div>
<div className="ps-settings-desc">
Choose from 10 studio palettes crafted for long-form writing.
</div>
</div>
<Select
value={s.theme}
onChange={(e) => setTheme(e.target.value as ThemeId)}
options={THEME_IDS.map((id) => ({
value: id,
label: THEME_LABELS[id],
}))}
/>
</div>
<div className="ps-settings-row" style={{ flexDirection: "column", alignItems: "stretch", gap: 10 }}>
<div>
<div className="ps-settings-label">Theme Palettes</div>
<div className="ps-settings-desc">
Click any theme card to apply its background, surface, border, and default accent/text tokens.
</div>
</div>
<div className="ps-theme-swatch-grid">
{THEME_IDS.map((id) => {
const tok = THEME_TOKENS[id]!;
const isActive = s.theme === id;
return (
<button
key={id}
type="button"
className={`ps-theme-swatch-card${isActive ? " is-active" : ""}`}
onClick={() => setTheme(id)}
style={{
background: tok.css["--ps-surface"],
color: tok.css["--ps-text"],
borderColor: isActive
? tok.css["--ps-accent"]
: tok.css["--ps-border"],
}}
>
<div className="ps-theme-swatch-title">
<span>{tok.label}</span>
{isActive && <span>✓</span>}
</div>
<div className="ps-theme-swatch-dots">
<span
title="Background"
style={{ background: tok.css["--ps-bg"] }}
/>
<span
title="Surface"
style={{ background: tok.css["--ps-surface-2"] }}
/>
<span
title="Accent"
style={{ background: tok.css["--ps-accent"] }}
/>
<span
title="Text"
style={{ background: tok.css["--ps-text"] }}
/>
</div>
</button>
);
})}
</div>
</div>
{/* ACCENT COLOR PICKER */}
<div className="ps-settings-row" style={{ flexDirection: "column", alignItems: "stretch", gap: 10 }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
<div>
<div className="ps-settings-label">Accent Color</div>
<div className="ps-settings-desc">
Pick a preset swatch or choose any custom highlight/accent color.
</div>
</div>
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="color"
aria-label="Custom accent color picker"
value={s.accentColor.startsWith("#") && s.accentColor.length === 7 ? s.accentColor : activeThemeDefaultAccent}
onChange={(e) => set({ accentColor: e.target.value })}
style={{
width: 36,
height: 32,
padding: 2,
borderRadius: 6,
border: "1px solid var(--ps-border)",
background: "var(--ps-surface-2)",
cursor: "pointer",
}}
/>
<input
type="text"
className="ps-input"
value={s.accentColor}
onChange={(e) => set({ accentColor: e.target.value })}
style={{ width: 100, fontFamily: "var(--ps-font-mono)", fontSize: 12.5 }}
placeholder="#7c8bf5"
/>
<Button
variant="secondary"
size="sm"
onClick={() => set({ accentColor: activeThemeDefaultAccent })}
>
Theme Default
</Button>
</div>
</div>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
{ACCENT_PRESETS.map((color) => {
const selected = s.accentColor.toLowerCase() === color.toLowerCase();
return (
<button
key={color}
type="button"
title={`Accent ${color}`}
onClick={() => set({ accentColor: color })}
style={{
width: 28,
height: 28,
borderRadius: "50%",
background: color,
border: selected ? "3px solid var(--ps-text)" : "2px solid var(--ps-border)",
cursor: "pointer",
boxShadow: selected ? "0 0 0 2px var(--ps-bg)" : "none",
}}
/>
);
})}
</div>
</div>
{/* TEXT COLOR PICKER */}
<div className="ps-settings-row" style={{ flexDirection: "column", alignItems: "stretch", gap: 10 }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
<div>
<div className="ps-settings-label">Text Color</div>
<div className="ps-settings-desc">
Customize the primary manuscript &amp; UI text color, or use the active theme&rsquo;s default text color.
</div>
</div>
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="color"
aria-label="Custom text color picker"
value={
s.textColor && s.textColor.startsWith("#") && s.textColor.length === 7
? s.textColor
: activeThemeDefaultText
}
onChange={(e) => set({ textColor: e.target.value })}
style={{
width: 36,
height: 32,
padding: 2,
borderRadius: 6,
border: "1px solid var(--ps-border)",
background: "var(--ps-surface-2)",
cursor: "pointer",
}}
/>
<input
type="text"
className="ps-input"
value={s.textColor || activeThemeDefaultText}
onChange={(e) => set({ textColor: e.target.value })}
style={{ width: 100, fontFamily: "var(--ps-font-mono)", fontSize: 12.5 }}
placeholder={activeThemeDefaultText}
/>
<Button
variant="secondary"
size="sm"
onClick={() => set({ textColor: "" })}
>
Theme Default
</Button>
</div>
</div>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
{TEXT_COLOR_PRESETS.map((preset) => {
const effectiveText = (s.textColor || activeThemeDefaultText).toLowerCase();
const selected = effectiveText === preset.color.toLowerCase();
return (
<button
key={preset.color}
type="button"
title={`${preset.label} (${preset.color})`}
onClick={() => set({ textColor: preset.color })}
style={{
display: "inline-flex",
alignItems: "center",
gap: 6,
padding: "4px 10px",
borderRadius: 999,
background: "var(--ps-surface-2)",
color: "var(--ps-text)",
border: selected ? "2px solid var(--ps-accent)" : "1px solid var(--ps-border)",
fontSize: 12,
cursor: "pointer",
}}
>
<span
style={{
width: 14,
height: 14,
borderRadius: "50%",
background: preset.color,
border: "1px solid var(--ps-border)",
}}
/>
<span>{preset.label}</span>
</button>
);
})}
</div>
</div>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">UI Density</div>
<div className="ps-settings-desc">
Adjust padding, row height, and control spacing across all panels.
</div>
<div className="ps-settings-label">Density</div>
<div className="ps-settings-desc">Control UI spacing across sidebars, toolbars, and tables.</div>
</div>
<Select
aria-label="Density"
value={s.density}
onChange={(e) => set({ density: e.target.value as Density })}
options={[
{ value: "compact", label: "Compact (High density)" },
{ value: "comfortable", label: "Comfortable (Standard spacing)" },
{ value: "comfortable", label: "Comfortable" },
{ value: "compact", label: "Compact" },
]}
/>
</div>
</div>
)}
{/* AI PROVIDERS & AGENTS */}
{/* TAB 2: PROJECTS & WRITING */}
{activeTab === "writing" && (
<div className="ps-settings-group">
<h3>Projects &amp; Writing</h3>
<div className="ps-settings-row" style={{ flexDirection: "column", alignItems: "stretch", gap: 10 }}>
<div>
<div className="ps-settings-label">Main Project Directory</div>
<div className="ps-settings-desc">
Default folder on your machine for projects, backups, and manuscript exports.
</div>
</div>
<div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
<input
type="text"
className="ps-input"
style={{ flex: 1, minWidth: 240, fontFamily: "var(--ps-font-mono)", fontSize: 12.5 }}
value={projectDirDraft}
onChange={(e) => setProjectDirDraft(e.target.value)}
placeholder="~/Documents/PubScript"
aria-label="Main project directory"
/>
<Button
variant="secondary"
size="sm"
onClick={() => setBrowseProjectDirOpen(true)}
>
📁 Browse…
</Button>
<Button
variant="primary"
size="sm"
disabled={savingServerCfg}
onClick={() => void handleSaveProjectDirectory()}
>
Save Directory
</Button>
</div>
</div>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Word count goal</div>
<div className="ps-settings-desc">Target length for your manuscript.</div>
</div>
<Select
value={String(s.wordCountGoal)}
onChange={(e) => set({ wordCountGoal: Number(e.target.value) })}
options={[20_000, 40_000, 60_000, 80_000, 100_000, 120_000, 150_000].map((n) => ({
value: String(n),
label: `${(n / 1000).toFixed(0)},000 words`,
}))}
/>
</div>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Auto-save</div>
<div className="ps-settings-desc">
Persist manuscript changes automatically and record autosave revisions in the sidebar.
</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="checkbox"
checked={s.autoSave}
onChange={(e) => set({ autoSave: e.target.checked })}
/>
<span style={{ fontSize: 13 }}>{s.autoSave ? "Enabled" : "Disabled"}</span>
</label>
</div>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Spellcheck</div>
<div className="ps-settings-desc">
Underline misspelled words as you write using the bundled offline dictionary.
</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="checkbox"
checked={s.enableSpellcheck}
onChange={(e) => set({ enableSpellcheck: e.target.checked })}
/>
<span style={{ fontSize: 13 }}>{s.enableSpellcheck ? "Enabled" : "Disabled"}</span>
</label>
</div>
{s.enableSpellcheck && (
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Spellcheck Language</div>
<div className="ps-settings-desc">Active dictionary for spelling checks.</div>
</div>
<Select
value={s.spellcheckLanguage}
onChange={(e) => set({ spellcheckLanguage: e.target.value })}
options={[
{ value: "en_US", label: "English (US)" },
{ value: "en_GB", label: "English (UK)" },
{ value: "ca_ES", label: "Català (Espanya)" },
]}
/>
</div>
)}
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Grammar checking</div>
<div className="ps-settings-desc">Suggest grammar and style fixes inline.</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="checkbox"
checked={s.enableGrammarCheck}
onChange={(e) => set({ enableGrammarCheck: e.target.checked })}
/>
<span style={{ fontSize: 13 }}>{s.enableGrammarCheck ? "Enabled" : "Disabled"}</span>
</label>
</div>
{s.enableGrammarCheck && (
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Grammar provider</div>
<div className="ps-settings-desc">Local built-in rules or LanguageTool server.</div>
</div>
<Select
value={s.grammarProvider}
onChange={(e) =>
set({ grammarProvider: e.target.value as AppSettings["grammarProvider"] })
}
options={[
{ value: "local", label: "Built-in (Local)" },
{ value: "languagetool", label: "LanguageTool (Self-hosted / Cloud)" },
]}
/>
</div>
)}
{s.enableGrammarCheck && s.grammarProvider === "languagetool" && (
<div className="ps-settings-row">
<div style={{ flex: 1 }}>
<div className="ps-settings-label">LanguageTool API key</div>
<div className="ps-settings-desc">
Optional — uses the public or local endpoint without a key.
</div>
</div>
<Input
type="password"
placeholder="Optional API key"
value={s.grammarApiKey}
onChange={(e) => set({ grammarApiKey: e.target.value })}
/>
</div>
)}
</div>
)}
{/* TAB 3: AI PROVIDERS & AGENTS */}
{activeTab === "ai" && (
<>
<div className="ps-settings-group">
<h3>AI Providers &amp; Connection</h3>
<p className="ps-settings-desc" style={{ marginBottom: 12 }}>
Configure local AI servers (Ollama, llama.cpp, LM Studio) or cloud endpoints (OpenAI, Anthropic, Google Gemini, OpenRouter).
</p>
<div className="ps-ai-settings-card">
<div className="ps-ai-settings-top">
<div className="ps-ai-settings-card-head">
<div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
<Select
label="Select Provider to Configure"
value={currentProvider.id}
onChange={(e) => {
const id = e.target.value;
setSelectedProviderId(id);
const prov = s.aiProviders.find((p) => p.id === id);
if (prov) {
set({ activeProviderId: prov.id, activeModel: prov.defaultModel });
const found = s.aiProviders.find((p) => p.id === id);
if (found) {
set({
activeProviderId: id,
activeModel: found.defaultModel || found.models[0] || "",
});
}
}}
options={s.aiProviders.map((p) => ({
@@ -275,10 +709,31 @@ export function Settings() {
label: `${p.name} (${p.kind})`,
}))}
/>
{s.activeProviderId === currentProvider.id ? (
<Badge variant="success">Active Provider</Badge>
) : (
<Button
variant="secondary"
size="sm"
onClick={() =>
set({
activeProviderId: currentProvider.id,
activeModel: currentProvider.defaultModel || currentProvider.models[0] || "",
})
}
>
Set Active
</Button>
)}
</div>
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<Button variant="secondary" size="sm" onClick={() => void handleProbeModels()} disabled={probing}>
{probing ? "Loading…" : "↻ Load / Detect Models"}
<Button
variant="secondary"
size="sm"
onClick={() => void handleProbeModels()}
disabled={probing}
>
{probing ? "Detecting…" : "↻ Load / Detect Models"}
</Button>
<Button variant="secondary" size="sm" onClick={handleAddProvider}>
+ Add Provider
@@ -300,77 +755,80 @@ export function Settings() {
<div className="ps-ai-settings-grid">
<Input
label="Provider Display Name"
label="Provider Name"
value={currentProvider.name}
onChange={(e) => updateProvider(currentProvider.id, { name: e.target.value })}
/>
<Select
label="Adapter Protocol"
label="Provider API Type"
value={currentProvider.kind}
onChange={(e) =>
updateProvider(currentProvider.id, { kind: e.target.value as ProviderKind })
}
options={[
{ value: "openai-compatible", label: "OpenAI-Compatible (Ollama, llama.cpp, LM Studio, OpenAI)" },
{ value: "openai-compatible", label: "OpenAI-Compatible (Ollama / llama.cpp / LM Studio / OpenAI)" },
{ value: "anthropic", label: "Anthropic (Claude)" },
{ value: "google", label: "Google (Gemini)" },
{ value: "openrouter", label: "OpenRouter" },
]}
/>
<Input
label="API Base URL"
placeholder="http://localhost:11434/v1"
label="Base URL / Endpoint"
value={currentProvider.baseUrl}
placeholder="http://localhost:11434/v1"
onChange={(e) => updateProvider(currentProvider.id, { baseUrl: e.target.value })}
/>
<Input
label="API Key (optional for local servers)"
label="API Key (leave blank for local Ollama / llama.cpp)"
type="password"
placeholder="sk-..."
value={currentProvider.apiKey}
placeholder="sk-..."
onChange={(e) => updateProvider(currentProvider.id, { apiKey: e.target.value })}
/>
<Input
label="Default Model ID"
placeholder="e.g. llama3.2, gpt-4o, claude-3-7-sonnet-latest"
<Select
label="Default Model"
value={currentProvider.defaultModel}
onChange={(e) => {
const model = e.target.value;
const models = currentProvider.models.includes(model)
? currentProvider.models
: [model, ...currentProvider.models].filter(Boolean);
updateProvider(currentProvider.id, { defaultModel: model, models });
updateProvider(currentProvider.id, { defaultModel: model });
if (s.activeProviderId === currentProvider.id) {
set({ activeModel: model });
}
}}
options={currentProvider.models.map((m) => ({ value: m, label: m }))}
/>
<Input
label="Available Models (comma-separated)"
label="Custom Model ID (comma-separated list)"
value={currentProvider.models.join(", ")}
onChange={(e) => {
const models = e.target.value
const list = e.target.value
.split(",")
.map((m) => m.trim())
.map((x) => x.trim())
.filter(Boolean);
if (list.length > 0) {
updateProvider(currentProvider.id, {
models: models.length > 0 ? models : [currentProvider.defaultModel],
models: list,
defaultModel: list.includes(currentProvider.defaultModel)
? currentProvider.defaultModel
: list[0]!,
});
}
}}
/>
</div>
</div>
</div>
{/* AI AGENTS */}
<div className="ps-settings-group">
<h3>AI Agents &amp; Role Prompts</h3>
<p className="ps-settings-desc" style={{ marginBottom: 12 }}>
Customize temperature, context window (ctx), max output tokens, reasoning effort, and system prompts for each AI co-writing agent.
</p>
<div className="ps-ai-settings-card">
<div className="ps-ai-settings-top">
<div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
<div className="ps-ai-settings-card-head">
<div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
<Select
label="Select Agent to Edit"
value={currentAgent.id}
onChange={(e) => {
const id = e.target.value;
@@ -505,8 +963,11 @@ export function Settings() {
</div>
</div>
</div>
</>
)}
{/* SERVER & SYSTEM STARTUP */}
{/* TAB 4: SERVER & SYSTEM */}
{activeTab === "server" && (
<div className="ps-settings-group">
<h3>Server &amp; System Startup</h3>
@@ -589,128 +1050,13 @@ export function Settings() {
</span>
</label>
</div>
</div>
{/* WRITING & PROOFING */}
<div className="ps-settings-group">
<h3>Writing &amp; Proofing</h3>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Word count goal</div>
<div className="ps-settings-desc">Target length for your manuscript.</div>
</div>
<Select
value={String(s.wordCountGoal)}
onChange={(e) => set({ wordCountGoal: Number(e.target.value) })}
options={[20_000, 40_000, 60_000, 80_000, 100_000, 120_000, 150_000].map((n) => ({
value: String(n),
label: `${(n / 1000).toFixed(0)},000 words`,
}))}
/>
</div>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Auto-save</div>
<div className="ps-settings-desc">Persist manuscript changes automatically.</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="checkbox"
checked={s.autoSave}
onChange={(e) => set({ autoSave: e.target.checked })}
/>
</label>
</div>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Spellcheck</div>
<div className="ps-settings-desc">
Underline misspelled words as you write using the bundled offline dictionary.
</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="checkbox"
checked={s.enableSpellcheck}
onChange={(e) => set({ enableSpellcheck: e.target.checked })}
/>
</label>
</div>
{s.enableSpellcheck && (
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Spellcheck Language</div>
<div className="ps-settings-desc">Active dictionary for spelling checks.</div>
</div>
<Select
value={s.spellcheckLanguage}
onChange={(e) => set({ spellcheckLanguage: e.target.value })}
options={[
{ value: "en_US", label: "English (US)" },
{ value: "en_GB", label: "English (UK)" },
{ value: "ca_ES", label: "Català (Espanya)" },
]}
/>
</div>
)}
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Grammar checking</div>
<div className="ps-settings-desc">Suggest grammar and style fixes inline.</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: 8 }}>
<input
type="checkbox"
checked={s.enableGrammarCheck}
onChange={(e) => set({ enableGrammarCheck: e.target.checked })}
/>
</label>
</div>
{s.enableGrammarCheck && (
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Grammar provider</div>
<div className="ps-settings-desc">Local built-in rules or LanguageTool server.</div>
</div>
<Select
value={s.grammarProvider}
onChange={(e) =>
set({ grammarProvider: e.target.value as AppSettings["grammarProvider"] })
}
options={[
{ value: "local", label: "Built-in (Local)" },
{ value: "languagetool", label: "LanguageTool (Self-hosted / Cloud)" },
]}
/>
</div>
)}
{s.enableGrammarCheck && s.grammarProvider === "languagetool" && (
<div className="ps-settings-row">
<div style={{ flex: 1 }}>
<div className="ps-settings-label">LanguageTool API key</div>
<div className="ps-settings-desc">Optional — uses the public or local endpoint without a key.</div>
</div>
<Input
type="password"
placeholder="Optional API key"
value={s.grammarApiKey}
onChange={(e) => set({ grammarApiKey: e.target.value })}
/>
</div>
)}
</div>
<div className="ps-settings-row">
<div>
<div className="ps-settings-label">Reset to defaults</div>
<div className="ps-settings-desc">Restore default theme, providers, agents, and preferences.</div>
<div className="ps-settings-desc">
Restore default theme, colors, project directory, providers, agents, and preferences.
</div>
</div>
<Button
variant="danger"
@@ -724,5 +1070,17 @@ export function Settings() {
</Button>
</div>
</div>
)}
<DirectoryBrowserModal
open={browseProjectDirOpen}
initialPath={projectDirDraft}
title="Choose Main Project Directory"
onSelect={(dir) => {
void handleSaveProjectDirectory(dir);
}}
onClose={() => setBrowseProjectDirOpen(false)}
/>
</section>
);
}
+142 -51
View File
@@ -1,11 +1,10 @@
import { useEffect, useMemo, useState } from "react";
import { Modal, Button } from "@pubscript/ui";
import {
THEMES,
exportProjectData,
type ExportFormat,
} from "@pubscript/exporters";
import { Modal, Button, toast } from "@pubscript/ui";
import { exportProjectData, type ExportFormat } from "@pubscript/exporters";
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 { downloadFile } from "./download.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. */
function slug(value: string): string {
return value
return (
value
.trim()
.toLowerCase()
.replace(/[^\w-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60) || "project";
.slice(0, 60) || "manuscript"
);
}
export function ExportDialog({ open, onClose }: ExportDialogProps) {
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 [format, setFormat] = useState<ExportFormat>("markdown");
const [themeId, setThemeId] = useState("ink");
const projectDirectory = useSettings((s) => s.projectDirectory);
const serverPort = useSettings((s) => s.serverPort);
const [format, setFormat] = useState<ExportFormat>("epub");
const [scope, setScope] = useState<Scope>("project");
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 [exporting, setExporting] = useState(false);
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.
useEffect(() => {
if (!open || !adapter || !projectId) return;
@@ -48,7 +85,6 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
const allBooks = await adapter.listBooks(projectId);
if (!active) return;
setBooks(allBooks);
// Resolve the first chapter across books so the selector has a default.
let firstChapterId = "";
for (const book of allBooks) {
const cs = await adapter.listChapters(book.id);
@@ -69,30 +105,48 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
const chapterOptions = useMemo(() => {
const byBook = new Map<string, { id: string; title: string }[]>();
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;
}, [books, chapters]);
const formatInfo: FormatInfo | undefined = useMemo(
() => EXPORT_FORMATS.find((f) => f.id === format),
[format]
);
const handleExport = async () => {
if (!adapter || !projectId) return;
setExporting(true);
setError(null);
try {
const project = await buildExportProject(adapter, projectId);
const exportProj = await buildExportProject(adapter, projectId);
const options: Parameters<typeof exportProjectData>[2] = {
scope: scope === "chapter" ? "chapter" : "project",
theme: themeId,
};
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";
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();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
@@ -102,8 +156,9 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
};
return (
<>
<Modal
title="Export project"
title="Export Manuscript"
open={open}
onClose={onClose}
footer={
@@ -111,47 +166,35 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
<Button variant="ghost" onClick={onClose} disabled={exporting}>
Cancel
</Button>
<Button onClick={handleExport} disabled={exporting || !formatInfo}>
<Button
variant="primary"
onClick={() => void handleExport()}
disabled={exporting || !formatInfo}
>
{exporting ? "Exporting…" : "Export"}
</Button>
</>
}
>
<div className="ps-export-grid">
<label className="ps-export-field">
<span>Format</span>
<div className="ps-export-grid" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
<label className="ps-export-field" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
<span style={{ fontSize: 12.5, fontWeight: 600 }}>File Type / Conversion Format</span>
<select
className="ps-select"
value={format}
onChange={(e) => setFormat(e.target.value as ExportFormat)}
onChange={(e) => handleFormatChange(e.target.value as ExportFormat)}
disabled={exporting}
>
{EXPORT_FORMATS.map((f) => (
<option key={f.id} value={f.id}>
{f.label}
{f.label} (.{f.extension})
</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>
<label className="ps-export-field" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
<span style={{ fontSize: 12.5, fontWeight: 600 }}>Scope</span>
<select
className="ps-select"
value={scope}
@@ -164,8 +207,8 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
</label>
{scope === "chapter" && (
<label className="ps-export-field">
<span>Chapter</span>
<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}
@@ -177,14 +220,62 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
<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">{error}</p>}
{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 { 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 { createUlid } from "@pubscript/core";
@@ -238,6 +245,7 @@ export const DEFAULT_AI_AGENTS: AIAgentConfig[] = [
export interface AppSettings {
theme: ThemeId;
accentColor: string;
textColor: string;
density: Density;
fontFamily: FontFamily;
fontSize: number;
@@ -247,6 +255,7 @@ export interface AppSettings {
wordCountGoal: number;
autoSave: boolean;
focusMode: boolean;
projectDirectory: string;
// Navigation & AI Sidebars
navCollapsed: boolean;
aiSidebarOpen: boolean;
@@ -272,6 +281,7 @@ export interface AppSettings {
export const DEFAULT_SETTINGS: AppSettings = {
theme: "ink",
accentColor: "#7c8bf5",
textColor: "",
density: "comfortable",
fontFamily: "serif",
fontSize: 16,
@@ -281,6 +291,7 @@ export const DEFAULT_SETTINGS: AppSettings = {
wordCountGoal: 80_000,
autoSave: true,
focusMode: false,
projectDirectory: "~/Documents/PubScript",
navCollapsed: false,
aiSidebarOpen: false,
aiSidebarWidth: 370,
@@ -351,6 +362,10 @@ export interface SettingsStore extends AppSettings {
export const useSettings = create<SettingsStore>((set, get) => {
const initial = loadSettings();
applyTheme(initial.theme);
applyColorOverrides({
accentColor: initial.accentColor,
textColor: initial.textColor,
});
applyDensity(initial.density);
applyFontSettings({
size: initial.fontSize,
@@ -371,6 +386,12 @@ export const useSettings = create<SettingsStore>((set, get) => {
if (patch.theme != null) {
applyTheme(next.theme);
}
if (patch.theme != null || patch.accentColor != null || patch.textColor != null) {
applyColorOverrides({
accentColor: next.accentColor,
textColor: next.textColor,
});
}
if (patch.density != null) {
applyDensity(next.density);
}
@@ -391,7 +412,8 @@ export const useSettings = create<SettingsStore>((set, get) => {
},
setTheme: (theme) => {
applyTheme(theme);
get().set({ theme });
const themeDefaultAccent = THEME_TOKENS[theme]?.css["--ps-accent"] ?? "#7c8bf5";
get().set({ theme, accentColor: themeDefaultAccent, textColor: "" });
},
updateProvider: (id, patch) => {
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";
describe("theme token map", () => {
it("defines exactly four themes", () => {
expect(THEME_IDS).toEqual(["ink", "parchment", "nocturne", "terminal"]);
expect(Object.keys(THEME_TOKENS)).toHaveLength(4);
it("defines ten themes including the core four", () => {
expect(THEME_IDS).toEqual([
"ink",
"parchment",
"nocturne",
"terminal",
"espresso",
"forest",
"nordic",
"paperback",
"sepia",
"synthwave",
]);
expect(Object.keys(THEME_TOKENS)).toHaveLength(10);
});
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
* `document.documentElement.dataset.theme`. Accent color and density are
* runtime overrides layered on top.
* Ten themes ship as token objects; `applyTheme(id)` sets
* `document.documentElement.dataset.theme`. Accent color, text color, and
* 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> = {
ink: "Ink",
parchment: "Parchment",
nocturne: "Nocturne",
terminal: "Terminal",
ink: "Ink (Dark)",
parchment: "Parchment (Warm Light)",
nocturne: "Nocturne (Midnight Indigo)",
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 {
@@ -23,13 +50,9 @@ export interface ThemeTokens {
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> = {
ink: {
label: "Ink",
label: "Ink (Dark)",
css: {
"--ps-bg": "#0e0f13",
"--ps-surface": "#17181f",
@@ -45,7 +68,7 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
},
},
parchment: {
label: "Parchment",
label: "Parchment (Warm Light)",
css: {
"--ps-bg": "#f6f1e7",
"--ps-surface": "#fffdf7",
@@ -61,7 +84,7 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
},
},
nocturne: {
label: "Nocturne",
label: "Nocturne (Midnight Indigo)",
css: {
"--ps-bg": "#0c0b1e",
"--ps-surface": "#171533",
@@ -77,7 +100,7 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
},
},
terminal: {
label: "Terminal",
label: "Terminal (Phosphor Mono)",
css: {
"--ps-bg": "#05070a",
"--ps-surface": "#0a0f14",
@@ -92,6 +115,102 @@ export const THEME_TOKENS: Record<ThemeId, ThemeTokens> = {
"--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. */
@@ -126,13 +245,54 @@ export function applyTheme(id: ThemeId): ThemeId {
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. */
export function getActiveTheme(): ThemeId {
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.
*/
export interface FontSettings {
@@ -153,11 +313,6 @@ export const DEFAULT_FONT_SETTINGS: FontSettings = {
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 {
const root = typeof document !== "undefined" ? document.documentElement : undefined;
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);
}
/**
* 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 {
const root = typeof document !== "undefined" ? document.documentElement : undefined;
if (!root) return;
+100 -2
View File
@@ -1,7 +1,15 @@
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 { dirname, join, resolve } from "node:path";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import Fastify from "fastify";
import cors from "@fastify/cors";
@@ -80,10 +88,21 @@ export async function buildApp() {
const systemdUserDir = join(homedir(), ".config", "systemd", "user");
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 {
enabled: boolean;
port: number;
startOnBoot: boolean;
projectDirectory: string;
}
function loadPersistedServerSysConfig(): PersistedServerSysConfig {
@@ -100,6 +119,10 @@ export async function buildApp() {
typeof raw.startOnBoot === "boolean"
? raw.startOnBoot
: existsSync(autostartDesktopPath) || existsSync(systemdServicePath),
projectDirectory:
typeof raw.projectDirectory === "string" && raw.projectDirectory.trim()
? raw.projectDirectory.trim()
: defaultProjectDir,
};
}
} catch {
@@ -109,6 +132,7 @@ export async function buildApp() {
enabled: true,
port: config.port,
startOnBoot: existsSync(autostartDesktopPath) || existsSync(systemdServicePath),
projectDirectory: defaultProjectDir,
};
}
@@ -116,6 +140,11 @@ export async function buildApp() {
try {
mkdirSync(sysConfigDir, { recursive: true });
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 dbFile = join(dataDir, "pubscript.sqlite");
@@ -197,6 +226,7 @@ export async function buildApp() {
port: persisted.port,
activePort: config.port,
startOnBoot: persisted.startOnBoot,
projectDirectory: persisted.projectDirectory,
autostartPath: autostartDesktopPath,
systemdServicePath,
};
@@ -210,11 +240,16 @@ export async function buildApp() {
if (!Number.isFinite(nextPort) || nextPort < 1024 || nextPort > 65535) {
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 = {
enabled: typeof body.enabled === "boolean" ? body.enabled : current.enabled,
port: nextPort,
startOnBoot:
typeof body.startOnBoot === "boolean" ? body.startOnBoot : current.startOnBoot,
projectDirectory: nextProjectDir,
};
const configured = applySystemStartupFiles(next);
return {
@@ -223,12 +258,75 @@ export async function buildApp() {
port: next.port,
activePort: config.port,
startOnBoot: next.startOnBoot,
projectDirectory: next.projectDirectory,
autostartConfigured: configured,
autostartPath: autostartDesktopPath,
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);
registerAuthRoutes(app);
registerRoutes(app);