display word counts

This commit is contained in:
2026-02-21 09:44:02 +10:00
parent e21d1c7b58
commit 9cf57fe508
7 changed files with 96 additions and 4 deletions

View File

@@ -69,3 +69,33 @@ export async function writeMarkdownFile(filePath: string, content: string): Prom
assertInDraftRoot(filePath) assertInDraftRoot(filePath)
await writeFile(filePath, content, 'utf-8') await writeFile(filePath, content, 'utf-8')
} }
function countWords(text: string): number {
return text.trim() === '' ? 0 : text.trim().split(/\s+/).length
}
async function collectMarkdownPaths(dir: string): Promise<string[]> {
const entries = await readdir(dir, { withFileTypes: true })
const paths: string[] = []
for (const entry of entries) {
if (entry.name.startsWith('.')) continue
const fullPath = join(dir, entry.name)
if (entry.isDirectory()) {
const nested = await collectMarkdownPaths(fullPath)
paths.push(...nested)
} else if (entry.name.endsWith('.md')) {
paths.push(fullPath)
}
}
return paths
}
export async function getProjectWordCount(): Promise<number> {
const paths = await collectMarkdownPaths(DRAFT_ROOT)
let total = 0
for (const p of paths) {
const content = await readFile(p, 'utf-8')
total += countWords(content)
}
return total
}

View File

@@ -1,5 +1,5 @@
import { ipcMain } from 'electron' import { ipcMain } from 'electron'
import { listDraftFiles, readMarkdownFile, writeMarkdownFile } from './fileSystem' import { listDraftFiles, readMarkdownFile, writeMarkdownFile, getProjectWordCount } from './fileSystem'
import { streamMessage } from './aiService' import { streamMessage } from './aiService'
import type { AIPayload } from '../renderer/types/editor' import type { AIPayload } from '../renderer/types/editor'
@@ -16,6 +16,10 @@ export function registerIpcHandlers(): void {
await writeMarkdownFile(filePath, content) await writeMarkdownFile(filePath, content)
}) })
ipcMain.handle('fs:projectWordCount', async () => {
return await getProjectWordCount()
})
ipcMain.handle('ai:streamMessage', async (event, payload: AIPayload) => { ipcMain.handle('ai:streamMessage', async (event, payload: AIPayload) => {
try { try {
await streamMessage(payload, (chunk: string) => { await streamMessage(payload, (chunk: string) => {

View File

@@ -43,5 +43,7 @@ contextBridge.exposeInMainWorld('api', {
ipcRenderer.removeAllListeners('ai:chunk') ipcRenderer.removeAllListeners('ai:chunk')
ipcRenderer.removeAllListeners('ai:done') ipcRenderer.removeAllListeners('ai:done')
ipcRenderer.removeAllListeners('ai:error') ipcRenderer.removeAllListeners('ai:error')
} },
getProjectWordCount: (): Promise<number> => ipcRenderer.invoke('fs:projectWordCount')
}) })

View File

@@ -1,8 +1,18 @@
import { useEffect } from 'react'
import { useEditorStore } from '../../store/editorStore' import { useEditorStore } from '../../store/editorStore'
import { detectPassiveVoice } from '../../utils/passiveVoice' import { detectPassiveVoice } from '../../utils/passiveVoice'
import { parseAnnotationsFromAIResponse } from '../../utils/annotationParser' import { parseAnnotationsFromAIResponse } from '../../utils/annotationParser'
import './Toolbar.css' import './Toolbar.css'
function countWords(text: string): number {
return text.trim() === '' ? 0 : text.trim().split(/\s+/).length
}
function formatWordCount(n: number): string {
if (n >= 1000) return `${(n / 1000).toFixed(1)}k`
return String(n)
}
export function AnalysisToolbar(): JSX.Element { export function AnalysisToolbar(): JSX.Element {
const { const {
activeFilePath, activeFilePath,
@@ -19,9 +29,22 @@ export function AnalysisToolbar(): JSX.Element {
appendToLastAssistantMessage, appendToLastAssistantMessage,
setAILoading, setAILoading,
setAIError, setAIError,
chatHistory chatHistory,
projectWordCount,
setProjectWordCount
} = useEditorStore() } = useEditorStore()
useEffect(() => {
window.api.getProjectWordCount().then(setProjectWordCount).catch(() => {})
}, [])
// Refresh project count after a save (isDirty transitions from true → false)
useEffect(() => {
if (!isDirty) {
window.api.getProjectWordCount().then(setProjectWordCount).catch(() => {})
}
}, [isDirty])
const hasFile = Boolean(activeFilePath) const hasFile = Boolean(activeFilePath)
const runPassiveVoice = (): void => { const runPassiveVoice = (): void => {
@@ -78,6 +101,7 @@ export function AnalysisToolbar(): JSX.Element {
const passiveCount = annotations.filter((a) => a.type === 'passive_voice').length const passiveCount = annotations.filter((a) => a.type === 'passive_voice').length
const otherCount = annotations.filter((a) => a.type !== 'passive_voice').length const otherCount = annotations.filter((a) => a.type !== 'passive_voice').length
const docWordCount = countWords(activeFileContent)
return ( return (
<div className="toolbar"> <div className="toolbar">
@@ -130,6 +154,16 @@ export function AnalysisToolbar(): JSX.Element {
</div> </div>
<div className="toolbar-right"> <div className="toolbar-right">
{activeFilePath && (
<span
className="toolbar-wordcount"
title={`This document: ${docWordCount.toLocaleString()} words · Entire project: ${projectWordCount.toLocaleString()} words`}
>
{formatWordCount(docWordCount)}
<span className="toolbar-wordcount-sep">/</span>
{formatWordCount(projectWordCount)}
</span>
)}
{isDirty && ( {isDirty && (
<span className="toolbar-dirty" title="Unsaved changes — press Cmd+S to save"> <span className="toolbar-dirty" title="Unsaved changes — press Cmd+S to save">

View File

@@ -95,3 +95,17 @@
white-space: nowrap; white-space: nowrap;
max-width: 260px; max-width: 260px;
} }
.toolbar-wordcount {
color: var(--text-muted);
font-size: 11px;
font-family: var(--font-sans);
white-space: nowrap;
flex-shrink: 0;
cursor: default;
}
.toolbar-wordcount-sep {
margin: 0 3px;
opacity: 0.5;
}

View File

@@ -34,6 +34,10 @@ interface EditorState {
// Analysis mode // Analysis mode
analysisMode: AnalysisMode analysisMode: AnalysisMode
setAnalysisMode: (mode: AnalysisMode) => void setAnalysisMode: (mode: AnalysisMode) => void
// Word counts
projectWordCount: number
setProjectWordCount: (count: number) => void
} }
export const useEditorStore = create<EditorState>((set, get) => ({ export const useEditorStore = create<EditorState>((set, get) => ({
@@ -115,5 +119,8 @@ export const useEditorStore = create<EditorState>((set, get) => ({
clearAnnotations: () => set({ annotations: [], analysisMode: 'none' }), clearAnnotations: () => set({ annotations: [], analysisMode: 'none' }),
analysisMode: 'none', analysisMode: 'none',
setAnalysisMode: (analysisMode) => set({ analysisMode }) setAnalysisMode: (analysisMode) => set({ analysisMode }),
projectWordCount: 0,
setProjectWordCount: (projectWordCount) => set({ projectWordCount })
})) }))

View File

@@ -11,6 +11,7 @@ declare global {
onChunk: (chunk: string) => void onChunk: (chunk: string) => void
) => Promise<void> ) => Promise<void>
removeAIListener: () => void removeAIListener: () => void
getProjectWordCount: () => Promise<number>
} }
} }
} }