BetterDiscordAddons/Plugins/SpellCheck/SpellCheck.plugin.js

714 lines
36 KiB
JavaScript
Raw Normal View History

2020-10-20 23:25:34 +02:00
/**
* @name SpellCheck
2021-03-05 13:26:41 +01:00
* @author DevilBro
2020-10-20 23:25:34 +02:00
* @authorId 278543574059057154
2023-11-04 19:46:31 +01:00
* @version 1.6.9
2021-03-05 13:26:41 +01:00
* @description Adds a Spell Check to all Message Inputs. Select a Word and Right Click it to add it to your Dictionary
2020-10-20 23:25:34 +02:00
* @invite Jx3TjNS
* @donate https://www.paypal.me/MircoWittrien
* @patreon https://www.patreon.com/MircoWittrien
2021-03-09 15:10:55 +01:00
* @website https://mwittrien.github.io/
* @source https://github.com/mwittrien/BetterDiscordAddons/tree/master/Plugins/SpellCheck/
2021-03-10 09:17:37 +01:00
* @updateUrl https://mwittrien.github.io/BetterDiscordAddons/Plugins/SpellCheck/SpellCheck.plugin.js
2020-10-20 23:25:34 +02:00
*/
2018-10-11 10:21:26 +02:00
2020-09-19 20:49:33 +02:00
module.exports = (_ => {
2022-09-01 14:40:11 +02:00
const changeLog = {
2022-09-02 12:37:10 +02:00
2020-09-19 20:49:33 +02:00
};
2021-01-23 21:47:04 +01:00
2022-02-05 21:14:17 +01:00
return !window.BDFDB_Global || (!window.BDFDB_Global.loaded && !window.BDFDB_Global.started) ? class {
2022-09-01 14:55:22 +02:00
constructor (meta) {for (let key in meta) this[key] = meta[key];}
getName () {return this.name;}
getAuthor () {return this.author;}
getVersion () {return this.version;}
getDescription () {return `The Library Plugin needed for ${this.name} is missing. Open the Plugin Settings to download it. \n\n${this.description}`;}
2021-02-01 17:13:13 +01:00
downloadLibrary () {
2023-11-18 18:31:04 +01:00
BdApi.Net.fetch("https://mwittrien.github.io/BetterDiscordAddons/Library/0BDFDB.plugin.js").then(r => {
if (!r || r.status != 200) throw new Error();
else return r.text();
}).then(b => {
if (!b) throw new Error();
else return require("fs").writeFile(require("path").join(BdApi.Plugins.folder, "0BDFDB.plugin.js"), b, _ => BdApi.showToast("Finished downloading BDFDB Library", {type: "success"}));
}).catch(error => {
BdApi.alert("Error", "Could not download BDFDB Library Plugin. Try again later or download it manually from GitHub: https://mwittrien.github.io/downloader/?library");
2021-02-01 17:13:13 +01:00
});
}
2020-09-19 20:49:33 +02:00
2021-01-06 12:38:36 +01:00
load () {
2020-11-19 16:51:14 +01:00
if (!window.BDFDB_Global || !Array.isArray(window.BDFDB_Global.pluginQueue)) window.BDFDB_Global = Object.assign({}, window.BDFDB_Global, {pluginQueue: []});
2020-09-19 20:49:33 +02:00
if (!window.BDFDB_Global.downloadModal) {
window.BDFDB_Global.downloadModal = true;
2022-09-01 14:55:22 +02:00
BdApi.showConfirmationModal("Library Missing", `The Library Plugin needed for ${this.name} is missing. Please click "Download Now" to install it.`, {
2020-09-19 20:49:33 +02:00
confirmText: "Download Now",
cancelText: "Cancel",
onCancel: _ => {delete window.BDFDB_Global.downloadModal;},
2020-09-20 08:15:13 +02:00
onConfirm: _ => {
delete window.BDFDB_Global.downloadModal;
2021-02-01 17:13:13 +01:00
this.downloadLibrary();
2020-09-20 08:15:13 +02:00
}
2020-09-19 20:49:33 +02:00
});
}
2022-09-01 14:55:22 +02:00
if (!window.BDFDB_Global.pluginQueue.includes(this.name)) window.BDFDB_Global.pluginQueue.push(this.name);
2020-10-09 21:09:35 +02:00
}
2021-01-06 12:38:36 +01:00
start () {this.load();}
stop () {}
getSettingsPanel () {
2020-11-28 23:12:09 +01:00
let template = document.createElement("template");
2022-09-01 14:55:22 +02:00
template.innerHTML = `<div style="color: var(--header-primary); font-size: 16px; font-weight: 300; white-space: pre; line-height: 22px;">The Library Plugin needed for ${this.name} is missing.\nPlease click <a style="font-weight: 500;">Download Now</a> to install it.</div>`;
2021-02-01 17:13:13 +01:00
template.content.firstElementChild.querySelector("a").addEventListener("click", this.downloadLibrary);
2020-11-28 23:12:09 +01:00
return template.content.firstElementChild;
}
2020-10-09 21:09:35 +02:00
} : (([Plugin, BDFDB]) => {
2020-09-19 20:49:33 +02:00
var languages, dictionaries, langDictionaries, languageToasts, checkTimeout, currentText;
2023-07-07 11:37:08 +02:00
const dictionaryLanguageIds = ["af", "bg", "cs", "da", "de", "el", "en", "es", "fr", "hr", "it", "nl", "pl", "pt-BR", "pt", "ru", "sv", "tr", "uk"];
2020-09-19 20:49:33 +02:00
2020-10-09 21:09:35 +02:00
return class SpellCheck extends Plugin {
2021-01-06 12:38:36 +01:00
onLoad () {
2020-09-19 20:49:33 +02:00
languages = {};
dictionaries = {};
langDictionaries = {};
languageToasts = {};
this.defaults = {
2021-05-28 19:39:58 +02:00
general: {
2023-11-18 18:31:04 +01:00
downloadDictionary: {value: false, description: "Use local Dictionary File (downloads Dictionary on first Usage)"}
2020-09-19 20:49:33 +02:00
},
choices: {
2023-11-18 18:31:04 +01:00
dictionaryLanguage: {value: "en", force: true, description: "Primary Language"},
secondaryLanguage: {value: "-", force: false, description: "Secondary Language"}
2020-09-19 20:49:33 +02:00
},
amounts: {
2023-11-18 18:31:04 +01:00
maxSimilarAmount: {value: 6, min: 1, max: 30, description: "Maximal Amount of suggested Words"}
2020-02-20 17:23:49 +01:00
}
2020-09-19 20:49:33 +02:00
};
2020-02-20 17:23:49 +01:00
2022-10-28 12:00:31 +02:00
this.modulePatches = {
componentDidMount: [
"ChannelTextAreaEditor"
],
componentDidUpdate: [
"ChannelTextAreaEditor"
]
2020-09-19 20:49:33 +02:00
};
2020-02-20 17:23:49 +01:00
2020-09-19 20:49:33 +02:00
this.css = `
${BDFDB.dotCNS._spellcheckoverlay + BDFDB.dotCN._spellcheckerror} {
2021-01-23 21:47:04 +01:00
background: url('data:image/svg+xml; utf8, <svg xmlns="http://www.w3.org/2000/svg" width="4" height="3" viewBox="0 0 4 3" fill="red"><rect x="0" y="2" width="1" height="1"/><rect x="1" y="1" width="1" height="1"/><rect x="2" y="0" width="1" height="1"/><rect x="3" y="1" width="1" height="1"/></svg>') bottom repeat-x;
2020-09-19 20:49:33 +02:00
}
`;
}
2021-01-06 12:38:36 +01:00
onStart () {
2023-07-07 11:37:08 +02:00
languages = BDFDB.ObjectUtils.filter(BDFDB.LanguageUtils.languages, langId => dictionaryLanguageIds.includes(langId), true);
if (BDFDB.LibraryStores.SpellcheckStore && BDFDB.LibraryStores.SpellcheckStore.isEnabled()) BDFDB.LibraryModules.DispatchApiUtils.dispatch({type: "SPELLCHECK_TOGGLE"});
2020-06-09 09:30:21 +02:00
2023-07-07 11:37:08 +02:00
BDFDB.PatchUtils.forceAllUpdates(this);
for (let key in this.settings.choices) {
if (key == "dictionaryLanguage" && !languages[this.settings.choices[key]]) {
this.settings.choices[key] = "en";
BDFDB.DataUtils.save(this.settings.choices[key], this, "choices", key);
2020-06-05 20:03:21 +02:00
}
2023-07-07 11:37:08 +02:00
this.setDictionary(key, this.settings.choices[key]);
}
2020-02-20 17:23:49 +01:00
}
2020-09-19 20:49:33 +02:00
2021-01-06 12:38:36 +01:00
onStop () {
2021-05-28 19:39:58 +02:00
BDFDB.PatchUtils.forceAllUpdates(this);
2020-02-20 17:23:49 +01:00
BDFDB.DOMUtils.remove(BDFDB.dotCN._spellcheckoverlay);
2019-01-26 22:45:19 +01:00
2022-04-29 14:52:56 +02:00
for (let key in languageToasts) languageToasts[key] && languageToasts[key].close();
2020-02-20 17:23:49 +01:00
}
2018-10-11 10:21:26 +02:00
2020-09-19 20:49:33 +02:00
getSettingsPanel (collapseStates = {}) {
2021-05-28 19:39:58 +02:00
let ownDictionary = BDFDB.DataUtils.load(this, "owndics", this.settings.choices.dictionaryLanguage) || [];
2020-09-19 20:49:33 +02:00
2021-05-28 19:39:58 +02:00
let settingsPanel;
return settingsPanel = BDFDB.PluginUtils.createSettingsPanel(this, {
collapseStates: collapseStates,
children: _ => {
let settingsItems = [];
2020-09-19 20:49:33 +02:00
2021-05-28 19:39:58 +02:00
for (let key in this.defaults.general) settingsItems.push(BDFDB.ReactUtils.createElement(BDFDB.LibraryComponents.SettingsSaveItem, {
className: BDFDB.disCN.marginbottom8,
type: "Switch",
plugin: this,
keys: ["general", key],
label: this.defaults.general[key].description,
value: this.settings.general[key]
}));
for (let key in this.defaults.choices) settingsItems.push(BDFDB.ReactUtils.createElement(BDFDB.LibraryComponents.SettingsSaveItem, {
className: BDFDB.disCN.marginbottom8,
type: "Select",
plugin: this,
keys: ["choices", key],
label: this.defaults.choices[key].description,
basis: "70%",
value: this.settings.choices[key],
options: (this.defaults.choices[key].force ? [] : [{value: "-", label: BDFDB.LanguageUtils.LanguageStrings.FORM_LABEL_NOTHING}]).concat(BDFDB.ObjectUtils.toArray(BDFDB.ObjectUtils.map(languages, (lang, id) => ({value: id, label: this.getLanguageName(lang)})))),
searchable: true,
onChange: value => {
this.setDictionary(key, value);
BDFDB.PluginUtils.refreshSettingsPanel(this, settingsPanel);
}
}));
for (let key in this.defaults.amounts) settingsItems.push(BDFDB.ReactUtils.createElement(BDFDB.LibraryComponents.SettingsSaveItem, {
className: BDFDB.disCN.marginbottom8,
type: "TextInput",
childProps: {
type: "number"
},
plugin: this,
keys: ["amounts", key],
label: this.defaults.amounts[key].description,
basis: "20%",
min: this.defaults.amounts[key].min,
max: this.defaults.amounts[key].max,
value: this.settings.amounts[key]
}));
if (ownDictionary.length) settingsItems.push(BDFDB.ReactUtils.createElement(BDFDB.LibraryComponents.SettingsPanelList, {
title: "Your own Dictionary:",
children: ownDictionary.map(word => BDFDB.ReactUtils.createElement(BDFDB.LibraryComponents.Card, {
children: word.toLowerCase(),
onRemove: _ => {
BDFDB.ArrayUtils.remove(ownDictionary, word);
BDFDB.DataUtils.save(ownDictionary, this, "owndics", this.settings.choices.dictionaryLanguage);
dictionaries.dictionaryLanguage = this.formatDictionary(langDictionaries.dictionaryLanguage.concat(ownDictionary));
BDFDB.PluginUtils.refreshSettingsPanel(this, settingsPanel);
}
}))
}));
return settingsItems;
2020-09-19 20:49:33 +02:00
}
2021-05-28 19:39:58 +02:00
});
2020-09-19 20:49:33 +02:00
}
2019-01-26 22:45:19 +01:00
2021-01-06 12:38:36 +01:00
onSettingsClosed () {
2020-09-19 20:49:33 +02:00
if (this.SettingsUpdated) {
delete this.SettingsUpdated;
2021-05-28 19:39:58 +02:00
BDFDB.PatchUtils.forceAllUpdates(this);
2020-02-20 17:23:49 +01:00
}
2019-02-19 13:34:09 +01:00
}
2019-01-26 22:45:19 +01:00
2022-10-28 12:00:31 +02:00
onTextAreaContextMenu (e) {
2021-03-01 14:38:18 +01:00
let [removeParent, removeIndex] = BDFDB.ContextMenuUtils.findItem(e.returnvalue, {id: "spellcheck", group: true});
if (removeIndex > -1) removeParent.splice(removeIndex, 1);
2021-03-01 14:42:03 +01:00
[removeParent, removeIndex] = BDFDB.ContextMenuUtils.findItem(e.returnvalue, {id: "correction-0", group: true});
if (removeIndex > -1) removeParent.splice(removeIndex, 1);
2020-09-19 20:49:33 +02:00
let textarea = BDFDB.DOMUtils.getParent(BDFDB.dotCN.textarea, e.instance.props.target), word = null;
if (textarea) for (let error of textarea.parentElement.querySelectorAll(BDFDB.dotCN._spellcheckerror)) {
let rects = BDFDB.DOMUtils.getRects(error);
2020-09-20 07:20:57 +02:00
let position = BDFDB.ListenerUtils.getPosition();
if (position.pageX > rects.x && position.pageX < (rects.x + rects.width) && position.pageY > rects.y && position.pageY < (rects.y + rects.height)) {
2020-09-19 20:49:33 +02:00
word = error.innerText;
break;
}
}
if (word && this.isWordNotInDictionary(word)) {
let similarWords = this.getSimilarWords(word.toLowerCase().trim());
let [children, index] = BDFDB.ContextMenuUtils.findItem(e.returnvalue, {id: "devmode-copy-id", group: true});
children.splice(index > -1 ? index : children.length, 0, BDFDB.ContextMenuUtils.createItem(BDFDB.LibraryComponents.MenuItems.MenuGroup, {
children: BDFDB.ContextMenuUtils.createItem(BDFDB.LibraryComponents.MenuItems.MenuItem, {
label: BDFDB.LanguageUtils.LanguageStrings.SPELLCHECK,
id: BDFDB.ContextMenuUtils.createItemId(this.name, "spellcheck"),
children: [
BDFDB.ContextMenuUtils.createItem(BDFDB.LibraryComponents.MenuItems.MenuItem, {
label: this.labels.context_spellcheck,
2020-09-19 20:49:33 +02:00
id: BDFDB.ContextMenuUtils.createItemId(this.name, "add-to-spellcheck"),
2022-04-06 19:29:59 +02:00
hint: _ => BDFDB.ReactUtils.createElement(BDFDB.LibraryComponents.MenuItems.MenuHint, {
hint: word
}),
action: _ => this.addToOwnDictionary(word)
2020-09-19 20:49:33 +02:00
}),
BDFDB.ContextMenuUtils.createItem(BDFDB.LibraryComponents.MenuItems.MenuSeparator, {}),
!similarWords.length ? BDFDB.ContextMenuUtils.createItem(BDFDB.LibraryComponents.MenuItems.MenuItem, {
label: this.labels.context_nosimilarwords,
2020-09-19 20:49:33 +02:00
id: BDFDB.ContextMenuUtils.createItemId(this.name, "no-suggestions"),
disabled: true
}) : similarWords.sort().map(suggestion => BDFDB.ContextMenuUtils.createItem(BDFDB.LibraryComponents.MenuItems.MenuItem, {
label: suggestion,
id: BDFDB.ContextMenuUtils.createItemId(this.name, "suggestion", suggestion),
2022-04-06 19:29:59 +02:00
action: _ => this.replaceWord(e.instance.props.editor, word, suggestion)
2020-09-19 20:49:33 +02:00
}))
].flat(10).filter(n => n)
})
}));
}
2020-06-09 09:30:21 +02:00
}
2022-10-24 10:42:20 +02:00
processChannelTextAreaEditor (e) {
2022-04-06 19:29:59 +02:00
let newText = BDFDB.SlateUtils.toTextValue(e.instance.props.richValue);
2020-09-19 20:49:33 +02:00
if (newText != currentText) {
currentText = newText;
BDFDB.DOMUtils.remove(e.node.parentElement.querySelectorAll(BDFDB.dotCN._spellcheckoverlay));
BDFDB.TimeUtils.clear(checkTimeout);
checkTimeout = BDFDB.TimeUtils.timeout(_ => {
let overlay = e.node.cloneNode(true), wrapper = BDFDB.DOMUtils.getParent(BDFDB.dotCN.textareainner, e.node);
BDFDB.DOMUtils.addClass(overlay, BDFDB.disCN._spellcheckoverlay);
let style = Object.assign({}, getComputedStyle(e.node));
for (let i in style) if (i.indexOf("webkit") == -1 && isNaN(parseInt(i))) overlay.style[i] = style[i];
overlay.style.setProperty("color", "transparent", "important");
overlay.style.setProperty("background", "none", "important");
overlay.style.setProperty("mask", "none", "important");
overlay.style.setProperty("pointer-events", "none", "important");
overlay.style.setProperty("position", "absolute", "important");
overlay.style.setProperty("left", BDFDB.DOMUtils.getRects(e.node).left - BDFDB.DOMUtils.getRects(wrapper).left + "px", "important");
overlay.style.setProperty("width", BDFDB.DOMUtils.getRects(e.node).width - style.paddingLeft - style.paddingRight + "px", "important");
overlay.style.setProperty("height", style.height, "important");
for (let child of overlay.querySelectorAll("*")) {
child.style.setProperty("color", "transparent", "important");
child.style.setProperty("background-color", "transparent", "important");
child.style.setProperty("border-color", "transparent", "important");
child.style.setProperty("text-shadow", "none", "important");
2021-04-09 20:14:58 +02:00
child.style.setProperty("object-position", "-999999px -999999px", "important");
2020-09-19 20:49:33 +02:00
child.style.setProperty("pointer-events", "none", "important");
if (child.getAttribute("data-slate-string") && child.parentElement.getAttribute("data-slate-leaf")) {
let newline = child.querySelector("br");
if (newline) newline.remove();
child.innerHTML = this.spellCheckText(child.textContent);
if (newline) child.appendChild(newline);
}
2020-06-09 19:42:00 +02:00
}
2020-09-19 20:49:33 +02:00
e.node.parentElement.appendChild(overlay);
}, 300);
}
2020-06-09 19:42:00 +02:00
}
2019-01-26 22:45:19 +01:00
2020-09-19 20:49:33 +02:00
spellCheckText (string) {
let htmlString = [];
2022-05-23 13:30:09 +02:00
let splitter = "!?!?!?!?!?!?!?!" + this.name + BDFDB.NumberUtils.generateId() + this.name + "!?!?!?!?!?!?!?!";
2022-06-03 09:02:15 +02:00
string.replace(/([0-9\ \@\>\<\|\,\;\.\:\-\_\=\#\+\*\~\[\]\(\)\{\}\\\/\&\^\t\r\n])/g, "$1" + splitter).split(splitter).forEach(word => {
let execReturn = /[0-9\ \@\>\<\|\,\;\.\:\-\_\=\#\+\*\~\[\]\(\)\{\}\\\/\&\^\t\r\n]$/g.exec(word);
2022-05-23 13:30:09 +02:00
if (execReturn) word = word.slice(0, execReturn[0].length * -1);
htmlString.push(`<span class="${this.isWordNotInDictionary(word) ? BDFDB.disCN._spellcheckerror : ""}" style="color: transparent !important; text-shadow: none !important;">${BDFDB.StringUtils.htmlEscape(word)}</span>`);
if (execReturn) htmlString.push(`<span>${execReturn[0]}</span>`);
2020-09-19 20:49:33 +02:00
});
2022-05-23 13:30:09 +02:00
return htmlString.join("").replace(/\n /g, "\n");
2020-09-19 20:49:33 +02:00
}
2020-01-15 21:46:41 +01:00
2020-09-19 20:49:33 +02:00
replaceWord (editor, toBeReplaced, replacement) {
2022-04-06 19:29:59 +02:00
if (!editor) return;
2020-09-19 20:49:33 +02:00
toBeReplaced = toBeReplaced.toUpperCase();
let newString = [];
2022-05-23 13:30:09 +02:00
let splitter = "!?!?!?!?!?!?!?!" + this.name + BDFDB.NumberUtils.generateId() + this.name + "!?!?!?!?!?!?!?!";
2022-06-03 09:02:15 +02:00
BDFDB.SlateUtils.toTextValue(editor.children).replace(/([0-9\ \@\>\<\|\,\;\.\:\-\_\=\#\+\*\~\[\]\(\)\{\}\\\/\&\^\t\r\n])/g, "$1" + splitter).split(splitter).forEach(word => {
let execReturn = /[0-9\ \@\>\<\|\,\;\.\:\-\_\=\#\+\*\~\[\]\(\)\{\}\\\/\&\^\t\r\n]$/g.exec(word);
2022-05-23 13:30:09 +02:00
if (execReturn) word = word.slice(0, execReturn[0].length * -1);
2020-09-19 20:49:33 +02:00
if (word.toUpperCase() == toBeReplaced) {
let firstLetter = word.charAt(0);
let isCapitalised = firstLetter.toUpperCase() == firstLetter && firstLetter.toLowerCase() != firstLetter;
2022-05-23 13:30:09 +02:00
newString.push(isCapitalised ? replacement.charAt(0).toUpperCase() + replacement.slice(1) : replacement);
2020-09-19 20:49:33 +02:00
}
2022-05-23 13:30:09 +02:00
else newString.push(word);
if (execReturn) newString.push(execReturn[0]);
2020-09-19 20:49:33 +02:00
});
2022-04-06 19:29:59 +02:00
editor.history.stack.splice(editor.history.index + 1, 0, {
type: "other",
2023-07-14 09:56:01 +02:00
mergeable: false,
createdAt: new Date().getTime(),
value: BDFDB.SlateUtils.toRichValue(newString.join("")),
2022-04-06 19:29:59 +02:00
selection: editor.history.stack[editor.history.index].selection
});
editor.redo();
2020-09-19 20:49:33 +02:00
}
2019-01-26 22:45:19 +01:00
2020-09-19 20:49:33 +02:00
addToOwnDictionary (word) {
word = word.split(" ")[0].split("\n")[0].split("\r")[0].split("\t")[0];
if (word) {
let wordLow = word.toLowerCase();
2021-05-28 19:39:58 +02:00
if (languages[this.settings.choices.dictionaryLanguage]) {
let ownDictionary = BDFDB.DataUtils.load(this, "owndics", this.settings.choices.dictionaryLanguage) || [];
2020-09-19 20:49:33 +02:00
if (!ownDictionary.includes(wordLow)) {
ownDictionary.push(wordLow);
2021-05-28 19:39:58 +02:00
BDFDB.DataUtils.save(ownDictionary, this, "owndics", this.settings.choices.dictionaryLanguage);
BDFDB.NotificationUtils.toast(this.labels.toast_wordadd.replace("{{var0}}", word).replace("{{var1}}", this.getLanguageName(languages[this.settings.choices.dictionaryLanguage])), {type: "success"});
2020-09-19 20:49:33 +02:00
dictionaries.dictionaryLanguage = this.formatDictionary(langDictionaries.dictionaryLanguage.concat(ownDictionary));
}
2020-05-23 10:59:15 +02:00
}
2020-02-20 17:23:49 +01:00
}
2018-10-11 10:21:26 +02:00
}
2019-01-26 22:45:19 +01:00
2020-09-19 20:49:33 +02:00
setDictionary (key, lang) {
2022-04-29 14:52:56 +02:00
languageToasts[key] && languageToasts[key].close();
2020-09-19 20:49:33 +02:00
if (languages[lang]) {
let ownDictionary = BDFDB.DataUtils.load(this, "owndics", lang) || [];
2022-04-29 14:52:56 +02:00
languageToasts[key] = BDFDB.NotificationUtils.toast(`${this.labels.toast_dictionary.replace("{{var0}}", this.getLanguageName(languages[lang]))} - ${BDFDB.LanguageUtils.LibraryStrings.please_wait}`, {timeout: 0, ellipsis: true, position: "center"});
2020-09-19 20:49:33 +02:00
languageToasts[key].lang = lang
2021-03-01 14:38:18 +01:00
const folder = BDFDB.LibraryRequires.path.join(BDFDB.BDUtils.getPluginsFolder(), "dictionaries");
const filePath = BDFDB.LibraryRequires.path.join(folder, lang + ".dic");
2020-09-19 20:49:33 +02:00
2023-11-04 19:46:31 +01:00
const parse = (error, body, download) => {
2022-04-29 14:52:56 +02:00
languageToasts[key].close();
2023-11-04 19:46:31 +01:00
if (error || body.toLowerCase().indexOf("<!doctype html>") > -1) {
2021-01-26 21:14:48 +01:00
BDFDB.NotificationUtils.toast(this.labels.toast_dictionary_fail.replace("{{var0}}", this.getLanguageName(languages[lang])), {
type: "danger",
2021-01-28 14:11:00 +01:00
position: "center"
2021-01-26 21:14:48 +01:00
});
2020-05-25 21:03:56 +02:00
}
2023-11-04 19:46:31 +01:00
else if (body && languageToasts[key].lang == lang) {
2020-09-19 20:49:33 +02:00
if (download) {
if (!BDFDB.LibraryRequires.fs.existsSync(folder)) BDFDB.LibraryRequires.fs.mkdirSync(folder);
BDFDB.LibraryRequires.fs.writeFile(filePath, body, _ => {});
}
2021-05-28 19:39:58 +02:00
langDictionaries[key] = body.toLowerCase().replace(/\r/g, "").replace(/\s/g, "\n").split("\n");
2020-09-19 20:49:33 +02:00
dictionaries[key] = this.formatDictionary(langDictionaries[key].concat(ownDictionary));
2021-01-26 21:14:48 +01:00
BDFDB.NotificationUtils.toast(this.labels.toast_dictionary_success.replace("{{var0}}", this.getLanguageName(languages[lang])), {
type: "success",
2021-01-28 14:11:00 +01:00
position: "center"
2021-01-26 21:14:48 +01:00
});
2020-09-19 20:49:33 +02:00
}
};
2023-11-04 19:46:31 +01:00
if (this.settings.general.downloadDictionary && BDFDB.LibraryRequires.fs.existsSync(filePath)) BDFDB.LibraryRequires.fs.readFile(filePath, "utf8", (error, body) => {
parse(error, body, false);
2020-09-19 20:49:33 +02:00
});
else BDFDB.LibraryRequires.request("https://mwittrien.github.io/BetterDiscordAddons/Plugins/SpellCheck/dic/" + lang + ".dic", (error, response, body) => {
2023-11-04 19:46:31 +01:00
parse(error, body, this.settings.general.downloadDictionary);
2020-09-19 20:49:33 +02:00
});
}
else {
delete dictionaries[key];
delete langDictionaries[key];
}
2020-05-23 10:59:15 +02:00
}
2020-09-19 20:49:33 +02:00
formatDictionary (words) {
let i = 0;
return words.reduce((dictionary, word) => {
let firstLetterLower = word.charAt(0).toLowerCase();
if (!dictionary[firstLetterLower]) dictionary[firstLetterLower] = {};
if (!dictionary[firstLetterLower][word.length]) dictionary[firstLetterLower][word.length] = [];
dictionary[firstLetterLower][word.length].push(word);
return dictionary;
}, {});
2020-05-23 10:59:15 +02:00
}
2019-01-26 22:45:19 +01:00
2020-09-19 20:49:33 +02:00
isWordNotInDictionary (unformatedWord) {
let wordLow = unformatedWord.toLowerCase();
2022-05-24 13:59:33 +02:00
let wordWithoutSymbols = wordLow.replace(/[0-9\µ\@\$\£\€\¥\¢\²\³\>\<\|\,\;\.\:\-\_\#\+\*\~\?\¿\\\´\`\“\”\\\}\=\]\)\[\(\{\/\&\%\§\"\!\¡\^\°\n\t\r]/g, "");
2020-09-19 20:49:33 +02:00
if (wordLow.indexOf("http://") != 0 && wordLow.indexOf("https://") != 0 && wordWithoutSymbols && wordWithoutSymbols.length > wordLow.length/2) {
let wordStartingPos = /^.{1}'/.test(wordWithoutSymbols) ? wordWithoutSymbols.split("'")[1] : "";
let wordEndingPos = /'.{1}$/.test(wordWithoutSymbols) ? wordWithoutSymbols.split("'").reverse()[1] : "";
for (let key in dictionaries) for (let word of BDFDB.ArrayUtils.removeCopies([wordLow, wordWithoutSymbols, wordStartingPos, wordEndingPos].filter(n => n))) {
let firstLetterLower = word.charAt(0);
if (dictionaries[key] && dictionaries[key][firstLetterLower] && dictionaries[key][firstLetterLower][word.length] && dictionaries[key][firstLetterLower][word.length].includes(word)) return false;
}
return true;
2020-05-23 10:59:15 +02:00
}
2020-09-19 20:49:33 +02:00
return false;
2020-05-23 10:59:15 +02:00
}
2019-01-26 22:45:19 +01:00
2020-09-19 20:49:33 +02:00
getSimilarWords (word) {
let similarWords = [];
2021-05-28 19:39:58 +02:00
if (this.settings.amounts.maxSimilarAmount > 0) {
2020-09-19 20:49:33 +02:00
let firstLetterLower = word.charAt(0).toLowerCase();
let possibilities = [];
for (let key in dictionaries) if (dictionaries[key] && dictionaries[key][firstLetterLower]) possibilities = possibilities.concat(BDFDB.ObjectUtils.toArray(dictionaries[key][firstLetterLower]).flat());
possibilities = BDFDB.ArrayUtils.removeCopies(possibilities);
let similarities = {};
for (let string of possibilities) {
let value = this.wordSimilarity(word, string);
if (!similarities[value]) similarities[value] = [];
similarities[value].push(string);
}
let amount = 0;
for (let value of Object.keys(similarities).sort().reverse()) {
for (let similarWord of similarities[value]) {
2021-05-28 19:39:58 +02:00
if (amount < this.settings.amounts.maxSimilarAmount && !similarWords.includes(similarWord)) {
2020-09-19 20:49:33 +02:00
similarWords.push(similarWord);
amount++;
}
2021-05-28 19:39:58 +02:00
if (amount >= this.settings.amounts.maxSimilarAmount) break;
2020-02-20 17:23:49 +01:00
}
2021-05-28 19:39:58 +02:00
if (amount >= this.settings.amounts.maxSimilarAmount) break;
2018-10-11 10:21:26 +02:00
}
}
2020-09-19 20:49:33 +02:00
return similarWords;
2018-10-11 10:21:26 +02:00
}
2019-01-26 22:45:19 +01:00
2020-09-19 20:49:33 +02:00
wordSimilarity (a, b) {
let temp;
if (a.length === 0 || b.length === 0 || a.length - b.length > 3 || b.length - a.length > 3) return 0;
if (a.length > b.length) {
temp = a;
a = b;
b = temp;
}
let result = 0, row = [...Array(a.length + 1).keys()];
for (let i = 1; i <= b.length; i++) {
result = i;
for (let j = 1; j <= a.length; j++) {
temp = row[j - 1];
row[j - 1] = result;
result = b[i - 1] === a[j - 1] ? temp : Math.min(temp + 1, Math.min(result + 1, row[j] + 1));
}
2020-02-20 17:23:49 +01:00
}
2020-09-19 20:49:33 +02:00
return (b.length - result) / b.length;
2020-02-20 17:23:49 +01:00
}
2020-06-09 09:30:21 +02:00
2020-09-19 20:49:33 +02:00
getLanguageName (language) {
if (language.name.startsWith("Discord")) return language.name.slice(0, -1) + (language.ownlang && languages[language.id].name != language.ownlang ? ` / ${language.ownlang}` : "") + ")";
else return language.name + (language.ownlang && language.name != language.ownlang ? ` / ${language.ownlang}` : "");
2020-02-20 17:23:49 +01:00
}
2020-07-26 17:02:25 +02:00
2021-01-06 12:38:36 +01:00
setLabelsByLanguage () {
2020-09-19 20:49:33 +02:00
switch (BDFDB.LanguageUtils.getLanguage().id) {
case "bg": // Bulgarian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Няма подобни думи",
context_spellcheck: "Добавяне към речника",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Опит за извличане на речник ({{var0}})",
toast_dictionary_fail: "Извличането на речника не бе успешно ({{var0}})",
toast_dictionary_success: "Речник ({{var0}}) е извлечен успешно",
toast_wordadd: "Думата '{{var0}}' е добавена към речника ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "da": // Danish
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Ingen lignende ord",
context_spellcheck: "Føj til ordbog",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Forsøger at hente ordbog ({{var0}})",
toast_dictionary_fail: "Ordbogen ({{var0}}) kunne ikke hentes",
toast_dictionary_success: "Ordbogen ({{var0}}) hentet med succes",
toast_wordadd: "Ordet '{{var0}}' blev føjet til ordbogen ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "de": // German
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Keine ähnlichen Wörter",
context_spellcheck: "Zum Wörterbuch hinzufügen",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Versuch, das Wörterbuch abzurufen ({{var0}})",
toast_dictionary_fail: "Fehler beim Abrufen des Wörterbuchs ({{var0}})",
toast_dictionary_success: "Wörterbuch ({{var0}}) erfolgreich abgerufen",
toast_wordadd: "Wort '{{var0}}' zum Wörterbuch ({{var1}}) hinzugefügt"
2020-09-19 20:49:33 +02:00
};
case "el": // Greek
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Δεν υπάρχουν παρόμοιες λέξεις",
context_spellcheck: "Προσθήκη στο λεξικό",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Προσπάθεια λήψης λεξικού ({{var0}})",
toast_dictionary_fail: "Αποτυχία ανάκτησης λεξικού ({{var0}})",
toast_dictionary_success: "Το λεξικό ({{var0}}) ανακτήθηκε με επιτυχία",
toast_wordadd: "Προστέθηκε η λέξη '{{var0}}' στο λεξικό ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "es": // Spanish
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "No hay palabras similares",
context_spellcheck: "Agregar al diccionario",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Intentando obtener el diccionario ({{var0}})",
toast_dictionary_fail: "No se pudo recuperar el diccionario ({{var0}})",
toast_dictionary_success: "Diccionario ({{var0}}) obtenido correctamente",
toast_wordadd: "Se agregó la palabra '{{var0}}' al diccionario ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "fi": // Finnish
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Ei vastaavia sanoja",
context_spellcheck: "Lisää sanakirjaan",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Sanaa yritetään noutaa ({{var0}})",
toast_dictionary_fail: "Sanakirjan noutaminen epäonnistui ({{var0}})",
toast_dictionary_success: "Sanakirjan ({{var0}}) haku onnistui",
toast_wordadd: "Sana '{{var0}}' lisättiin sanakirjaan ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "fr": // French
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Pas de mots similaires",
context_spellcheck: "Ajouter au dictionnaire",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Tentative de récupération du dictionnaire ({{var0}})",
toast_dictionary_fail: "Échec de la récupération du dictionnaire ({{var0}})",
toast_dictionary_success: "Le dictionnaire ({{var0}}) a bien été récupéré",
toast_wordadd: "Mot '{{var0}}' ajouté au dictionnaire ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "hr": // Croatian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Nema sličnih riječi",
context_spellcheck: "Dodaj u rječnik",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Pokušaj dohvaćanja Rječnika ({{var0}})",
toast_dictionary_fail: "Dohvaćanje Rječnika nije uspjelo ({{var0}})",
toast_dictionary_success: "Rječnik ({{var0}}) je uspješno dohvaćen",
toast_wordadd: "Riječ '{{var0}}' dodana je u rječnik ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "hu": // Hungarian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Nincsenek hasonló szavak",
context_spellcheck: "Hozzáadás a szótárhoz",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Szótár lekérése próbálkozik ({{var0}})",
toast_dictionary_fail: "Nem sikerült beolvasni a Szótárt ({{var0}})",
toast_dictionary_success: "A szótár ({{var0}}) letöltése sikeresen megtörtént",
toast_wordadd: "A '{{var0}}' szó hozzáadva a ({{var1}}) szótárhoz"
2020-09-19 20:49:33 +02:00
};
case "it": // Italian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Nessuna parola simile",
context_spellcheck: "Aggiungi al dizionario",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Tentativo di recupero del dizionario ({{var0}})",
toast_dictionary_fail: "Impossibile recuperare il dizionario ({{var0}})",
toast_dictionary_success: "Dizionario ({{var0}}) recuperato correttamente",
toast_wordadd: "Parola '{{var0}}' aggiunta al dizionario ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "ja": // Japanese
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "同様の言葉はありません",
context_spellcheck: "辞書に追加",
2021-01-23 21:47:04 +01:00
toast_dictionary: "辞書を取得しようとしています {{var0}} ",
toast_dictionary_fail: "辞書の取得に失敗しました {{var0}} ",
toast_dictionary_success: "辞書 {{var0}} が正常にフェッチされました",
toast_wordadd: "単語 '{{var0}}' が辞書 ({{var1}}) に追加されました"
2020-09-19 20:49:33 +02:00
};
case "ko": // Korean
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "유사한 단어 없음",
context_spellcheck: "사전에 추가",
2021-01-23 21:47:04 +01:00
toast_dictionary: "사전 ({{var0}}) 을 가져 오는 중",
toast_dictionary_fail: "사전 ({{var0}}) 을 가져 오지 못했습니다.",
toast_dictionary_success: "사전 ({{var0}}) 을 성공적으로 가져 왔습니다.",
toast_wordadd: "단어 '{{var0}}' 이 ({{var1}}) 사전에 추가되었습니다"
2020-09-19 20:49:33 +02:00
};
case "lt": // Lithuanian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Jokių panašių žodžių",
context_spellcheck: "Pridėti prie žodyno",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Bandoma gauti žodyną ({{var0}})",
toast_dictionary_fail: "Nepavyko gauti žodyno ({{var0}})",
toast_dictionary_success: "Žodynas ({{var0}}) sėkmingai gautas",
toast_wordadd: "Žodis '{{var0}}' pridėtas prie žodyno ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "nl": // Dutch
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Geen vergelijkbare woorden",
context_spellcheck: "Toevoegen aan woordenboek",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Probeert woordenboek op te halen ({{var0}})",
toast_dictionary_fail: "Ophalen van woordenboek ({{var0}}) is mislukt",
toast_dictionary_success: "Woordenboek ({{var0}}) succesvol opgehaald",
toast_wordadd: "Woord '{{var0}}' toegevoegd aan woordenboek ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "no": // Norwegian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Ingen lignende ord",
context_spellcheck: "Legg til ordbok",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Prøver å hente ordbok ({{var0}})",
toast_dictionary_fail: "Kunne ikke hente ordboken ({{var0}})",
toast_dictionary_success: "Ordbok ({{var0}}) hentet",
toast_wordadd: "Ordet '{{var0}}' ble lagt til ordboken ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "pl": // Polish
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Brak podobnych słów",
context_spellcheck: "Dodaj do słownika",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Próba pobrania słownika ({{var0}})",
toast_dictionary_fail: "Nie udało się pobrać słownika ({{var0}})",
toast_dictionary_success: "Słownik ({{var0}}) został pobrany pomyślnie",
toast_wordadd: "Słowo '{{var0}}' zostało dodane do słownika ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "pt-BR": // Portuguese (Brazil)
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Sem palavras semelhantes",
context_spellcheck: "Adicionar ao Dicionário",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Tentando obter Dicionário ({{var0}})",
toast_dictionary_fail: "Falha ao buscar dicionário ({{var0}})",
toast_dictionary_success: "Dicionário ({{var0}}) obtido com sucesso",
toast_wordadd: "Palavra '{{var0}}' adicionada ao dicionário ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "ro": // Romanian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Fără cuvinte similare",
context_spellcheck: "Adăugați la dicționar",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Încercarea de a prelua dicționar ({{var0}})",
toast_dictionary_fail: "Eroare la preluarea dicționarului ({{var0}})",
toast_dictionary_success: "Dicționarul ({{var0}}) a fost preluat cu succes",
toast_wordadd: "Cuvântul '{{var0}}' a fost adăugat în dicționar ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "ru": // Russian
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Нет похожих слов",
context_spellcheck: "Добавить в словарь",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Попытка получить словарь ({{var0}})",
toast_dictionary_fail: "Не удалось получить словарь ({{var0}})",
toast_dictionary_success: "Словарь ({{var0}}) получен успешно",
toast_wordadd: "Слово '{{var0}}' добавлено в словарь ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "sv": // Swedish
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "Inga liknande ord",
context_spellcheck: "Lägg till ordbok",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Försöker hämta ordbok ({{var0}})",
toast_dictionary_fail: "Det gick inte att hämta ordboken ({{var0}})",
toast_dictionary_success: "Ordbok ({{var0}}) hämtades framgångsrikt",
toast_wordadd: "Ordet '{{var0}}' har lagts till i ordboken ({{var1}})"
2020-09-19 20:49:33 +02:00
};
case "th": // Thai
2020-09-19 20:49:33 +02:00
return {
context_nosimilarwords: "ไม่มีคำที่คล้ายกัน",
context_spellcheck: "เพิ่มในพจนานุกรม",
2021-01-23 21:47:04 +01:00
toast_dictionary: "กำลังพยายามดึงพจนานุกรม ({{var0}})",
toast_dictionary_fail: "ไม่สามารถดึงพจนานุกรม ({{var0}})",
toast_dictionary_success: "ดึงพจนานุกรม ({{var0}}) สำเร็จ",
toast_wordadd: "เพิ่มคำ '{{var0}}' ในพจนานุกรม ({{var1}}) แล้ว"
};
case "tr": // Turkish
return {
context_nosimilarwords: "Benzer kelime yok",
context_spellcheck: "Sözlüğe Ekle",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Sözlük ({{var0}}) getirilmeye çalışılıyor",
toast_dictionary_fail: "Sözlük ({{var0}}) getirilemedi",
toast_dictionary_success: "Sözlük ({{var0}}) başarıyla getirildi",
toast_wordadd: "'{{var0}}' kelimesi, ({{var1}}) sözlüğüne eklendi"
};
case "uk": // Ukrainian
return {
context_nosimilarwords: "Немає подібних слів",
context_spellcheck: "Додати до словника",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Спроба отримати словник ({{var0}})",
toast_dictionary_fail: "Не вдалося отримати словник ({{var0}})",
toast_dictionary_success: "Словник ({{var0}}) отримано успішно",
toast_wordadd: "Слово '{{var0}}' додано до словника ({{var1}})"
};
case "vi": // Vietnamese
return {
context_nosimilarwords: "Không có từ tương tự",
context_spellcheck: "Thêm vào từ điển",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Đang cố gắng tìm nạp Từ điển ({{var0}})",
toast_dictionary_fail: "Không tìm nạp được Từ điển ({{var0}})",
toast_dictionary_success: "Từ điển ({{var0}}) được tìm nạp thành công",
toast_wordadd: "Đã thêm từ '{{var0}}' vào từ điển ({{var1}})"
};
2021-01-15 17:54:22 +01:00
case "zh-CN": // Chinese (China)
return {
context_nosimilarwords: "没有类似的词",
context_spellcheck: "添加到字典",
2021-01-23 21:47:04 +01:00
toast_dictionary: "尝试获取字典 {{var0}} ",
toast_dictionary_fail: "无法获取字典 {{var0}} ",
toast_dictionary_success: "已成功获取字典 {{var0}} ",
toast_wordadd: "将单词 '{{var0}}' 添加到字典 ({{var1}}) 中"
};
2021-01-15 17:54:22 +01:00
case "zh-TW": // Chinese (Taiwan)
return {
context_nosimilarwords: "沒有類似的詞",
context_spellcheck: "添加到字典",
2021-01-23 21:47:04 +01:00
toast_dictionary: "嘗試獲取字典 {{var0}} ",
toast_dictionary_fail: "無法獲取字典 {{var0}} ",
toast_dictionary_success: "已成功獲取字典 {{var0}} ",
toast_wordadd: "將單詞 '{{var0}}' 添加到字典 ({{var1}}) 中"
};
default: // English
return {
context_nosimilarwords: "No similar Words",
context_spellcheck: "Add to Dictionary",
2021-01-23 21:47:04 +01:00
toast_dictionary: "Trying to fetch Dictionary ({{var0}})",
toast_dictionary_fail: "Failed to fetch Dictionary ({{var0}})",
toast_dictionary_success: "Dictionary ({{var0}}) fetched successfully",
toast_wordadd: "Word '{{var0}}' added to Dictionary ({{var1}})"
2020-09-19 20:49:33 +02:00
};
}
}
};
2022-09-01 14:40:11 +02:00
})(window.BDFDB_Global.PluginUtils.buildPlugin(changeLog));
2020-09-25 14:36:36 +02:00
})();