Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions components/writing/GrammarCheckPanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// QNBS-v3: PR-C1 — on-demand "Check this scene" LanguageTool panel. Self-hosted grammar/spell check
// over the active section; offset-safe apply, ignore, and add-to-dictionary. Hidden entirely when the
// active locale has no LanguageTool coverage (see useLanguageToolCheck).
import type { FC } from 'react';
import React from 'react';
import { useWriterViewContext } from '../../contexts/WriterViewContext';
import { useLanguageToolCheck } from '../../hooks/useLanguageToolCheck';
import { useTranslation } from '../../hooks/useTranslation';
import type { LanguageToolMatch } from '../../services/languageToolService';
import { Button } from '../ui/Button';

const GrammarMatchItem: FC<{
match: LanguageToolMatch;
onApply: (replacement: string) => void;
onIgnore: () => void;
onAddToDictionary: () => void;
}> = ({ match, onApply, onIgnore, onAddToDictionary }) => {
const { t } = useTranslation();
return (
<li className="rounded-sc-md border border-[var(--sc-border-subtle)] bg-[var(--sc-surface-raised)] p-2 space-y-1.5">
<div className="flex items-start justify-between gap-2">
<span className="text-[10px] uppercase tracking-wide text-[var(--sc-text-muted)]">
{match.categoryName || match.category}
</span>
<code className="text-[11px] text-[var(--sc-danger-fg)] bg-[var(--sc-danger-bg)] px-1 rounded truncate max-w-[50%]">
{match.matchedText}
</code>
</div>
<p className="text-xs text-[var(--sc-text-secondary)]">{match.message}</p>
<div className="flex flex-wrap items-center gap-1.5">
{match.replacements.length > 0 ? (
match.replacements.map((replacement) => (
<button
key={replacement}
type="button"
onClick={() => onApply(replacement)}
className="text-[11px] px-2 py-0.5 rounded-full bg-[var(--sc-accent)]/15 text-[var(--sc-text-primary)] border border-[var(--sc-border-subtle)] hover:bg-[var(--sc-accent)]/25 focus-visible:ring-2 focus-visible:ring-[var(--sc-ring-focus)]"
>
{replacement}
</button>
))
) : (
<span className="text-[11px] text-[var(--sc-text-muted)] italic">
{t('writer.grammar.noSuggestions')}
</span>
)}
</div>
<div className="flex items-center gap-2 pt-0.5">
<button
type="button"
onClick={onIgnore}
className="text-[11px] text-[var(--sc-text-muted)] hover:text-[var(--sc-text-secondary)] focus-visible:ring-2 focus-visible:ring-[var(--sc-ring-focus)] rounded"
>
{t('writer.grammar.ignore')}
</button>
{match.isSpelling && (
<button
type="button"
onClick={onAddToDictionary}
className="text-[11px] text-[var(--sc-text-muted)] hover:text-[var(--sc-text-secondary)] focus-visible:ring-2 focus-visible:ring-[var(--sc-ring-focus)] rounded"
>
{t('writer.grammar.addToDictionary')}
</button>
)}
</div>
</li>
);
};

const GrammarCheckPanel: FC = React.memo(() => {
const { t } = useTranslation();
const { selectedSectionId } = useWriterViewContext();
const {
available,
unsupportedLocale,
status,
matches,
check,
applySuggestion,
ignore,
addToDictionary,
} = useLanguageToolCheck();

// Locale has no LanguageTool support → feature is simply absent (honest, no error).
if (unsupportedLocale) {
return (
<p className="text-xs text-[var(--sc-text-muted)] px-1 py-2">
{t('writer.grammar.unsupported')}
</p>
);
}

const onCheck = () => {
if (selectedSectionId) void check(selectedSectionId);
};

return (
<section aria-label={t('writer.grammar.title')} className="space-y-3">
<div className="flex items-center justify-between gap-2">
<h3 className="text-sm font-semibold text-[var(--sc-text-primary)]">
{t('writer.grammar.title')}
</h3>
<Button
type="button"
size="sm"
variant="secondary"
onClick={onCheck}
disabled={!available || !selectedSectionId || status === 'checking'}
>
{status === 'checking' ? t('writer.grammar.checking') : t('writer.grammar.checkButton')}
</Button>
</div>

{!available && (
<p className="text-xs text-[var(--sc-warning-fg)]">{t('writer.grammar.disabled')}</p>
)}
{!selectedSectionId && available && (
<p className="text-xs text-[var(--sc-text-muted)]">{t('writer.grammar.selectScene')}</p>
)}
{status === 'offline' && (
<p className="text-xs text-[var(--sc-danger-fg)]">{t('writer.grammar.offline')}</p>
)}
{status === 'error' && (
<p className="text-xs text-[var(--sc-danger-fg)]">{t('writer.grammar.error')}</p>
)}
{status === 'ok' && matches.length === 0 && (
<p className="text-xs text-[var(--sc-success-fg)]">{t('writer.grammar.noIssues')}</p>
)}

{matches.length > 0 && (
<>
<p className="text-xs text-[var(--sc-text-muted)]">
{t('writer.grammar.issuesFound', { count: matches.length })}
</p>
<ul className="space-y-2" aria-label={t('writer.grammar.title')}>
{matches.map((match) => (
<GrammarMatchItem
Comment thread
qnbs marked this conversation as resolved.
key={`${match.offset}-${match.length}-${match.ruleId}`}
match={match}
onApply={(replacement) =>
selectedSectionId && applySuggestion(selectedSectionId, match, replacement)
}
onIgnore={() => ignore(match)}
onAddToDictionary={() => addToDictionary(match.matchedText)}
/>
))}
</ul>
</>
)}
</section>
);
});
GrammarCheckPanel.displayName = 'GrammarCheckPanel';

export { GrammarCheckPanel };
7 changes: 7 additions & 0 deletions components/writing/ToolsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Button } from '../ui/Button';
import { Card, CardContent, CardHeader } from '../ui/Card';
import { Icon } from '../ui/Icon';
import { Select } from '../ui/Select';
import { GrammarCheckPanel } from './GrammarCheckPanel';
import { ToolInputs } from './ToolInputs';

const ToolsPanel: FC = React.memo(() => {
Expand Down Expand Up @@ -243,6 +244,12 @@ const ToolsPanel: FC = React.memo(() => {
</Button>
)}
</div>

{/* QNBS-v3: PR-C1 — deterministic, self-hosted LanguageTool grammar check (no AI tokens),
separate from the AI generation flow above. Hidden for LanguageTool-unsupported locales. */}
<div className="flex-shrink-0 pt-3 mt-1 border-t border-[var(--sc-border-subtle)]">
<GrammarCheckPanel />
</div>
</CardContent>
</Card>
</div>
Expand Down
174 changes: 174 additions & 0 deletions hooks/useLanguageToolCheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
/**
* QNBS-v3: Orchestrates the on-demand "Check this scene" grammar feature (PR-C1) — the bridge between
* the pure `languageToolService` and the editor. Resolves the active locale → LanguageTool code from
* the SSOT (`getLanguageToolCode`), enforces the privacy gate (`assertLanguageToolAllowed`), runs the
* check on a section's text, and applies/ignores/dictionaries results. Heavy logic lives in the
* (tested) service; this hook only wires Redux + settings + abort lifecycle.
*/

import { useCallback, useRef, useState } from 'react';
import { useAppDispatch, useAppSelector } from '../app/hooks';
import { selectManuscript } from '../features/project/projectSelectors';
import { projectActions } from '../features/project/projectSlice';
import { settingsActions } from '../features/settings/settingsSlice';
import { getLanguageToolCode } from '../i18n/locales';
import { assertLanguageToolAllowed } from '../services/languageToolClient';
import {
applyMatchReplacement,
checkText,
type LanguageToolMatch,
} from '../services/languageToolService';
import { useTranslation } from './useTranslation';

export type LanguageToolUiStatus =
| 'idle'
| 'checking'
| 'ok'
| 'offline'
| 'error'
| 'disabled'
| 'unsupported';

export interface UseLanguageToolCheckReturn {
/** True when the active locale is LanguageTool-supported AND the integration is enabled. */
available: boolean;
/** True when the active locale has no LanguageTool coverage (feature hidden, not an error). */
unsupportedLocale: boolean;
status: LanguageToolUiStatus;
matches: LanguageToolMatch[];
/** Run a check against the given section's current content. */
check: (sectionId: string) => Promise<void>;
/** Apply one suggestion offset-safe into the section, then re-check (offsets shift). */
applySuggestion: (sectionId: string, match: LanguageToolMatch, replacement: string) => void;
/** Dismiss a single match from the current list (does not persist). */
ignore: (match: LanguageToolMatch) => void;
/** Persist a word to the user dictionary and drop its spelling matches from the list. */
addToDictionary: (word: string) => void;
/** Reset the panel. */
clear: () => void;
}

/** Stable identity for a match within one result set (offset+rule is unique per check). */
function matchKey(match: LanguageToolMatch): string {
return `${match.offset}:${match.length}:${match.ruleId}`;
}

export function useLanguageToolCheck(): UseLanguageToolCheckReturn {
const dispatch = useAppDispatch();
const { language } = useTranslation();
const manuscript = useAppSelector(selectManuscript);
const settings = useAppSelector((state) => state.settings);
const [status, setStatus] = useState<LanguageToolUiStatus>('idle');
const [matches, setMatches] = useState<LanguageToolMatch[]>([]);
const abortRef = useRef<AbortController | null>(null);

const ltCode = getLanguageToolCode(language);
const unsupportedLocale = ltCode === null;
// QNBS-v3: defensive against partial persisted settings (normalizePersistedSettings can lag a new
// nested object) — a component must never crash on a missing settings branch (project convention).
const enabled = settings?.integrations?.languageToolEnabled ?? false;
const baseUrl = settings?.integrations?.languageToolBaseUrl ?? '';
const dictionary = settings?.advancedEditor?.customDictionary ?? [];
const available = !unsupportedLocale && enabled;

const sectionContent = useCallback(
(sectionId: string): string | null => {
const section = manuscript.find((s) => s.id === sectionId);
return section ? (section.content ?? '') : null;
},
[manuscript],
);

const check = useCallback(
async (sectionId: string) => {
if (unsupportedLocale || ltCode === null) {
setStatus('unsupported');
setMatches([]);
return;
}
try {
assertLanguageToolAllowed(settings, baseUrl);
} catch {
// Disabled in settings, invalid URL, or remote blocked under local-only privacy mode.
setStatus('disabled');
setMatches([]);
return;
}
const content = sectionContent(sectionId);
if (content === null) return;

// Cancel any in-flight check so a rapid re-trigger never races.
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setStatus('checking');
try {
const result = await checkText(content, ltCode, {
baseUrl,
signal: controller.signal,
dictionary,
});
if (controller.signal.aborted) return;
setMatches(result.matches);
setStatus(result.status);
} catch {
// Aborted (superseded by a newer check) — leave the newer run to set state.
}
},
[unsupportedLocale, ltCode, settings, baseUrl, dictionary, sectionContent],
);

const applySuggestion = useCallback(
(sectionId: string, match: LanguageToolMatch, replacement: string) => {
const content = sectionContent(sectionId);
if (content === null) return;
const next = applyMatchReplacement(content, match, replacement);
if (next === content) return; // stale anchor — nothing applied
dispatch(
projectActions.updateManuscriptSection({ id: sectionId, changes: { content: next } }),
);
// Offsets of the remaining matches are now stale → re-check for a clean list.
void check(sectionId);
},
[sectionContent, dispatch, check],
);

const ignore = useCallback((match: LanguageToolMatch) => {
const key = matchKey(match);
setMatches((prev) => prev.filter((other) => matchKey(other) !== key));
}, []);

const addToDictionary = useCallback(
(word: string) => {
const trimmed = word.trim();
if (trimmed.length === 0) return;
const lower = trimmed.toLowerCase();
if (!dictionary.some((existing) => existing.toLowerCase() === lower)) {
dispatch(settingsActions.setAdvancedEditor({ customDictionary: [...dictionary, trimmed] }));
}
// Drop every spelling match for this word from the visible list.
setMatches((prev) =>
prev.filter((other) => !(other.isSpelling && other.matchedText.toLowerCase() === lower)),
);
},
[dictionary, dispatch],
);

const clear = useCallback(() => {
abortRef.current?.abort();
setMatches([]);
setStatus('idle');
}, []);

return {
available,
unsupportedLocale,
status,
matches,
check,
applySuggestion,
ignore,
addToDictionary,
clear,
};
}
16 changes: 15 additions & 1 deletion locales/ar/writer.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,19 @@
"writer.tts.start": "قراءة بصوت عالٍ",
"writer.tts.stop": "إيقاف القراءة",
"writer.versionControl.label": "الإصدارات",
"writer.versionControl.tooltip": "التحكم بالإصدارات (الفروع واللقطات)"
"writer.versionControl.tooltip": "التحكم بالإصدارات (الفروع واللقطات)",
"writer.grammar.title": "Grammar & Spelling",
"writer.grammar.checkButton": "Check this scene",
"writer.grammar.checking": "Checking…",
"writer.grammar.issuesFound": "{{count}} issues found",
"writer.grammar.noIssues": "No issues found.",
"writer.grammar.selectScene": "Select a scene to check.",
"writer.grammar.unsupported": "Grammar check isn't available for this language.",
"writer.grammar.disabled": "Enable LanguageTool in Settings → Connections to check this scene.",
"writer.grammar.offline": "Couldn't reach the LanguageTool server. Is it running?",
"writer.grammar.error": "The LanguageTool server returned an error.",
"writer.grammar.apply": "Apply",
"writer.grammar.ignore": "Ignore",
"writer.grammar.addToDictionary": "Add to dictionary",
"writer.grammar.noSuggestions": "No suggestions"
}
16 changes: 15 additions & 1 deletion locales/de/writer.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,19 @@
"writer.tts.start": "Vorlesen",
"writer.tts.stop": "Vorlesen stoppen",
"writer.versionControl.label": "Versionen",
"writer.versionControl.tooltip": "Versionskontrolle (Zweige & Schnappschüsse)"
"writer.versionControl.tooltip": "Versionskontrolle (Zweige & Schnappschüsse)",
"writer.grammar.title": "Grammatik & Rechtschreibung",
"writer.grammar.checkButton": "Diese Szene prüfen",
"writer.grammar.checking": "Prüfe…",
"writer.grammar.issuesFound": "{{count}} Probleme gefunden",
"writer.grammar.noIssues": "Keine Probleme gefunden.",
"writer.grammar.selectScene": "Wähle eine Szene zum Prüfen.",
"writer.grammar.unsupported": "Die Grammatikprüfung ist für diese Sprache nicht verfügbar.",
"writer.grammar.disabled": "Aktiviere LanguageTool in Einstellungen → Verbindungen, um diese Szene zu prüfen.",
"writer.grammar.offline": "LanguageTool-Server nicht erreichbar. Läuft er?",
"writer.grammar.error": "Der LanguageTool-Server hat einen Fehler zurückgegeben.",
"writer.grammar.apply": "Übernehmen",
"writer.grammar.ignore": "Ignorieren",
"writer.grammar.addToDictionary": "Zum Wörterbuch hinzufügen",
"writer.grammar.noSuggestions": "Keine Vorschläge"
}
Loading
Loading