Compare commits
10 Commits
833385c8d8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2868a6152b | |||
| 5cdc3efeef | |||
| ff40d424aa | |||
| 7c0b993d7e | |||
| 78d3bc2d82 | |||
| 2472860966 | |||
| f205332d24 | |||
| 8c10ba7731 | |||
| 5bc045ad40 | |||
| 199e909778 |
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "hohoff-editor",
|
"name": "hohoff-editor",
|
||||||
"version": "1.22.0",
|
"version": "1.24.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "hohoff-editor",
|
"name": "hohoff-editor",
|
||||||
"version": "1.22.0",
|
"version": "1.24.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/sdk": "^0.29.0",
|
"@anthropic-ai/sdk": "^0.29.0",
|
||||||
"@codemirror/commands": "^6.6.0",
|
"@codemirror/commands": "^6.6.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hohoff-editor",
|
"name": "hohoff-editor",
|
||||||
"version": "1.22.0",
|
"version": "1.24.0",
|
||||||
"description": "Novel editor for Hohoff",
|
"description": "Novel editor for Hohoff",
|
||||||
"main": "out/main/index.js",
|
"main": "out/main/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
74
src/main/grammarService.ts
Normal file
74
src/main/grammarService.ts
Normal 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()
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -137,6 +137,12 @@ function buildAppMenu(win: BrowserWindow): void {
|
|||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ role: 'selectAll' },
|
{ role: 'selectAll' },
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Clean Up Spacing',
|
||||||
|
accelerator: 'CmdOrCtrl+Shift+K',
|
||||||
|
click: () => send(win, 'cleanupSpacing')
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
{
|
{
|
||||||
label: 'Find / Replace',
|
label: 'Find / Replace',
|
||||||
accelerator: 'CmdOrCtrl+F',
|
accelerator: 'CmdOrCtrl+F',
|
||||||
|
|||||||
@@ -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 { 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 type { SearchOptions, ProjectConfig } from './fileSystem'
|
||||||
import { streamMessage, resetClient } from './aiService'
|
import { streamMessage, resetClient } from './aiService'
|
||||||
|
import { checkGrammar } from './grammarService'
|
||||||
|
import type { GrammarMatch } from './grammarService'
|
||||||
import { onWordSnapshot, flushTelemetry } from './telemetry'
|
import { onWordSnapshot, flushTelemetry } from './telemetry'
|
||||||
import type { AIPayload, Attachment, Submission } from '../renderer/types/editor'
|
import type { AIPayload, Attachment, Submission } from '../renderer/types/editor'
|
||||||
import { readGlobalConfig, writeGlobalConfig, getProjectTitle, addRecentProject, updateRecentProjectTitle } from './globalConfig'
|
import { readGlobalConfig, writeGlobalConfig, getProjectTitle, addRecentProject, updateRecentProjectTitle } from './globalConfig'
|
||||||
@@ -170,6 +172,10 @@ export function registerIpcHandlers(): void {
|
|||||||
await writeSubmissions(data)
|
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) => {
|
ipcMain.handle('ai:streamMessage', async (event, payload: AIPayload) => {
|
||||||
try {
|
try {
|
||||||
const storyBibleContent = (await readStoryBibleFile()) ?? undefined
|
const storyBibleContent = (await readStoryBibleFile()) ?? undefined
|
||||||
@@ -385,8 +391,14 @@ export function registerIpcHandlers(): void {
|
|||||||
showChapterTitle: boolean
|
showChapterTitle: boolean
|
||||||
includeCover: boolean
|
includeCover: boolean
|
||||||
includeFrontMatter: boolean
|
includeFrontMatter: boolean
|
||||||
|
includePartSeparators: boolean
|
||||||
pageFrom: number | null
|
pageFrom: number | null
|
||||||
pageTo: number | null
|
pageTo: number | null
|
||||||
|
font: 'courier' | 'times' | 'georgia'
|
||||||
|
fontSize: number
|
||||||
|
pageSize: 'letter' | 'a4'
|
||||||
|
titleOnFirstPage: boolean
|
||||||
|
boldHeadings: boolean
|
||||||
}): Promise<void> => {
|
}): Promise<void> => {
|
||||||
const win = BrowserWindow.fromWebContents(event.sender)
|
const win = BrowserWindow.fromWebContents(event.sender)
|
||||||
const projectCfg = await readProjectConfig()
|
const projectCfg = await readProjectConfig()
|
||||||
@@ -432,11 +444,19 @@ export function registerIpcHandlers(): void {
|
|||||||
authorEmail,
|
authorEmail,
|
||||||
].filter(Boolean)
|
].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 = `
|
const coverCSS = `
|
||||||
@page { size: letter; }
|
@page { size: ${pageSizeCss}; }
|
||||||
body {
|
body {
|
||||||
font-family: "Courier New", Courier, monospace;
|
font-family: ${fontFamily};
|
||||||
font-size: 12pt;
|
font-size: ${opts.fontSize}pt;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
color: #000;
|
color: #000;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
@@ -463,7 +483,7 @@ export function registerIpcHandlers(): void {
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
line-height: 2;
|
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-by { margin: 0; }
|
||||||
.cover-byline{ margin: 0; }
|
.cover-byline{ margin: 0; }
|
||||||
`
|
`
|
||||||
@@ -503,6 +523,7 @@ export function registerIpcHandlers(): void {
|
|||||||
// Body chapters = docs inside a Part subdirectory
|
// Body chapters = docs inside a Part subdirectory
|
||||||
let currentPart: string | null = null
|
let currentPart: string | null = null
|
||||||
let chapterIndex = 0
|
let chapterIndex = 0
|
||||||
|
let firstChapterDone = false
|
||||||
|
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
const slashIdx = doc.relativePath.indexOf('/')
|
const slashIdx = doc.relativePath.indexOf('/')
|
||||||
@@ -511,14 +532,8 @@ export function registerIpcHandlers(): void {
|
|||||||
|
|
||||||
if (isFrontMatter && !opts.includeFrontMatter) continue
|
if (isFrontMatter && !opts.includeFrontMatter) continue
|
||||||
|
|
||||||
if (partName !== null && partName !== currentPart) {
|
const isNewPart = partName !== null && partName !== currentPart
|
||||||
currentPart = partName
|
if (isNewPart) currentPart = partName
|
||||||
const safe = partName.replace(/&/g, '&').replace(/</g, '<')
|
|
||||||
sections.push({
|
|
||||||
title: partName,
|
|
||||||
bodyHtml: `<div class="part-page"><div class="part-title">${safe}</div></div>`
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileName = doc.relativePath.split('/').pop()?.replace(/\.md$/, '') ?? doc.relativePath
|
const fileName = doc.relativePath.split('/').pop()?.replace(/\.md$/, '') ?? doc.relativePath
|
||||||
let headerTitle: string
|
let headerTitle: string
|
||||||
@@ -546,17 +561,26 @@ export function registerIpcHandlers(): void {
|
|||||||
headerTitle = fileName
|
headerTitle = fileName
|
||||||
}
|
}
|
||||||
const contentHtml = await marked(normalize(doc.content))
|
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({
|
sections.push({
|
||||||
title: headerTitle,
|
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).
|
// CSS shared by chapter/part sections — cover page uses its own CSS (set above).
|
||||||
const pageCSS = `
|
const pageCSS = `
|
||||||
@page { size: letter; }
|
@page { size: ${pageSizeCss}; }
|
||||||
body { font-family: "Courier New", Courier, monospace; font-size: 12pt; line-height: 2; color: #000; margin: 0; padding: 0; }
|
body { font-family: ${fontFamily}; font-size: ${opts.fontSize}pt; 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; }
|
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; }
|
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; }
|
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; }
|
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; }
|
ul, ol { margin: 0 0 0 0.5in; }
|
||||||
li { margin: 0; }
|
li { margin: 0; }
|
||||||
.chapter { padding-top: 2.5in; }
|
.chapter { padding-top: 2.5in; }
|
||||||
.part-page { padding-top: 3.5in; text-align: center; }
|
.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; }
|
||||||
.part-title { font-family: "Courier New", Courier, monospace; font-size: 12pt; text-transform: uppercase; }
|
|
||||||
`
|
`
|
||||||
|
|
||||||
// Print each section to its own PDF buffer. Cover page uses its own CSS;
|
// Print each section to its own PDF buffer. Cover page uses its own CSS;
|
||||||
@@ -585,7 +608,7 @@ export function registerIpcHandlers(): void {
|
|||||||
try {
|
try {
|
||||||
await offscreen.loadFile(tempPath)
|
await offscreen.loadFile(tempPath)
|
||||||
const buf = await offscreen.webContents.printToPDF({
|
const buf = await offscreen.webContents.printToPDF({
|
||||||
pageSize: 'Letter',
|
pageSize: opts.pageSize === 'a4' ? 'A4' : 'Letter',
|
||||||
displayHeaderFooter: false,
|
displayHeaderFooter: false,
|
||||||
margins: { marginType: 'custom', top: 1.0, bottom: 1.0, left: 1.0, right: 1.0 }
|
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
|
// Merge all section PDFs into one document, tracking which section each page
|
||||||
// belongs to so we can stamp the correct running header on it.
|
// belongs to so we can stamp the correct running header on it.
|
||||||
const mergedPdf = await PDFDocument.create()
|
const mergedPdf = await PDFDocument.create()
|
||||||
const courier = await mergedPdf.embedFont(StandardFonts.Courier)
|
const headerStandardFont = opts.font === 'courier' ? StandardFonts.Courier : StandardFonts.TimesRoman
|
||||||
// pageOwners[i] tracks the section title and whether the page is a cover page
|
const headerFont = await mergedPdf.embedFont(headerStandardFont)
|
||||||
const pageOwners: { title: string; isCover: boolean }[] = []
|
// 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) {
|
for (const { title, buffer, isCover } of sectionPdfs) {
|
||||||
const srcPdf = await PDFDocument.load(buffer)
|
const srcPdf = await PDFDocument.load(buffer)
|
||||||
const copied = await mergedPdf.copyPages(srcPdf, srcPdf.getPageIndices())
|
const copied = await mergedPdf.copyPages(srcPdf, srcPdf.getPageIndices())
|
||||||
for (const page of copied) {
|
for (const [pageIdx, page] of copied.entries()) {
|
||||||
mergedPdf.addPage(page)
|
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.
|
// Page numbers count from 1 starting with the first non-cover page.
|
||||||
const allPages = mergedPdf.getPages()
|
const allPages = mergedPdf.getPages()
|
||||||
let bodyPageNum = 0
|
let bodyPageNum = 0
|
||||||
for (let i = 0; i < allPages.length; i++) {
|
for (let i = 0; i < allPages.length; i++) {
|
||||||
if (pageOwners[i].isCover) continue // no header/number on cover page
|
if (pageOwners[i].isCover) continue // no header/number on cover page
|
||||||
bodyPageNum++
|
bodyPageNum++
|
||||||
|
if (pageOwners[i].isSectionOpener) continue // no running header on chapter/part opener pages
|
||||||
const page = allPages[i]
|
const page = allPages[i]
|
||||||
const { width, height } = page.getSize()
|
const { width, height } = page.getSize()
|
||||||
const chapterUpper = pageOwners[i].title.toUpperCase()
|
const chapterUpper = pageOwners[i].title.toUpperCase()
|
||||||
const headerText = `${projectTitle} / ${chapterUpper} / ${bodyPageNum}`
|
const headerText = `${projectTitle} / ${chapterUpper} / ${bodyPageNum}`
|
||||||
const fontSize = 11
|
const fontSize = 11
|
||||||
const textWidth = courier.widthOfTextAtSize(headerText, fontSize)
|
const textWidth = headerFont.widthOfTextAtSize(headerText, fontSize)
|
||||||
page.drawText(headerText, {
|
page.drawText(headerText, {
|
||||||
x: width - 72 - textWidth, // 1 in from right edge (72pt = 1in)
|
x: width - 72 - textWidth, // 1 in from right edge (72pt = 1in)
|
||||||
y: height - 36, // 0.5 in from top edge (36pt = 0.5in)
|
y: height - 36, // 0.5 in from top edge (36pt = 0.5in)
|
||||||
size: fontSize,
|
size: fontSize,
|
||||||
font: courier,
|
font: headerFont,
|
||||||
color: rgb(0, 0, 0)
|
color: rgb(0, 0, 0)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -145,4 +145,7 @@ contextBridge.exposeInMainWorld('api', {
|
|||||||
|
|
||||||
writeSubmissions: (data: Submission[]): Promise<void> =>
|
writeSubmissions: (data: Submission[]): Promise<void> =>
|
||||||
ipcRenderer.invoke('submissions:write', data),
|
ipcRenderer.invoke('submissions:write', data),
|
||||||
|
|
||||||
|
checkGrammar: (text: string): Promise<import('../main/grammarService').GrammarMatch[]> =>
|
||||||
|
ipcRenderer.invoke('grammar:check', text),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { ExportDialog } from './components/Export/ExportDialog'
|
import { ExportDialog } from './components/Export/ExportDialog'
|
||||||
import type { ExportOptions } from './components/Export/ExportDialog'
|
import type { ExportOptions } from './components/Export/ExportDialog'
|
||||||
import { FileTree } from './components/FileTree/FileTree'
|
import { FileTree } from './components/FileTree/FileTree'
|
||||||
@@ -58,6 +58,7 @@ export default function App(): JSX.Element {
|
|||||||
const [isFirstRun, setIsFirstRun] = useState(false)
|
const [isFirstRun, setIsFirstRun] = useState(false)
|
||||||
const [focusPeek, setFocusPeek] = useState(false)
|
const [focusPeek, setFocusPeek] = useState(false)
|
||||||
const [projectTitle, setProjectTitle] = useState('')
|
const [projectTitle, setProjectTitle] = useState('')
|
||||||
|
const menuHandlerRef = useRef<((action: string) => Promise<void>) | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!focusMode) {
|
if (!focusMode) {
|
||||||
@@ -99,8 +100,7 @@ export default function App(): JSX.Element {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// Handle menu actions sent from the main process
|
// Handle menu actions sent from the main process
|
||||||
useEffect(() => {
|
menuHandlerRef.current = async (action: string): Promise<void> => {
|
||||||
return window.api.onMenuAction(async (action) => {
|
|
||||||
if (action === 'save') {
|
if (action === 'save') {
|
||||||
if (activeFilePath && isDirty) {
|
if (activeFilePath && isDirty) {
|
||||||
await window.api.writeFile(activeFilePath, activeFileContent)
|
await window.api.writeFile(activeFilePath, activeFileContent)
|
||||||
@@ -139,9 +139,27 @@ export default function App(): JSX.Element {
|
|||||||
}
|
}
|
||||||
} else if (action === 'exportProjectPDF') {
|
} else if (action === 'exportProjectPDF') {
|
||||||
setExportOpen(true)
|
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'
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
}, [activeFilePath, isDirty, activeFileContent, fontSize])
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return window.api.onMenuAction((action) => menuHandlerRef.current?.(action))
|
||||||
|
}, [])
|
||||||
|
|
||||||
// Handle Cmd+S / Ctrl+S and Cmd+Shift+F / Ctrl+Shift+F
|
// Handle Cmd+S / Ctrl+S and Cmd+Shift+F / Ctrl+Shift+F
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -563,6 +563,11 @@ function buildTheme(fontSize: number, dark: boolean, focusMode = false): ReturnT
|
|||||||
backgroundColor: 'rgba(240, 100, 180, 0.15)',
|
backgroundColor: 'rgba(240, 100, 180, 0.15)',
|
||||||
borderBottom: '2px solid rgba(240, 100, 180, 0.65)',
|
borderBottom: '2px solid rgba(240, 100, 180, 0.65)',
|
||||||
borderRadius: '2px'
|
borderRadius: '2px'
|
||||||
|
},
|
||||||
|
'.annotation-grammar': {
|
||||||
|
backgroundColor: 'rgba(220, 60, 60, 0.12)',
|
||||||
|
borderBottom: '2px solid rgba(220, 60, 60, 0.75)',
|
||||||
|
borderRadius: '2px'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{ dark }
|
{ dark }
|
||||||
|
|||||||
@@ -35,6 +35,15 @@
|
|||||||
grid-column: 2;
|
grid-column: 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.export-format-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.export-format-field {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
.export-page-range {
|
.export-page-range {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -6,18 +6,24 @@ export interface ExportOptions {
|
|||||||
showChapterTitle: boolean
|
showChapterTitle: boolean
|
||||||
includeCover: boolean
|
includeCover: boolean
|
||||||
includeFrontMatter: boolean
|
includeFrontMatter: boolean
|
||||||
|
includePartSeparators: boolean
|
||||||
pageFrom: number | null
|
pageFrom: number | null
|
||||||
pageTo: number | null
|
pageTo: number | null
|
||||||
|
font: 'courier' | 'times' | 'georgia'
|
||||||
|
fontSize: number
|
||||||
|
pageSize: 'letter' | 'a4'
|
||||||
|
titleOnFirstPage: boolean
|
||||||
|
boldHeadings: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const STORAGE_KEY = 'exportDialogPrefs'
|
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 {
|
try {
|
||||||
const raw = localStorage.getItem(STORAGE_KEY)
|
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 */ }
|
} 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 {
|
interface Props {
|
||||||
@@ -31,6 +37,12 @@ export function ExportDialog({ onClose, onExport }: Props): JSX.Element {
|
|||||||
const [showChapterTitle, setShowChapterTitle] = useState(prefs.showChapterTitle)
|
const [showChapterTitle, setShowChapterTitle] = useState(prefs.showChapterTitle)
|
||||||
const [includeCover, setIncludeCover] = useState(prefs.includeCover)
|
const [includeCover, setIncludeCover] = useState(prefs.includeCover)
|
||||||
const [includeFrontMatter, setIncludeFrontMatter] = useState(prefs.includeFrontMatter)
|
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 [pageFrom, setPageFrom] = useState('')
|
||||||
const [pageTo, setPageTo] = useState('')
|
const [pageTo, setPageTo] = useState('')
|
||||||
const overlayRef = useRef<HTMLDivElement>(null)
|
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 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))
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleExport = (): void => {
|
const handleExport = (): void => {
|
||||||
const from = pageFrom.trim() ? parseInt(pageFrom, 10) : null
|
const from = pageFrom.trim() ? parseInt(pageFrom, 10) : null
|
||||||
const to = pageTo.trim() ? parseInt(pageTo, 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 => {
|
const pageRangeValid = (): boolean => {
|
||||||
@@ -116,6 +128,77 @@ export function ExportDialog({ onClose, onExport }: Props): JSX.Element {
|
|||||||
<span className="export-toggle-label">Include front & back matter</span>
|
<span className="export-toggle-label">Include front & back matter</span>
|
||||||
<span className="export-toggle-hint">Prologue, Content Warning, Epilogue</span>
|
<span className="export-toggle-hint">Prologue, Content Warning, Epilogue</span>
|
||||||
</label>
|
</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>
|
||||||
|
|
||||||
<div className="settings-field">
|
<div className="settings-field">
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ function badgeColor(type: TextAnnotation['type']): string {
|
|||||||
case 'user_comment': return 'rgba(240, 100, 180, 0.85)'
|
case 'user_comment': return 'rgba(240, 100, 180, 0.85)'
|
||||||
case 'document_note': return 'rgba(80, 180, 240, 0.85)'
|
case 'document_note': return 'rgba(80, 180, 240, 0.85)'
|
||||||
case 'polish': return 'rgba(55, 138, 221, 0.75)'
|
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 [activeKey, setActiveKey] = useState<string | null>(null)
|
||||||
const [tooltip, setTooltip] = useState<TooltipState | null>(null)
|
const [tooltip, setTooltip] = useState<TooltipState | null>(null)
|
||||||
const { setAnnotations, clearAnnotations } = useEditorStore()
|
const { setAnnotations, clearAnnotations } = useEditorStore()
|
||||||
|
const widgetRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
const dims = Object.entries(score.dimensions) as [string, PolishDimension][]
|
const dims = Object.entries(score.dimensions) as [string, PolishDimension][]
|
||||||
|
|
||||||
function handleDimClick(key: string, dim: PolishDimension): void {
|
function handleDimClick(key: string, dim: PolishDimension): void {
|
||||||
if (activeKey === key) {
|
if (activeKey === key) {
|
||||||
setActiveKey(null)
|
setActiveKey(null)
|
||||||
clearAnnotations()
|
setAnnotations([])
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (dim.matches.length === 0) return
|
if (dim.matches.length === 0) return
|
||||||
@@ -326,8 +328,21 @@ function PolishMeter({ score }: { score: PolishScore }): JSX.Element {
|
|||||||
}
|
}
|
||||||
}, [score.overall])
|
}, [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 (
|
return (
|
||||||
<div className="pm-widget">
|
<div ref={widgetRef} className="pm-widget">
|
||||||
<div className="pm-header">
|
<div className="pm-header">
|
||||||
<span className="pm-title">Polish</span>
|
<span className="pm-title">Polish</span>
|
||||||
<span className="pm-overall" style={{ color: scoreColor(score.overall) }}>{score.overall}</span>
|
<span className="pm-overall" style={{ color: scoreColor(score.overall) }}>{score.overall}</span>
|
||||||
|
|||||||
@@ -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 passiveCount = annotations.filter((a) => a.type === 'passive_voice').length
|
||||||
const pastProgressiveCount = annotations.filter((a) => a.type === 'past_progressive').length
|
const pastProgressiveCount = annotations.filter((a) => a.type === 'past_progressive').length
|
||||||
const weakVerbsCount = annotations.filter((a) => a.type === 'weak_verbs').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 styleCount = annotations.filter((a) => a.type === 'style').length
|
||||||
const showTellCount = annotations.filter((a) => a.type === 'show_tell').length
|
const showTellCount = annotations.filter((a) => a.type === 'show_tell').length
|
||||||
const critiqueCount = annotations.filter((a) => a.type === 'critique').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 anyActive = Boolean(analysisMode)
|
||||||
const sentenceStats = activeFileContent ? computeSentenceStats(activeFileContent) : null
|
const sentenceStats = activeFileContent ? computeSentenceStats(activeFileContent) : null
|
||||||
const paragraphRhythm = activeFileContent ? computeParagraphRhythm(activeFileContent) : []
|
const paragraphRhythm = activeFileContent ? computeParagraphRhythm(activeFileContent) : []
|
||||||
@@ -506,6 +535,14 @@ export function AnalysisToolbar(): JSX.Element {
|
|||||||
<span>Critique</span>
|
<span>Critique</span>
|
||||||
{critiqueCount > 0 && <span className="toolbar-analyze-count">{critiqueCount}</span>}
|
{critiqueCount > 0 && <span className="toolbar-analyze-count">{critiqueCount}</span>}
|
||||||
</button>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
})(),
|
})(),
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ export interface ChatSession {
|
|||||||
messages: ChatMessage[]
|
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 {
|
export interface TextAnnotation {
|
||||||
id: string
|
id: string
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user