hi I am looking for grammar check in any text box
Ex : similar to outlook behavior
Note : I already enabled the spell check but I am looking for grammar .strong text
Please feel to suggest another approach I have tried loading different libraries linking part is missing
// Function to load the nspell library
async function loadNspellLibrary() {
return new Promise((resolve, reject) => {
if (window.nspell) {
console.log("nspell library already loaded.");
resolve(); // If nspell is already loaded, resolve immediately
return;
}
const script = document.createElement('script');
// Alternative URL for nspell library
script.src = "https://cdn.jsdelivr.net/npm/nspell@2.0.4";
script.onload = () => {
console.log("nspell library loaded successfully.");
resolve();
};
script.onerror = (error) => {
console.error("Failed to load nspell library:", error);
reject(error);
};
document.head.appendChild(script);
});
}
// Function to fetch dictionary files
async function fetchDictionaryFiles() {
try {
const dictionary = await fetch('https://unpkg.com/dictionaries/en/index.dic').then(response => response.text());
const affix = await fetch('https://unpkg.com/dictionaries/en/index.aff').then(response => response.text());
console.log("Dictionary and affix files fetched successfully.");
return { dictionary, affix };
} catch (error) {
console.error("Failed to fetch dictionary files:", error);
throw error;
}
}
// Function to initialize nspell with fetched dictionary files
async function initializeNspell() {
await loadNspellLibrary();
const { dictionary, affix } = await fetchDictionaryFiles();
return new window.nspell({ aff: affix, dic: dictionary });
}
// Function to check grammar using nspell
async function checkGrammar(nspellInstance, text) {
// Split the text into words
const words = text.split(/\s+/);
// Check each word and collect suggestions
const suggestions = words.map(word => {
if (!nspellInstance.correct(word)) {
return `Word: ${word}, Suggestions: ${nspellInstance.suggest(word).join(', ')}`;
}
return null;
}).filter(suggestion => suggestion !== null).join('\n');
return suggestions;
}
// Initialize nspell and set up the event listener
async function setupSpellChecker() {
try {
const nspellInstance = await initializeNspell();
console.log("nspell initialized successfully.");
// Reference to the text input field
const textInput = textinputFiled;
// Event listener for text input changes
textInput.onChange(async () => {
const text = textInput.value;
const suggestions = await checkGrammar(nspellInstance, text);
textInput.setValue(suggestions);
});
console.log("Spell checker setup completed.");
} catch (error) {
console.error('Error setting up the spell checker:', error);
}
}
// Load libraries and initialize spell checker when the page loads
setupSpellChecker().catch(error => {
console.error('Error in setupSpellChecker:', error);
});