Compare commits

...

10 Commits

Author SHA1 Message Date
TC
2868a6152b 1.24.0 2026-06-22 22:00:48 +10:00
TC
5cdc3efeef 💄 make title/part titles match font size 2026-06-22 22:00:40 +10:00
TC
ff40d424aa 💄 hide running headings on title pages 2026-06-22 21:56:50 +10:00
TC
7c0b993d7e 💄 fix formatting for project PDF export 2026-06-22 21:51:19 +10:00
TC
78d3bc2d82 cleanup spacing 2026-06-22 17:17:16 +10:00
TC
2472860966 1.23.1 2026-06-21 19:42:11 +10:00
TC
f205332d24 🔧 more options for PDF export 2026-06-21 19:10:24 +10:00
TC
8c10ba7731 🐛 fix the export dialogue 2026-06-21 16:47:16 +10:00
TC
5bc045ad40 1.23.0 2026-06-20 22:18:23 +10:00
TC
199e909778 grammar checker 2026-06-20 22:18:12 +10:00
14 changed files with 360 additions and 83 deletions

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "hohoff-editor",
"version": "1.22.0",
"version": "1.24.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "hohoff-editor",
"version": "1.22.0",
"version": "1.24.0",
"dependencies": {
"@anthropic-ai/sdk": "^0.29.0",
"@codemirror/commands": "^6.6.0",

View File

@@ -1,6 +1,6 @@
{
"name": "hohoff-editor",
"version": "1.22.0",
"version": "1.24.0",
"description": "Novel editor for Hohoff",
"main": "out/main/index.js",
"scripts": {

View File

@@ -0,0 +1,74 @@
import https from 'https'
import querystring from 'querystring'
export interface GrammarMatch {
offset: number
length: number
message: string
shortMessage: string
replacement: string | null
ruleId: string
categoryId: string
}
const IGNORED_RULE_IDS = new Set([
'WHITESPACE_RULE',
'UNPAIRED_BRACKETS',
'EN_QUOTES',
'DASH_RULE',
'WORD_CONTAINS_UNDERSCORE',
])
export async function checkGrammar(text: string, language = 'en-US'): Promise<GrammarMatch[]> {
return new Promise((resolve, reject) => {
const body = querystring.stringify({ text, language, enabledOnly: 'false' })
const req = https.request(
{
hostname: 'api.languagetool.org',
path: '/v2/check',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body),
'Accept': 'application/json',
},
},
(res) => {
let data = ''
res.on('data', (chunk) => { data += chunk })
res.on('end', () => {
try {
const parsed = JSON.parse(data) as {
matches: Array<{
offset: number
length: number
message: string
shortMessage: string
replacements: Array<{ value: string }>
rule: { id: string; category: { id: string } }
}>
}
const matches: GrammarMatch[] = parsed.matches
.filter((m) => !IGNORED_RULE_IDS.has(m.rule.id))
.map((m) => ({
offset: m.offset,
length: m.length,
message: m.message,
shortMessage: m.shortMessage || m.message,
replacement: m.replacements[0]?.value ?? null,
ruleId: m.rule.id,
categoryId: m.rule.category.id,
}))
resolve(matches)
} catch (e) {
reject(new Error(`LanguageTool parse error: ${String(e)}`))
}
})
}
)
req.on('error', reject)
req.setTimeout(15000, () => { req.destroy(); reject(new Error('Grammar check timed out')) })
req.write(body)
req.end()
})
}

View File

@@ -137,6 +137,12 @@ function buildAppMenu(win: BrowserWindow): void {
{ type: 'separator' },
{ role: 'selectAll' },
{ type: 'separator' },
{
label: 'Clean Up Spacing',
accelerator: 'CmdOrCtrl+Shift+K',
click: () => send(win, 'cleanupSpacing')
},
{ type: 'separator' },
{
label: 'Find / Replace',
accelerator: 'CmdOrCtrl+F',

View File

@@ -5,6 +5,8 @@ import { tmpdir } from 'os'
import { listDraftFiles, readMarkdownFile, writeMarkdownFile, getProjectWordCount, saveOrderFile, readSession, writeSession, saveRevision, listRevisions, loadRevision, deleteRevision, renameFileOrDir, deleteFileOrDir, createMarkdownFile, createSubdirectory, moveFileOrDir, readStoryBibleFile, openStoryBibleFile, writeStoryBibleFile, openPublisherPackFile, searchAcrossFiles, replaceInFiles, readAllDraftFiles, readProjectConfig, writeProjectConfig, PROJECT_CONFIG_FIELDS, readTelemetry, readSubmissions, writeSubmissions } from './fileSystem'
import type { SearchOptions, ProjectConfig } from './fileSystem'
import { streamMessage, resetClient } from './aiService'
import { checkGrammar } from './grammarService'
import type { GrammarMatch } from './grammarService'
import { onWordSnapshot, flushTelemetry } from './telemetry'
import type { AIPayload, Attachment, Submission } from '../renderer/types/editor'
import { readGlobalConfig, writeGlobalConfig, getProjectTitle, addRecentProject, updateRecentProjectTitle } from './globalConfig'
@@ -170,6 +172,10 @@ export function registerIpcHandlers(): void {
await writeSubmissions(data)
})
ipcMain.handle('grammar:check', async (_event, text: string): Promise<GrammarMatch[]> => {
return await checkGrammar(text)
})
ipcMain.handle('ai:streamMessage', async (event, payload: AIPayload) => {
try {
const storyBibleContent = (await readStoryBibleFile()) ?? undefined
@@ -385,8 +391,14 @@ export function registerIpcHandlers(): void {
showChapterTitle: boolean
includeCover: boolean
includeFrontMatter: boolean
includePartSeparators: boolean
pageFrom: number | null
pageTo: number | null
font: 'courier' | 'times' | 'georgia'
fontSize: number
pageSize: 'letter' | 'a4'
titleOnFirstPage: boolean
boldHeadings: boolean
}): Promise<void> => {
const win = BrowserWindow.fromWebContents(event.sender)
const projectCfg = await readProjectConfig()
@@ -432,11 +444,19 @@ export function registerIpcHandlers(): void {
authorEmail,
].filter(Boolean)
const fontFamily = opts.font === 'times'
? '"Times New Roman", Times, serif'
: opts.font === 'georgia'
? 'Georgia, serif'
: '"Courier New", Courier, monospace'
const pageSizeCss = opts.pageSize === 'a4' ? 'A4' : 'letter'
const headingWeight = opts.boldHeadings ? 'bold' : 'normal'
const coverCSS = `
@page { size: letter; }
@page { size: ${pageSizeCss}; }
body {
font-family: "Courier New", Courier, monospace;
font-size: 12pt;
font-family: ${fontFamily};
font-size: ${opts.fontSize}pt;
line-height: 1.5;
color: #000;
margin: 0;
@@ -463,7 +483,7 @@ export function registerIpcHandlers(): void {
text-align: center;
line-height: 2;
}
.cover-title { font-size: 12pt; text-transform: uppercase; margin: 0; }
.cover-title { font-size: ${opts.fontSize}pt; text-transform: uppercase; margin: 0; }
.cover-by { margin: 0; }
.cover-byline{ margin: 0; }
`
@@ -503,6 +523,7 @@ export function registerIpcHandlers(): void {
// Body chapters = docs inside a Part subdirectory
let currentPart: string | null = null
let chapterIndex = 0
let firstChapterDone = false
for (const doc of docs) {
const slashIdx = doc.relativePath.indexOf('/')
@@ -511,14 +532,8 @@ export function registerIpcHandlers(): void {
if (isFrontMatter && !opts.includeFrontMatter) continue
if (partName !== null && partName !== currentPart) {
currentPart = partName
const safe = partName.replace(/&/g, '&amp;').replace(/</g, '&lt;')
sections.push({
title: partName,
bodyHtml: `<div class="part-page"><div class="part-title">${safe}</div></div>`
})
}
const isNewPart = partName !== null && partName !== currentPart
if (isNewPart) currentPart = partName
const fileName = doc.relativePath.split('/').pop()?.replace(/\.md$/, '') ?? doc.relativePath
let headerTitle: string
@@ -546,17 +561,26 @@ export function registerIpcHandlers(): void {
headerTitle = fileName
}
const contentHtml = await marked(normalize(doc.content))
let titleHtml = ''
if (!firstChapterDone && opts.titleOnFirstPage) {
titleHtml = `<h1 style="font-weight:bold;margin-bottom:0">${esc(projectName)}</h1>`
}
firstChapterDone = true
const partHtml = (isNewPart && opts.includePartSeparators && currentPart)
? `<h2 class="part-heading">${esc(currentPart)}</h2>`
: ''
sections.push({
title: headerTitle,
bodyHtml: `<div class="chapter">${headingHtml}${contentHtml}</div>`
bodyHtml: `<div class="chapter">${titleHtml}${partHtml}${headingHtml}${contentHtml}</div>`
})
}
// CSS shared by chapter/part sections — cover page uses its own CSS (set above).
const pageCSS = `
@page { size: letter; }
body { font-family: "Courier New", Courier, monospace; font-size: 12pt; line-height: 2; color: #000; margin: 0; padding: 0; }
h1, h2, h3 { font-weight: normal; font-size: 12pt; text-align: center; text-transform: uppercase; margin: 0; line-height: 2; }
@page { size: ${pageSizeCss}; }
body { font-family: ${fontFamily}; font-size: ${opts.fontSize}pt; line-height: 2; color: #000; margin: 0; padding: 0; }
h1 { font-weight: bold; font-size: ${opts.fontSize}pt; text-align: center; text-transform: uppercase; letter-spacing: 0.15em; margin: 0; line-height: 2; }
h2, h3 { font-weight: ${headingWeight}; font-size: ${opts.fontSize}pt; text-align: center; text-transform: uppercase; margin: 0; line-height: 2; }
p { margin: 0; text-indent: 0.5in; text-align: left; }
h1 + p, h2 + p, h3 + p, hr + p, .chapter > p:first-child { text-indent: 0; }
hr { border: none; margin: 0; height: 2em; text-align: center; }
@@ -567,8 +591,7 @@ export function registerIpcHandlers(): void {
ul, ol { margin: 0 0 0 0.5in; }
li { margin: 0; }
.chapter { padding-top: 2.5in; }
.part-page { padding-top: 3.5in; text-align: center; }
.part-title { font-family: "Courier New", Courier, monospace; font-size: 12pt; text-transform: uppercase; }
.part-heading { font-family: ${fontFamily}; font-weight: bold; font-size: ${opts.fontSize}pt; text-align: center; text-transform: uppercase; letter-spacing: 0.15em; margin: 0; line-height: 2; }
`
// Print each section to its own PDF buffer. Cover page uses its own CSS;
@@ -585,7 +608,7 @@ export function registerIpcHandlers(): void {
try {
await offscreen.loadFile(tempPath)
const buf = await offscreen.webContents.printToPDF({
pageSize: 'Letter',
pageSize: opts.pageSize === 'a4' ? 'A4' : 'Letter',
displayHeaderFooter: false,
margins: { marginType: 'custom', top: 1.0, bottom: 1.0, left: 1.0, right: 1.0 }
})
@@ -599,37 +622,41 @@ export function registerIpcHandlers(): void {
// Merge all section PDFs into one document, tracking which section each page
// belongs to so we can stamp the correct running header on it.
const mergedPdf = await PDFDocument.create()
const courier = await mergedPdf.embedFont(StandardFonts.Courier)
// pageOwners[i] tracks the section title and whether the page is a cover page
const pageOwners: { title: string; isCover: boolean }[] = []
const headerStandardFont = opts.font === 'courier' ? StandardFonts.Courier : StandardFonts.TimesRoman
const headerFont = await mergedPdf.embedFont(headerStandardFont)
// pageOwners[i] tracks the section title, whether the page is a cover page,
// and whether it is the first page of its section (chapter/part opener).
const pageOwners: { title: string; isCover: boolean; isSectionOpener: boolean }[] = []
for (const { title, buffer, isCover } of sectionPdfs) {
const srcPdf = await PDFDocument.load(buffer)
const copied = await mergedPdf.copyPages(srcPdf, srcPdf.getPageIndices())
for (const page of copied) {
for (const [pageIdx, page] of copied.entries()) {
mergedPdf.addPage(page)
pageOwners.push({ title, isCover })
pageOwners.push({ title, isCover, isSectionOpener: pageIdx === 0 })
}
}
// Stamp the running header on body pages only (cover page gets no header).
// Stamp the running header on body pages only (cover page and section opener
// pages get no header — opener pages show the chapter/part title instead).
// Page numbers count from 1 starting with the first non-cover page.
const allPages = mergedPdf.getPages()
let bodyPageNum = 0
for (let i = 0; i < allPages.length; i++) {
if (pageOwners[i].isCover) continue // no header/number on cover page
bodyPageNum++
if (pageOwners[i].isSectionOpener) continue // no running header on chapter/part opener pages
const page = allPages[i]
const { width, height } = page.getSize()
const chapterUpper = pageOwners[i].title.toUpperCase()
const headerText = `${projectTitle} / ${chapterUpper} / ${bodyPageNum}`
const fontSize = 11
const textWidth = courier.widthOfTextAtSize(headerText, fontSize)
const textWidth = headerFont.widthOfTextAtSize(headerText, fontSize)
page.drawText(headerText, {
x: width - 72 - textWidth, // 1 in from right edge (72pt = 1in)
y: height - 36, // 0.5 in from top edge (36pt = 0.5in)
size: fontSize,
font: courier,
font: headerFont,
color: rgb(0, 0, 0)
})
}

View File

@@ -145,4 +145,7 @@ contextBridge.exposeInMainWorld('api', {
writeSubmissions: (data: Submission[]): Promise<void> =>
ipcRenderer.invoke('submissions:write', data),
checkGrammar: (text: string): Promise<import('../main/grammarService').GrammarMatch[]> =>
ipcRenderer.invoke('grammar:check', text),
})

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { ExportDialog } from './components/Export/ExportDialog'
import type { ExportOptions } from './components/Export/ExportDialog'
import { FileTree } from './components/FileTree/FileTree'
@@ -58,6 +58,7 @@ export default function App(): JSX.Element {
const [isFirstRun, setIsFirstRun] = useState(false)
const [focusPeek, setFocusPeek] = useState(false)
const [projectTitle, setProjectTitle] = useState('')
const menuHandlerRef = useRef<((action: string) => Promise<void>) | null>(null)
useEffect(() => {
if (!focusMode) {
@@ -99,49 +100,66 @@ export default function App(): JSX.Element {
}, [])
// Handle menu actions sent from the main process
useEffect(() => {
return window.api.onMenuAction(async (action) => {
if (action === 'save') {
if (activeFilePath && isDirty) {
await window.api.writeFile(activeFilePath, activeFileContent)
await window.api.saveRevision(activeFilePath, activeFileContent)
markSaved()
}
} else if (action === 'toggleSidebar') {
setSidebarOpen((v) => { const n = !v; localStorage.setItem('sidebarOpen', String(n)); return n })
} else if (action === 'toggleChat') {
setChatOpen((v) => { const n = !v; localStorage.setItem('chatOpen', String(n)); return n })
} else if (action === 'toggleRevisions') {
toggleRevisionPanel()
} else if (action === 'toggleTheme') {
toggleTheme()
} else if (action === 'fontIncrease') {
setFontSize(fontSize + 1)
} else if (action === 'fontDecrease') {
setFontSize(fontSize - 1)
} else if (action === 'fontReset') {
setFontSize(15)
} else if (action === 'projectSearch') {
openProjectSearch()
} else if (action === 'openSettings') {
setSettingsOpen(true)
} else if (action === 'toggleFocusMode') {
toggleFocusMode()
} else if (action === 'openProject') {
const picked = await window.api.pickProjectFolder()
if (picked) await switchProject(picked)
} else if (action.startsWith('openRecent:')) {
await switchProject(action.slice('openRecent:'.length))
} else if (action === 'exportPDF') {
if (activeFilePath && activeFileContent) {
const fileName = activeFilePath.split('/').pop()?.replace(/\.md$/, '') ?? 'document'
await window.api.exportPDF(activeFileContent, fileName)
}
} else if (action === 'exportProjectPDF') {
setExportOpen(true)
menuHandlerRef.current = async (action: string): Promise<void> => {
if (action === 'save') {
if (activeFilePath && isDirty) {
await window.api.writeFile(activeFilePath, activeFileContent)
await window.api.saveRevision(activeFilePath, activeFileContent)
markSaved()
}
})
}, [activeFilePath, isDirty, activeFileContent, fontSize])
} else if (action === 'toggleSidebar') {
setSidebarOpen((v) => { const n = !v; localStorage.setItem('sidebarOpen', String(n)); return n })
} else if (action === 'toggleChat') {
setChatOpen((v) => { const n = !v; localStorage.setItem('chatOpen', String(n)); return n })
} else if (action === 'toggleRevisions') {
toggleRevisionPanel()
} else if (action === 'toggleTheme') {
toggleTheme()
} else if (action === 'fontIncrease') {
setFontSize(fontSize + 1)
} else if (action === 'fontDecrease') {
setFontSize(fontSize - 1)
} else if (action === 'fontReset') {
setFontSize(15)
} else if (action === 'projectSearch') {
openProjectSearch()
} else if (action === 'openSettings') {
setSettingsOpen(true)
} else if (action === 'toggleFocusMode') {
toggleFocusMode()
} else if (action === 'openProject') {
const picked = await window.api.pickProjectFolder()
if (picked) await switchProject(picked)
} else if (action.startsWith('openRecent:')) {
await switchProject(action.slice('openRecent:'.length))
} else if (action === 'exportPDF') {
if (activeFilePath && activeFileContent) {
const fileName = activeFilePath.split('/').pop()?.replace(/\.md$/, '') ?? 'document'
await window.api.exportPDF(activeFileContent, fileName)
}
} else if (action === 'exportProjectPDF') {
setExportOpen(true)
} else if (action === 'cleanupSpacing') {
const view = currentEditorView
if (!view) return
const { from, to } = view.state.selection.main
const hasSelection = from !== to
const start = hasSelection ? from : 0
const end = hasSelection ? to : view.state.doc.length
const text = view.state.doc.sliceString(start, end)
const cleaned = text.replace(/\n\n+/g, '\n')
if (cleaned !== text) {
view.dispatch(view.state.update({
changes: { from: start, to: end, insert: cleaned },
userEvent: 'input'
}))
}
}
}
useEffect(() => {
return window.api.onMenuAction((action) => menuHandlerRef.current?.(action))
}, [])
// Handle Cmd+S / Ctrl+S and Cmd+Shift+F / Ctrl+Shift+F
useEffect(() => {

View File

@@ -563,6 +563,11 @@ function buildTheme(fontSize: number, dark: boolean, focusMode = false): ReturnT
backgroundColor: 'rgba(240, 100, 180, 0.15)',
borderBottom: '2px solid rgba(240, 100, 180, 0.65)',
borderRadius: '2px'
},
'.annotation-grammar': {
backgroundColor: 'rgba(220, 60, 60, 0.12)',
borderBottom: '2px solid rgba(220, 60, 60, 0.75)',
borderRadius: '2px'
}
},
{ dark }

View File

@@ -35,6 +35,15 @@
grid-column: 2;
}
.export-format-row {
display: flex;
gap: 12px;
}
.export-format-field {
flex: 1;
}
.export-page-range {
display: flex;
align-items: center;

View File

@@ -6,18 +6,24 @@ export interface ExportOptions {
showChapterTitle: boolean
includeCover: boolean
includeFrontMatter: boolean
includePartSeparators: boolean
pageFrom: number | null
pageTo: number | null
font: 'courier' | 'times' | 'georgia'
fontSize: number
pageSize: 'letter' | 'a4'
titleOnFirstPage: boolean
boldHeadings: boolean
}
const STORAGE_KEY = 'exportDialogPrefs'
function loadPrefs(): Pick<ExportOptions, 'romanNumerals' | 'showChapterTitle' | 'includeCover' | 'includeFrontMatter'> {
function loadPrefs(): Pick<ExportOptions, 'romanNumerals' | 'showChapterTitle' | 'includeCover' | 'includeFrontMatter' | 'includePartSeparators' | 'font' | 'fontSize' | 'pageSize' | 'titleOnFirstPage' | 'boldHeadings'> {
try {
const raw = localStorage.getItem(STORAGE_KEY)
if (raw) return JSON.parse(raw)
if (raw) return { font: 'courier', fontSize: 12, pageSize: 'letter', titleOnFirstPage: false, boldHeadings: false, includePartSeparators: true, ...JSON.parse(raw) }
} catch { /* ignore */ }
return { romanNumerals: true, showChapterTitle: false, includeCover: true, includeFrontMatter: true }
return { romanNumerals: true, showChapterTitle: false, includeCover: true, includeFrontMatter: true, includePartSeparators: true, font: 'courier', fontSize: 12, pageSize: 'letter', titleOnFirstPage: false, boldHeadings: false }
}
interface Props {
@@ -31,6 +37,12 @@ export function ExportDialog({ onClose, onExport }: Props): JSX.Element {
const [showChapterTitle, setShowChapterTitle] = useState(prefs.showChapterTitle)
const [includeCover, setIncludeCover] = useState(prefs.includeCover)
const [includeFrontMatter, setIncludeFrontMatter] = useState(prefs.includeFrontMatter)
const [includePartSeparators, setIncludePartSeparators] = useState(prefs.includePartSeparators)
const [font, setFont] = useState(prefs.font)
const [fontSize, setFontSize] = useState(prefs.fontSize)
const [pageSize, setPageSize] = useState(prefs.pageSize)
const [titleOnFirstPage, setTitleOnFirstPage] = useState(prefs.titleOnFirstPage)
const [boldHeadings, setBoldHeadings] = useState(prefs.boldHeadings)
const [pageFrom, setPageFrom] = useState('')
const [pageTo, setPageTo] = useState('')
const overlayRef = useRef<HTMLDivElement>(null)
@@ -48,14 +60,14 @@ export function ExportDialog({ onClose, onExport }: Props): JSX.Element {
}
const savePrefs = (patch: Partial<typeof prefs>): void => {
const next = { romanNumerals, showChapterTitle, includeCover, includeFrontMatter, ...patch }
const next = { romanNumerals, showChapterTitle, includeCover, includeFrontMatter, includePartSeparators, font, fontSize, pageSize, titleOnFirstPage, boldHeadings, ...patch }
localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
}
const handleExport = (): void => {
const from = pageFrom.trim() ? parseInt(pageFrom, 10) : null
const to = pageTo.trim() ? parseInt(pageTo, 10) : null
onExport({ romanNumerals, showChapterTitle, includeCover, includeFrontMatter, pageFrom: from, pageTo: to })
onExport({ romanNumerals, showChapterTitle, includeCover, includeFrontMatter, includePartSeparators, pageFrom: from, pageTo: to, font, fontSize, pageSize, titleOnFirstPage, boldHeadings })
}
const pageRangeValid = (): boolean => {
@@ -116,6 +128,77 @@ export function ExportDialog({ onClose, onExport }: Props): JSX.Element {
<span className="export-toggle-label">Include front &amp; back matter</span>
<span className="export-toggle-hint">Prologue, Content Warning, Epilogue</span>
</label>
<label className="export-toggle">
<input
type="checkbox"
checked={includePartSeparators}
onChange={e => { setIncludePartSeparators(e.target.checked); savePrefs({ includePartSeparators: e.target.checked }) }}
/>
<span className="export-toggle-label">Include part labels</span>
<span className="export-toggle-hint">Part name above the first chapter of each part</span>
</label>
</div>
<div className="export-format-row">
<div className="settings-field export-format-field">
<span className="settings-label">Font</span>
<select
className="settings-input"
value={font}
onChange={e => { const v = e.target.value as ExportOptions['font']; setFont(v); savePrefs({ font: v }) }}
>
<option value="courier">Courier New</option>
<option value="times">Times New Roman</option>
<option value="georgia">Georgia</option>
</select>
</div>
<div className="settings-field export-format-field">
<span className="settings-label">Font size</span>
<select
className="settings-input"
value={fontSize}
onChange={e => { const v = parseInt(e.target.value, 10); setFontSize(v); savePrefs({ fontSize: v }) }}
>
<option value={11}>11pt</option>
<option value={12}>12pt</option>
<option value={13}>13pt</option>
<option value={14}>14pt</option>
</select>
</div>
<div className="settings-field export-format-field">
<span className="settings-label">Page size</span>
<select
className="settings-input"
value={pageSize}
onChange={e => { const v = e.target.value as ExportOptions['pageSize']; setPageSize(v); savePrefs({ pageSize: v }) }}
>
<option value="letter">Letter</option>
<option value="a4">A4</option>
</select>
</div>
</div>
<div className="export-toggles">
<label className="export-toggle">
<input
type="checkbox"
checked={titleOnFirstPage}
onChange={e => { setTitleOnFirstPage(e.target.checked); savePrefs({ titleOnFirstPage: e.target.checked }) }}
/>
<span className="export-toggle-label">Title on first page</span>
<span className="export-toggle-hint">Manuscript title bold and centered above chapter one</span>
</label>
<label className="export-toggle">
<input
type="checkbox"
checked={boldHeadings}
onChange={e => { setBoldHeadings(e.target.checked); savePrefs({ boldHeadings: e.target.checked }) }}
/>
<span className="export-toggle-label">Bold chapter headings</span>
<span className="export-toggle-hint">Chapter numbers and titles in bold</span>
</label>
</div>
<div className="settings-field">

View File

@@ -29,6 +29,7 @@ function badgeColor(type: TextAnnotation['type']): string {
case 'user_comment': return 'rgba(240, 100, 180, 0.85)'
case 'document_note': return 'rgba(80, 180, 240, 0.85)'
case 'polish': return 'rgba(55, 138, 221, 0.75)'
case 'grammar': return 'rgba(220, 60, 60, 0.8)'
}
}
@@ -295,13 +296,14 @@ function PolishMeter({ score }: { score: PolishScore }): JSX.Element {
const [activeKey, setActiveKey] = useState<string | null>(null)
const [tooltip, setTooltip] = useState<TooltipState | null>(null)
const { setAnnotations, clearAnnotations } = useEditorStore()
const widgetRef = useRef<HTMLDivElement>(null)
const dims = Object.entries(score.dimensions) as [string, PolishDimension][]
function handleDimClick(key: string, dim: PolishDimension): void {
if (activeKey === key) {
setActiveKey(null)
clearAnnotations()
setAnnotations([])
return
}
if (dim.matches.length === 0) return
@@ -326,8 +328,21 @@ function PolishMeter({ score }: { score: PolishScore }): JSX.Element {
}
}, [score.overall])
// Hide highlights when clicking outside the polish meter
useEffect(() => {
if (!activeKey) return
function handleOutsideClick(e: MouseEvent): void {
if (widgetRef.current && !widgetRef.current.contains(e.target as Node)) {
setActiveKey(null)
setAnnotations([])
}
}
document.addEventListener('mousedown', handleOutsideClick)
return () => document.removeEventListener('mousedown', handleOutsideClick)
}, [activeKey, setAnnotations])
return (
<div className="pm-widget">
<div ref={widgetRef} className="pm-widget">
<div className="pm-header">
<span className="pm-title">Polish</span>
<span className="pm-overall" style={{ color: scoreColor(score.overall) }}>{score.overall}</span>

View File

@@ -363,6 +363,34 @@ export function AnalysisToolbar(): JSX.Element {
}
}
const runGrammar = async (): Promise<void> => {
if (!hasFile || isAILoading) return
setAILoading(true)
setAIError(null)
setAnalysisMode('none')
try {
const matches = await window.api.checkGrammar(activeFileContent)
const newAnnotations = matches.map((m) => {
const matched = activeFileContent.slice(m.offset, m.offset + m.length)
return {
id: `grammar-${m.offset}-${m.ruleId}`,
type: 'grammar' as const,
from: m.offset,
to: m.offset + m.length,
matchedText: matched,
message: m.message,
suggestion: m.replacement ?? undefined,
}
})
const existing = useEditorStore.getState().annotations.filter((a) => a.type !== 'grammar')
setAnnotations([...existing, ...newAnnotations])
} catch (err) {
setAIError(err instanceof Error ? err.message : 'Grammar check failed')
} finally {
setAILoading(false)
}
}
const passiveCount = annotations.filter((a) => a.type === 'passive_voice').length
const pastProgressiveCount = annotations.filter((a) => a.type === 'past_progressive').length
const weakVerbsCount = annotations.filter((a) => a.type === 'weak_verbs').length
@@ -371,7 +399,8 @@ export function AnalysisToolbar(): JSX.Element {
const styleCount = annotations.filter((a) => a.type === 'style').length
const showTellCount = annotations.filter((a) => a.type === 'show_tell').length
const critiqueCount = annotations.filter((a) => a.type === 'critique').length
const totalCount = passiveCount + pastProgressiveCount + weakVerbsCount + clichesCount + consistencyCount + styleCount + showTellCount + critiqueCount
const grammarCount = annotations.filter((a) => a.type === 'grammar').length
const totalCount = passiveCount + pastProgressiveCount + weakVerbsCount + clichesCount + consistencyCount + styleCount + showTellCount + critiqueCount + grammarCount
const anyActive = Boolean(analysisMode)
const sentenceStats = activeFileContent ? computeSentenceStats(activeFileContent) : null
const paragraphRhythm = activeFileContent ? computeParagraphRhythm(activeFileContent) : []
@@ -506,6 +535,14 @@ export function AnalysisToolbar(): JSX.Element {
<span>Critique</span>
{critiqueCount > 0 && <span className="toolbar-analyze-count">{critiqueCount}</span>}
</button>
<div className="context-menu-separator" />
<button
className="context-menu-item"
onClick={() => { setAnalyzeOpen(false); void runGrammar() }}
>
<span>Grammar</span>
{grammarCount > 0 && <span className="toolbar-analyze-count">{grammarCount}</span>}
</button>
</div>
)
})(),

View File

@@ -41,7 +41,7 @@ export interface ChatSession {
messages: ChatMessage[]
}
export type AnnotationType = 'passive_voice' | 'past_progressive' | 'weak_verbs' | 'cliches' | 'consistency' | 'style' | 'show_tell' | 'critique' | 'custom' | 'user_comment' | 'document_note' | 'polish'
export type AnnotationType = 'passive_voice' | 'past_progressive' | 'weak_verbs' | 'cliches' | 'consistency' | 'style' | 'show_tell' | 'critique' | 'custom' | 'user_comment' | 'document_note' | 'polish' | 'grammar'
export interface TextAnnotation {
id: string

File diff suppressed because one or more lines are too long