sentence length histogram

This commit is contained in:
TC
2026-06-10 22:37:07 +10:00
parent 9beb48129e
commit fc34480ff3
9 changed files with 558 additions and 23 deletions

View File

@@ -1,4 +1,6 @@
import { useEffect, useState } from 'react'
import { ExportDialog } from './components/Export/ExportDialog'
import type { ExportOptions } from './components/Export/ExportDialog'
import { FileTree } from './components/FileTree/FileTree'
import { currentEditorView } from './components/Editor/MarkdownEditor'
import { MarkdownEditor } from './components/Editor/MarkdownEditor'
@@ -42,6 +44,7 @@ export default function App(): JSX.Element {
() => localStorage.getItem('chatOpen') !== 'false'
)
const [settingsOpen, setSettingsOpen] = useState(false)
const [exportOpen, setExportOpen] = useState(false)
const [isFirstRun, setIsFirstRun] = useState(false)
const [focusPeek, setFocusPeek] = useState(false)
const [projectTitle, setProjectTitle] = useState('')
@@ -125,7 +128,7 @@ export default function App(): JSX.Element {
await window.api.exportPDF(activeFileContent, fileName)
}
} else if (action === 'exportProjectPDF') {
await window.api.exportProjectPDF()
setExportOpen(true)
}
})
}, [activeFilePath, isDirty, activeFileContent, fontSize])
@@ -248,6 +251,15 @@ export default function App(): JSX.Element {
}}
/>
)}
{exportOpen && (
<ExportDialog
onClose={() => setExportOpen(false)}
onExport={async (opts: ExportOptions) => {
setExportOpen(false)
await window.api.exportProjectPDF(opts)
}}
/>
)}
</div>
)
}

View File

@@ -0,0 +1,52 @@
.export-dialog {
width: 400px;
}
.export-toggles {
display: flex;
flex-direction: column;
gap: 12px;
}
.export-toggle {
display: grid;
grid-template-columns: 16px 1fr;
grid-template-rows: auto auto;
column-gap: 10px;
row-gap: 1px;
cursor: pointer;
align-items: start;
}
.export-toggle input[type="checkbox"] {
margin-top: 2px;
accent-color: var(--accent);
cursor: pointer;
}
.export-toggle-label {
font-size: 13px;
color: var(--text-primary);
}
.export-toggle-hint {
font-size: 11px;
color: var(--text-muted);
grid-column: 2;
}
.export-page-range {
display: flex;
align-items: center;
gap: 8px;
}
.export-page-input {
width: 80px;
flex: none;
}
.export-page-dash {
color: var(--text-muted);
font-size: 14px;
}

View File

@@ -0,0 +1,137 @@
import { useEffect, useRef, useState } from 'react'
import './Export.css'
export interface ExportOptions {
romanNumerals: boolean
includeCover: boolean
includeFrontMatter: boolean
pageFrom: number | null
pageTo: number | null
}
interface Props {
onClose: () => void
onExport: (opts: ExportOptions) => void
}
export function ExportDialog({ onClose, onExport }: Props): JSX.Element {
const [romanNumerals, setRomanNumerals] = useState(true)
const [includeCover, setIncludeCover] = useState(true)
const [includeFrontMatter, setIncludeFrontMatter] = useState(true)
const [pageFrom, setPageFrom] = useState('')
const [pageTo, setPageTo] = useState('')
const overlayRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handler = (e: KeyboardEvent): void => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [onClose])
const handleOverlayClick = (e: React.MouseEvent): void => {
if (e.target === overlayRef.current) onClose()
}
const handleExport = (): void => {
const from = pageFrom.trim() ? parseInt(pageFrom, 10) : null
const to = pageTo.trim() ? parseInt(pageTo, 10) : null
onExport({ romanNumerals, includeCover, includeFrontMatter, pageFrom: from, pageTo: to })
}
const pageRangeValid = (): boolean => {
const from = pageFrom.trim() ? parseInt(pageFrom, 10) : null
const to = pageTo.trim() ? parseInt(pageTo, 10) : null
if (from !== null && (isNaN(from) || from < 1)) return false
if (to !== null && (isNaN(to) || to < 1)) return false
if (from !== null && to !== null && from > to) return false
return true
}
return (
<div className="settings-overlay" ref={overlayRef} onClick={handleOverlayClick}>
<div className="settings-dialog export-dialog">
<div className="settings-header">
<span className="settings-title">Export manuscript</span>
<button className="settings-close" onClick={onClose}></button>
</div>
<div className="settings-body">
<div className="export-toggles">
<label className="export-toggle">
<input
type="checkbox"
checked={romanNumerals}
onChange={e => setRomanNumerals(e.target.checked)}
/>
<span className="export-toggle-label">Roman numeral chapter titles</span>
<span className="export-toggle-hint">I, II, III instead of file names</span>
</label>
<label className="export-toggle">
<input
type="checkbox"
checked={includeCover}
onChange={e => setIncludeCover(e.target.checked)}
/>
<span className="export-toggle-label">Include cover page</span>
<span className="export-toggle-hint">Author contact block and word count</span>
</label>
<label className="export-toggle">
<input
type="checkbox"
checked={includeFrontMatter}
onChange={e => setIncludeFrontMatter(e.target.checked)}
/>
<span className="export-toggle-label">Include front &amp; back matter</span>
<span className="export-toggle-hint">Prologue, Content Warning, Epilogue</span>
</label>
</div>
<div className="settings-field">
<span className="settings-label">Page range</span>
<div className="export-page-range">
<input
className="settings-input export-page-input"
type="number"
min={1}
placeholder="From"
value={pageFrom}
onChange={e => setPageFrom(e.target.value)}
/>
<span className="export-page-dash"></span>
<input
className="settings-input export-page-input"
type="number"
min={1}
placeholder="To"
value={pageTo}
onChange={e => setPageTo(e.target.value)}
/>
</div>
<p className="settings-hint">Leave blank to export all pages. Page numbers match the manuscript header (cover page not counted).</p>
{!pageRangeValid() && (
<p className="settings-hint settings-hint--warn">Invalid page range.</p>
)}
</div>
</div>
<div className="settings-footer">
<div />
<div className="settings-footer-actions">
<button className="settings-btn settings-btn--secondary" onClick={onClose}>Cancel</button>
<button
className="settings-btn settings-btn--primary"
onClick={handleExport}
disabled={!pageRangeValid()}
>
Export PDF
</button>
</div>
</div>
</div>
</div>
)
}

View File

@@ -43,14 +43,33 @@ function formatWordCount(n: number): string {
return String(n)
}
function computeAvgSentenceLength(text: string): number | null {
interface SentenceStats {
avg: number
stdDev: number
totalSentences: number
/** bins[i] = count of sentences with (i+1) words; bins[30] = sentences with 31+ words */
bins: number[]
outliers: Array<{ text: string; wordCount: number }>
}
function computeSentenceStats(text: string): SentenceStats | null {
const sentences = text
.split(/[.!?]+/)
.map(s => s.trim())
.filter(s => s.length > 0)
.filter(s => s.length > 0 && /\w/.test(s))
if (sentences.length === 0) return null
const totalWords = sentences.reduce((sum, s) => sum + countWords(s), 0)
return Math.round((totalWords / sentences.length) * 10) / 10
const lengths = sentences.map(s => countWords(s))
const avg = lengths.reduce((a, b) => a + b, 0) / lengths.length
const variance = lengths.reduce((a, b) => a + (b - avg) ** 2, 0) / lengths.length
const stdDev = Math.sqrt(variance)
const bins = new Array(31).fill(0)
const outliers: Array<{ text: string; wordCount: number }> = []
for (let i = 0; i < sentences.length; i++) {
const wc = lengths[i]
bins[Math.min(wc - 1, 30)]++
if (wc <= 4 || wc >= 26) outliers.push({ text: sentences[i], wordCount: wc })
}
return { avg, stdDev, totalSentences: sentences.length, bins, outliers }
}
export function AnalysisToolbar(): JSX.Element {
@@ -87,6 +106,10 @@ export function AnalysisToolbar(): JSX.Element {
const analyzeButtonRef = useRef<HTMLButtonElement>(null)
const analyzeMenuRef = useRef<HTMLDivElement>(null)
const [statsOpen, setStatsOpen] = useState(false)
const statsButtonRef = useRef<HTMLButtonElement>(null)
const statsMenuRef = useRef<HTMLDivElement>(null)
useEffect(() => {
window.api.getProjectWordCount().then(setProjectWordCount).catch(() => {})
}, [])
@@ -98,8 +121,8 @@ export function AnalysisToolbar(): JSX.Element {
}
}, [isDirty])
// Close dropdown on file change
useEffect(() => { setAnalyzeOpen(false) }, [activeFilePath])
// Close dropdowns on file change
useEffect(() => { setAnalyzeOpen(false); setStatsOpen(false) }, [activeFilePath])
// Click-outside closes dropdown
useEffect(() => {
@@ -116,13 +139,28 @@ export function AnalysisToolbar(): JSX.Element {
return () => document.removeEventListener('mousedown', handler)
}, [analyzeOpen])
// Escape closes dropdown
// Escape closes dropdowns
useEffect(() => {
if (!analyzeOpen) return
const handler = (e: KeyboardEvent): void => { if (e.key === 'Escape') setAnalyzeOpen(false) }
if (!analyzeOpen && !statsOpen) return
const handler = (e: KeyboardEvent): void => {
if (e.key === 'Escape') { setAnalyzeOpen(false); setStatsOpen(false) }
}
document.addEventListener('keydown', handler)
return () => document.removeEventListener('keydown', handler)
}, [analyzeOpen])
}, [analyzeOpen, statsOpen])
// Click-outside closes stats popover
useEffect(() => {
if (!statsOpen) return
const handler = (e: MouseEvent): void => {
if (
!statsButtonRef.current?.contains(e.target as Node) &&
!statsMenuRef.current?.contains(e.target as Node)
) setStatsOpen(false)
}
document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler)
}, [statsOpen])
const hasFile = Boolean(activeFilePath)
const isStoryBible = activeFilePath?.endsWith('Story Bible.md') ?? false
@@ -230,7 +268,8 @@ export function AnalysisToolbar(): JSX.Element {
const totalCount = passiveCount + consistencyCount + styleCount + showTellCount + critiqueCount
const anyActive = Boolean(analysisMode)
const docWordCount = countWords(activeFileContent)
const avgSentenceLen = activeFileContent ? computeAvgSentenceLength(activeFileContent) : null
const sentenceStats = activeFileContent ? computeSentenceStats(activeFileContent) : null
const avgSentenceLen = sentenceStats ? Math.round(sentenceStats.avg * 10) / 10 : null
return (
<div className="toolbar">
@@ -387,6 +426,87 @@ export function AnalysisToolbar(): JSX.Element {
{formatWordCount(selectionWordCount)} sel
</span>
)}
{activeFilePath && sentenceStats && (
<>
<button
ref={statsButtonRef}
className={`toolbar-btn toolbar-btn-stats${statsOpen ? ' active' : ''}`}
onClick={() => setStatsOpen(v => !v)}
title="Sentence length histogram"
>
</button>
{statsOpen && statsButtonRef.current && createPortal(
(() => {
const rect = statsButtonRef.current!.getBoundingClientRect()
const maxBin = Math.max(...sentenceStats.bins, 1)
const CHART_H = 60
return (
<div
ref={statsMenuRef}
className="toolbar-stats-popover"
style={{ top: rect.bottom + 4, right: window.innerWidth - rect.right }}
>
<div className="toolbar-stats-header">
<span className="toolbar-stats-title">Sentence Lengths</span>
<button className="toolbar-stats-close" onClick={() => setStatsOpen(false)}>×</button>
</div>
<div className="toolbar-stats-summary">
<span>avg <strong>{Math.round(sentenceStats.avg * 10) / 10}w</strong></span>
<span>σ <strong>{Math.round(sentenceStats.stdDev * 10) / 10}</strong></span>
<span><strong>{sentenceStats.totalSentences}</strong> sentences</span>
</div>
<div className="toolbar-stats-chart" style={{ height: CHART_H }}>
{sentenceStats.bins.map((count, i) => {
const wordCount = i + 1
const isTarget = wordCount >= 11 && wordCount <= 16
const barH = count === 0 ? 0 : Math.max(2, Math.round((count / maxBin) * CHART_H))
return (
<div
key={i}
className={`toolbar-stats-bar${isTarget ? ' target' : ''}`}
style={{ height: barH }}
title={`${wordCount === 31 ? '31+' : wordCount}w: ${count} sentence${count !== 1 ? 's' : ''}`}
/>
)
})}
</div>
<div className="toolbar-stats-axis">
<span>1</span>
<span>8</span>
<span className="toolbar-stats-axis-target">1116 </span>
<span>22</span>
<span>31+</span>
</div>
{sentenceStats.outliers.length > 0 && (
<div className="toolbar-stats-outliers">
<div className="toolbar-stats-outliers-title">
Flagged (4 or 26 words)
</div>
<div className="toolbar-stats-outliers-list">
{sentenceStats.outliers.slice(0, 8).map((o, i) => (
<div key={i} className="toolbar-stats-outlier">
<span className="toolbar-stats-outlier-wc">{o.wordCount}w</span>
<span className={`toolbar-stats-outlier-text${o.wordCount <= 4 ? ' short' : ' long'}`}>
{o.text.length > 55 ? o.text.slice(0, 55) + '…' : o.text}
</span>
</div>
))}
{sentenceStats.outliers.length > 8 && (
<div className="toolbar-stats-outlier-more">
+{sentenceStats.outliers.length - 8} more
</div>
)}
</div>
</div>
)}
</div>
)
})(),
document.body
)}
</>
)}
{activeFilePath && (
<span
className="toolbar-wordcount"

View File

@@ -200,6 +200,165 @@
flex-shrink: 0;
}
/* ── Stats button ────────────────────────────────────────────────── */
.toolbar-btn-stats {
padding: 4px 7px;
font-size: 13px;
line-height: 1;
flex-shrink: 0;
letter-spacing: -0.02em;
}
/* ── Sentence stats popover ──────────────────────────────────────── */
.toolbar-stats-popover {
position: fixed;
z-index: 1000;
background: var(--panel-bg, var(--toolbar-bg));
border: 1px solid var(--border);
border-radius: 8px;
padding: 14px 16px 12px;
width: 300px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
}
.toolbar-stats-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.toolbar-stats-title {
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-muted);
}
.toolbar-stats-close {
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
font-size: 16px;
padding: 0;
line-height: 1;
opacity: 0.6;
transition: opacity 0.15s;
}
.toolbar-stats-close:hover {
opacity: 1;
}
.toolbar-stats-summary {
font-size: 12px;
color: var(--text-secondary);
margin-bottom: 12px;
display: flex;
gap: 16px;
}
.toolbar-stats-summary strong {
color: var(--text-primary);
font-weight: 600;
}
.toolbar-stats-chart {
display: flex;
align-items: flex-end;
gap: 1px;
margin-bottom: 5px;
}
.toolbar-stats-bar {
flex: 1;
min-height: 0;
border-radius: 1px 1px 0 0;
background: var(--text-muted);
opacity: 0.3;
transition: opacity 0.1s;
cursor: default;
}
.toolbar-stats-bar.target {
background: var(--accent);
opacity: 0.65;
}
.toolbar-stats-bar:hover {
opacity: 0.9 !important;
}
.toolbar-stats-axis {
display: flex;
justify-content: space-between;
font-size: 9px;
color: var(--text-muted);
opacity: 0.55;
margin-bottom: 12px;
}
.toolbar-stats-axis-target {
color: var(--accent);
opacity: 1;
}
.toolbar-stats-outliers {
border-top: 1px solid var(--border);
padding-top: 10px;
}
.toolbar-stats-outliers-title {
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-muted);
margin-bottom: 7px;
}
.toolbar-stats-outliers-list {
max-height: 140px;
overflow-y: auto;
}
.toolbar-stats-outlier {
display: flex;
gap: 8px;
align-items: baseline;
padding: 2px 0;
}
.toolbar-stats-outlier-wc {
font-size: 10px;
color: var(--text-muted);
flex-shrink: 0;
font-variant-numeric: tabular-nums;
min-width: 22px;
}
.toolbar-stats-outlier-text {
font-size: 11px;
font-family: var(--font-serif);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-secondary);
}
.toolbar-stats-outlier-text.short {
opacity: 0.6;
}
.toolbar-stats-outlier-more {
font-size: 10px;
color: var(--text-muted);
padding: 3px 0;
opacity: 0.6;
}
/* ── Story Bible toolbar ─────────────────────────────────────────── */
.toolbar-bible-label {
font-size: 9px;

View File

@@ -1,4 +1,5 @@
import type { FileNode, AIPayload, RevisionMeta, Attachment, SearchFileResult, GlobalConfig } from './editor'
import type { ExportOptions } from '../components/Export/ExportDialog'
interface SearchOptions {
caseSensitive: boolean
@@ -38,7 +39,7 @@ declare global {
writeConfig: (updates: Partial<GlobalConfig>) => Promise<void>
pickProjectFolder: () => Promise<string | null>
exportPDF: (content: string, fileName: string) => Promise<void>
exportProjectPDF: () => Promise<void>
exportProjectPDF: (opts: ExportOptions) => Promise<void>
}
}
}