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>
);
}
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 { 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
.trim()
.replace(/[^\w-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60) || "project";
return (
value
.trim()
.toLowerCase()
.replace(/[^\w-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
.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,89 +156,126 @@ export function ExportDialog({ open, onClose }: ExportDialogProps) {
};
return (
<Modal
title="Export project"
open={open}
onClose={onClose}
footer={
<>
<Button variant="ghost" onClick={onClose} disabled={exporting}>
Cancel
</Button>
<Button onClick={handleExport} disabled={exporting || !formatInfo}>
{exporting ? "Exporting…" : "Export"}
</Button>
</>
}
>
<div className="ps-export-grid">
<label className="ps-export-field">
<span>Format</span>
<select
className="ps-select"
value={format}
onChange={(e) => setFormat(e.target.value as ExportFormat)}
disabled={exporting}
>
{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>
<>
<Modal
title="Export Manuscript"
open={open}
onClose={onClose}
footer={
<>
<Button variant="ghost" onClick={onClose} disabled={exporting}>
Cancel
</Button>
<Button
variant="primary"
onClick={() => void handleExport()}
disabled={exporting || !formatInfo}
>
{exporting ? "Exporting…" : "Export"}
</Button>
</>
}
>
<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={chapterId}
onChange={(e) => setChapterId(e.target.value)}
disabled={exporting || chapterOptions.size === 0}
value={format}
onChange={(e) => handleFormatChange(e.target.value as ExportFormat)}
disabled={exporting}
>
{Array.from(chapterOptions.values()).flatMap((cs) =>
cs.map((c) => (
<option key={c.id} value={c.id}>
{c.title}
</option>
))
)}
{EXPORT_FORMATS.map((f) => (
<option key={f.id} value={f.id}>
{f.label} (.{f.extension})
</option>
))}
</select>
</label>
)}
</div>
{error && <p className="ps-export-error" role="alert">{error}</p>}
</Modal>
<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}
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 { 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) =>