-
Notifications
You must be signed in to change notification settings - Fork 1
feat(languagetool): 'Check this scene' grammar panel (PR-C1 MVP) #236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| 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 }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.