opengrammer
v1.3.6
Published
A grammar checker npm package that scans text for grammar mistakes and provides suggestions with visual indicators
Downloads
43
Maintainers
Readme
OpenGrammer
A JavaScript npm package that scans text for grammar mistakes using custom rules and provides visual indicators with hover tooltips showing correction suggestions.
This is a basic grammer detection and currently only in English. Need a larger dictonary for nouns and such any suggestions will be much loved :)
Features
- Custom grammar rule engine for detecting common mistakes
- HTML formatting with blue wavy underlines for errors
- Interactive tooltips with suggestions on hover
- Zero external dependencies (for core functionality)
- Easy integration into web projects, React, and TipTap editors
- Context-aware checking to reduce false positives
Installation
npm install opengrammerFor TipTap integration, also install:
npm install opengrammer @tiptap/pmQuick Start
HTML / ContentEditable (Simplest)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="node_modules/opengrammer/src/styles.css">
</head>
<body>
<div id="editor" contenteditable>Their going to the store. Its a nice day.</div>
<script type="module">
import { GrammerCheckContent } from './node_modules/opengrammer/src/index.js';
GrammerCheckContent('#editor', {
debug: false // Set to true for debug logs
});
</script>
</body>
</html>That's it! Grammar checking happens automatically as you type.
React
import { useEffect, useRef } from 'react';
import { GrammerCheckContent } from 'opengrammer';
import 'opengrammer/styles';
function GrammarEditor() {
const editorRef = useRef(null);
const checkerRef = useRef(null);
useEffect(() => {
if (editorRef.current) {
checkerRef.current = GrammerCheckContent(editorRef.current, {
debounceMs: 1000,
autoCheckOnLoad: true,
autoCheckOnBlur: true,
debug: false
});
return () => {
checkerRef.current?.destroy();
};
}
}, []);
return (
<div
ref={editorRef}
contentEditable
style={{
minHeight: '150px',
padding: '12px',
border: '2px solid #e5e7eb',
borderRadius: '8px'
}}
>
Type your text here...
</div>
);
}See REACT.md for more React examples.
TipTap
import { useEffect, useRef } from 'react';
import { useEditor } from '@tiptap/react';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { GrammerCheckContentTipTap } from 'opengrammer';
import 'opengrammer/styles';
function TipTapEditor() {
const checkerRef = useRef(null);
const editor = useEditor({
extensions: [
// your extensions
],
content: '<p>Their going to the store. Its a nice day.</p>'
});
useEffect(() => {
if (editor) {
checkerRef.current = GrammerCheckContentTipTap(editor, {
decorations: { Decoration, DecorationSet },
debounceMs: 1000,
autoCheckOnLoad: true,
autoCheckOnBlur: true,
debug: false
});
return () => {
checkerRef.current?.destroy();
};
}
}, [editor]);
return <EditorContent editor={editor} />;
}See TIPTAP.md for complete TipTap integration guide.
Core API
checkGrammar(text)
Checks text for grammar errors and returns an array of error objects.
Parameters:
text(string): The text to check
Returns:
- Array of error objects, each containing:
id(string): Unique identifier for the errorstartIndex(number): Start position in the original textendIndex(number): End position in the original texttext(string): The incorrect text segmentsuggestions(Array): Array of suggested correctionsmessage(string): Explanation of the error
Example:
import { checkGrammar } from 'opengrammer';
const errors = checkGrammar("Their going there.");
// Returns:
// [
// {
// id: "error-0",
// startIndex: 0,
// endIndex: 5,
// text: "Their",
// suggestions: ["there", "they're"],
// message: "Check usage of 'there', 'their', or 'they're'"
// }
// ]formatText(text, errors)
Formats text with errors wrapped in HTML <span> tags.
Parameters:
text(string): Original texterrors(Array): Array of error objects fromcheckGrammar
Returns:
- HTML string with errors wrapped in
<span class="grammar-error">tags
Example:
import { checkGrammar, formatText } from 'opengrammer';
const errors = checkGrammar("Their going there.");
const formatted = formatText("Their going there.", errors);
// Returns: '<span class="grammar-error" data-error-id="error-0" ...>Their</span> going there.'checkAndFormat(text)
Convenience function that checks grammar and formats text in one step.
Parameters:
text(string): Text to check and format
Returns:
- Object with:
errors(Array): Array of error objectsformatted(string): HTML string with errors wrapped in tags
Example:
import { checkAndFormat } from 'opengrammer';
const result = checkAndFormat("Their going there.");
console.log(result.errors); // Array of errors
console.log(result.formatted); // HTML stringinitTooltips(container)
Initializes tooltip event listeners on formatted HTML elements.
Parameters:
container(HTMLElement|string): Container element or CSS selector containing formatted text
Example:
import { checkAndFormat, initTooltips } from 'opengrammer';
const result = checkAndFormat(text);
document.getElementById('content').innerHTML = result.formatted;
// Initialize tooltips
initTooltips('#content');removeTooltips(container)
Removes tooltip event listeners from a container.
Parameters:
container(HTMLElement|string): Container element or CSS selector
Setup Functions
GrammerCheckContent(selectorOrElement, options)
Easiest way to add grammar checking to a contenteditable element. Handles cursor position, debouncing, and tooltips automatically.
Parameters:
selectorOrElement(string|HTMLElement): CSS selector or DOM elementoptions(Object): Configuration optionsdebounceMs(number): Delay before checking after typing stops (default: 1000)autoCheckOnLoad(boolean): Check grammar when element loads (default: true)autoCheckOnBlur(boolean): Check grammar when element loses focus (default: true)debug(boolean): Enable debug logging (default: false)decorationClass(string): CSS class for error highlights (default: 'grammar-error-decoration')decorationStyle(string|object): Inline styles for error highlights. Can be a CSS string or an object with camelCase propertiesdecorationAttributes(object): Additional HTML attributes to add to decorations (default: {})tooltipStyle(string|object): Customize tooltip container styles (default: {})tooltipMessageStyle(string|object): Customize error message styles (default: {})tooltipSuggestionsStyle(string|object): Customize suggestions section styles (default: {})tooltipLabelStyle(string|object): Customize "Suggestions:" label styles (default: {})tooltipListStyle(string|object): Customize suggestions list styles (default: {})tooltipItemStyle(string|object): Customize individual suggestion item styles (default: {})
Returns:
- Object with:
check(): Manually trigger grammar checkdestroy(): Clean up event listeners
Example:
import { GrammerCheckContent } from 'opengrammer';
const checker = GrammerCheckContent('#my-editor', {
debounceMs: 500,
debug: true
});
// Manual check
checker.check();
// Cleanup
checker.destroy();GrammerCheckContentTipTap(editor, options)
Integrates grammar checking with TipTap/ProseMirror editors.
Parameters:
editor(Editor): TipTap editor instanceoptions(Object): Configuration optionsdecorations(Object): Required -{ Decoration, DecorationSet }from@tiptap/pm/viewdebounceMs(number): Delay before checking (default: 1000)autoCheckOnLoad(boolean): Check on load (default: true)autoCheckOnBlur(boolean): Check on blur (default: true)debug(boolean): Enable debug logging (default: false)decorationClass(string): CSS class for error highlights (default: 'grammar-error-decoration')decorationStyle(string|object): Inline styles for error highlights. Can be a CSS string or an object with camelCase propertiesdecorationAttributes(object): Additional HTML attributes to add to decorations (default: {})tooltipStyle(string|object): Customize tooltip container styles (default: {})tooltipMessageStyle(string|object): Customize error message styles (default: {})tooltipSuggestionsStyle(string|object): Customize suggestions section styles (default: {})tooltipLabelStyle(string|object): Customize "Suggestions:" label styles (default: {})tooltipListStyle(string|object): Customize suggestions list styles (default: {})tooltipItemStyle(string|object): Customize individual suggestion item styles (default: {})
Returns:
- Object with:
check(): Manually trigger grammar checkdestroy(): Clean up event listeners and decorationsgetErrors(): Get current grammar errors arraygetDecorations(): Get current ProseMirror decoration set
Example:
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { GrammerCheckContentTipTap } from 'opengrammer';
const checker = GrammerCheckContentTipTap(editor, {
decorations: { Decoration, DecorationSet },
debounceMs: 1000,
debug: false
});Grammar Rules
The package includes custom context-aware rules for detecting:
- Homophones: there/their/they're, its/it's, your/you're, to/too/two
- Double spaces: Multiple consecutive spaces
- Missing capitalization: Lowercase letters after periods
- Punctuation: Multiple periods (should use ellipsis)
- Missing apostrophes: Common contractions (don't, can't, won't, etc.)
Rules check sentence context to reduce false positives. For example, "Their car" won't be flagged because "their" is correctly followed by a noun.
Styling
Import the CSS file to get the default styling:
import 'opengrammer/styles';Or include it in your HTML:
<link rel="stylesheet" href="node_modules/opengrammer/src/styles.css">The CSS provides:
- Blue wavy underline for grammar errors
- Dark tooltip with suggestions
- Hover effects and animations
You can customize the styling by overriding the CSS classes:
.grammar-error- Error text styling.grammar-tooltip- Tooltip container.grammar-tooltip-message- Error message.grammar-tooltip-suggestions- Suggestions section
Debug Mode
Enable debug logging to see what's happening:
GrammerCheckContent('#editor', { debug: true });Debug output includes:
- When grammar checking starts/completes
- Number of errors found and their details
- Performance timing
- Cursor position restoration
- Debounce and blur events
- Initialization status
Browser Support
Requires modern browsers with ES6 module support and DOM APIs. Works in:
- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
Documentation
- React Integration Guide - Detailed React examples and patterns
- TipTap Integration Guide - Complete TipTap/ProseMirror setup
License
MIT
