Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(obsidian): misc. QoL improvements (#1382)

Elijah Potterdc10cc71113c
diff --git a/packages/obsidian-plugin/src/HarperSettingTab.ts b/packages/obsidian-plugin/src/HarperSettingTab.ts
index 5e90c0b41..faa1e8abe 100644
--- a/packages/obsidian-plugin/src/HarperSettingTab.ts
+++ b/packages/obsidian-plugin/src/HarperSettingTab.ts
@@ -4,12 +4,13 @@ import { startCase } from 'lodash-es';
import { type App, PluginSettingTab, Setting } from 'obsidian';
import type State from './State.js';
import type { Settings } from './State.js';
+import { dictToString, stringToDict } from './dictUtils';
import type HarperPlugin from './index.js';
export class HarperSettingTab extends PluginSettingTab {
private state: State;
private settings: Settings;
- private descriptions: Record<string, string>;
+ private descriptionsHTML: Record<string, string>;
private plugin: HarperPlugin;
constructor(app: App, plugin: HarperPlugin, state: State) {
@@ -17,8 +18,14 @@ export class HarperSettingTab extends PluginSettingTab {
this.state = state;
this.plugin = plugin;
- this.updateDescriptions();
- this.updateSettings();
+ // Poll every so often
+ const update = () => {
+ this.updateDescriptions();
+ this.updateSettings();
+ setTimeout(update, 1000);
+ };
+
+ update();
}
updateSettings() {
@@ -28,8 +35,8 @@ export class HarperSettingTab extends PluginSettingTab {
}
updateDescriptions() {
- this.state.getDescriptions().then((v) => {
- this.descriptions = v;
+ this.state.getDescriptionHTML().then((v) => {
+ this.descriptionsHTML = v;
});
}
@@ -37,12 +44,17 @@ export class HarperSettingTab extends PluginSettingTab {
const { containerEl } = this;
containerEl.empty();
- new Setting(containerEl).setName('Use Web Worker').addToggle((toggle) =>
- toggle.setValue(this.settings.useWebWorker).onChange(async (value) => {
- this.settings.useWebWorker = value;
- await this.state.initializeFromSettings(this.settings);
- }),
- );
+ new Setting(containerEl)
+ .setName('Use Web Worker')
+ .setDesc(
+ 'Whether to run the Harper engine in a separate thread. Improves stability and speed at the cost of memory.',
+ )
+ .addToggle((toggle) =>
+ toggle.setValue(this.settings.useWebWorker).onChange(async (value) => {
+ this.settings.useWebWorker = value;
+ await this.state.initializeFromSettings(this.settings);
+ }),
+ );
new Setting(containerEl).setName('English Dialect').addDropdown((dropdown) => {
dropdown
@@ -59,6 +71,20 @@ export class HarperSettingTab extends PluginSettingTab {
});
});
+ new Setting(containerEl)
+ .setName('Personal Dictionary')
+ .setDesc(
+ 'Make edits to your personal dictionary. Add names, places, or terms you use often. Each line should contain its own word.',
+ )
+ .addTextArea((ta) => {
+ ta.inputEl.cols = 20;
+ ta.setValue(dictToString(this.settings.userDictionary ?? [''])).onChange(async (v) => {
+ const dict = stringToDict(v);
+ this.settings.userDictionary = dict;
+ await this.state.initializeFromSettings(this.settings);
+ });
+ });
+
new Setting(containerEl)
.setName('Delay')
.setDesc(
@@ -109,20 +135,30 @@ export class HarperSettingTab extends PluginSettingTab {
renderLintSettings(searchQuery: string, containerEl: HTMLElement) {
containerEl.innerHTML = '';
+ const queryLower = searchQuery.toLowerCase();
+
for (const setting of Object.keys(this.settings.lintSettings)) {
const value = this.settings.lintSettings[setting];
- const description = this.descriptions[setting];
+ const descriptionHTML = this.descriptionsHTML[setting];
if (
searchQuery !== '' &&
- !(description.contains(searchQuery) || setting.contains(searchQuery))
+ !(
+ descriptionHTML.toLowerCase().contains(queryLower) ||
+ setting.toLowerCase().contains(queryLower)
+ )
) {
continue;
}
+ const fragment = document.createDocumentFragment();
+ const template = document.createElement('template');
+ template.innerHTML = descriptionHTML;
+ fragment.appendChild(template.content);
+
new Setting(containerEl)
.setName(startCase(setting))
- .setDesc(description)
+ .setDesc(fragment)
.addDropdown((dropdown) =>
dropdown
.addOption('default', 'Default')
diff --git a/packages/obsidian-plugin/src/State.test.ts b/packages/obsidian-plugin/src/State.test.ts
index 10a4c5ce1..d329228ae 100644
--- a/packages/obsidian-plugin/src/State.test.ts
+++ b/packages/obsidian-plugin/src/State.test.ts
@@ -77,7 +77,7 @@ test('Lint settings and descriptions have the same keys', async () => {
const state = createEphemeralState();
const settings = await state.getSettings();
- const descriptions = await state.getDescriptions();
+ const descriptions = await state.getDescriptionHTML();
expect(Object.keys(descriptions).sort()).toStrictEqual(Object.keys(settings.lintSettings).sort());
});
diff --git a/packages/obsidian-plugin/src/State.ts b/packages/obsidian-plugin/src/State.ts
index 9bb41d4df..27278ec05 100644
--- a/packages/obsidian-plugin/src/State.ts
+++ b/packages/obsidian-plugin/src/State.ts
@@ -104,7 +104,11 @@ export default class State {
const actions = lint.suggestions().map((sug) => {
return {
- name: suggestionToLabel(sug),
+ name:
+ sug.kind() == SuggestionKind.Replace
+ ? sug.get_replacement_text()
+ : suggestionToLabel(sug),
+ title: suggestionToLabel(sug),
apply: (view) => {
if (sug.kind() === SuggestionKind.Remove) {
view.dispatch({
@@ -139,7 +143,8 @@ export default class State {
const word = lint.get_problem_text();
actions.push({
- name: `Add “${word}” to your dictionary`,
+ name: '📖',
+ title: `Add “${word}” to your dictionary`,
apply: (view) => {
this.harper.importWords([word]);
this.reinitialize();
@@ -189,8 +194,8 @@ export default class State {
};
}
- public async getDescriptions(): Promise<Record<string, string>> {
- return await this.harper.getLintDescriptions();
+ public async getDescriptionHTML(): Promise<Record<string, string>> {
+ return await this.harper.getLintDescriptionsHTML();
}
/** Get a reference to the CM editor extensions.
@@ -248,7 +253,7 @@ function suggestionToLabel(sug: Suggestion) {
if (sug.kind() === SuggestionKind.Remove) {
return 'Remove';
} else if (sug.kind() === SuggestionKind.Replace) {
- return `Replace with “${sug.get_replacement_text()}”`;
+ return `“Replace with ${sug.get_replacement_text()}”`;
} else if (sug.kind() === SuggestionKind.InsertAfter) {
return `Insert “${sug.get_replacement_text()}” after this.`;
}
diff --git a/packages/obsidian-plugin/src/dictUtils.test.ts b/packages/obsidian-plugin/src/dictUtils.test.ts
new file mode 100644
index 000000000..14698e221
--- /dev/null
+++ b/packages/obsidian-plugin/src/dictUtils.test.ts
@@ -0,0 +1,85 @@
+import { expect, test } from 'vitest';
+import { dictToString, stringToDict } from './dictUtils';
+
+test('Dictionary values are reversible', () => {
+ const possibleDicts = [
+ [
+ 'lynx',
+ 'capybara',
+ 'ibex',
+ 'wombat',
+ 'ocelot',
+ 'pangolin',
+ 'stoat',
+ 'vole',
+ 'caracal',
+ 'gazelle',
+ ],
+ [
+ 'azurite',
+ 'feldspar',
+ 'gabbro',
+ 'peridot',
+ 'chalcedony',
+ 'rutile',
+ 'aragonite',
+ 'spinel',
+ 'pyrite',
+ 'malachite',
+ ],
+ [
+ 'auscultation',
+ 'phlebotomy',
+ 'sutures',
+ 'anticoagulant',
+ 'intubation',
+ 'tachycardia',
+ 'catheter',
+ 'defibrillator',
+ 'ischemia',
+ 'hematoma',
+ ],
+ [
+ 'fennel',
+ 'sunchoke',
+ 'burrata',
+ 'tamarind',
+ 'sumac',
+ 'cassava',
+ 'farro',
+ 'durian',
+ 'romanesco',
+ 'chicory',
+ ],
+ [
+ 'taciturn',
+ 'indelible',
+ 'verdant',
+ 'oblique',
+ 'incisive',
+ 'mellifluous',
+ 'crepuscular',
+ 'effulgent',
+ 'sinistral',
+ 'pellucid',
+ ],
+ ];
+
+ for (const set of possibleDicts) {
+ const text = dictToString(set);
+ const back = stringToDict(text);
+
+ expect(back).toStrictEqual(set);
+ }
+});
+
+test('Can handle multiple newlines', () => {
+ const dictText = 'worda\n\nwordb';
+
+ expect(stringToDict(dictText)).toStrictEqual(['worda', 'wordb']);
+});
+
+test('Can handle carriage returns', () => {
+ const dictText = 'worda\r\n\r\nwordb\r\nwordc';
+ expect(stringToDict(dictText)).toStrictEqual(['worda', 'wordb', 'wordc']);
+});
diff --git a/packages/obsidian-plugin/src/dictUtils.ts b/packages/obsidian-plugin/src/dictUtils.ts
new file mode 100644
index 000000000..63ef7a80b
--- /dev/null
+++ b/packages/obsidian-plugin/src/dictUtils.ts
@@ -0,0 +1,12 @@
+/** Converts the content of a text area to viable dictionary values. */
+export function stringToDict(s: string): string[] {
+ return s
+ .split('\n')
+ .map((s) => s.trim())
+ .filter((v) => v.length > 0);
+}
+
+/** Converts the content of a text area to viable dictionary values. */
+export function dictToString(values: string[]): string {
+ return values.map((v) => v.trim()).join('\n');
+}
diff --git a/packages/obsidian-plugin/src/lint.ts b/packages/obsidian-plugin/src/lint.ts
index f41c820fc..ce23b29f2 100644
--- a/packages/obsidian-plugin/src/lint.ts
+++ b/packages/obsidian-plugin/src/lint.ts
@@ -58,6 +58,8 @@ export interface Diagnostic {
export interface Action {
/// The label to show to the user. Should be relatively short.
name: string;
+ /// The value to pass the title property of the button.
+ title: string;
/// The function to call when the user activates this action. Is
/// given the diagnostic's _current_ position, which may have
/// changed since the creation of the diagnostic, due to editing.
@@ -391,37 +393,41 @@ function renderDiagnostic(view: EditorView, diagnostic: Diagnostic, inPanel: boo
{ class: 'cm-diagnosticText' },
diagnostic.renderMessage ? diagnostic.renderMessage(view) : diagnostic.message,
),
- diagnostic.actions?.map((action, i) => {
- let fired = false;
- const click = (e: Event) => {
- e.preventDefault();
- if (fired) return;
- fired = true;
- const found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
- if (found) action.apply(view, found.from, found.to);
- };
- const { name } = action;
- const keyIndex = keys[i] ? name.indexOf(keys[i]) : -1;
- const nameElt =
- keyIndex < 0
- ? name
- : [
- name.slice(0, keyIndex),
- elt('u', name.slice(keyIndex, keyIndex + 1)),
- name.slice(keyIndex + 1),
- ];
- return elt(
- 'button',
- {
- type: 'button',
- class: 'cm-diagnosticAction',
- onclick: click,
- onmousedown: click,
- 'aria-label': ` Action: ${name}${keyIndex < 0 ? '' : ` (access key "${keys[i]})"`}.`,
- },
- nameElt,
- );
- }),
+ elt(
+ 'span',
+ { class: 'cm-diagnosticActionCont' },
+ diagnostic.actions?.map((action, i) => {
+ let fired = false;
+ const click = (e: Event) => {
+ e.preventDefault();
+ if (fired) return;
+ fired = true;
+ const found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
+ if (found) action.apply(view, found.from, found.to);
+ };
+ const { name, title } = action;
+ const keyIndex = keys[i] ? name.indexOf(keys[i]) : -1;
+ const nameElt =
+ keyIndex < 0
+ ? name
+ : [
+ name.slice(0, keyIndex),
+ elt('u', name.slice(keyIndex, keyIndex + 1)),
+ name.slice(keyIndex + 1),
+ ];
+ return elt(
+ 'button',
+ {
+ type: 'button',
+ class: 'cm-diagnosticAction',
+ onclick: click,
+ onmousedown: click,
+ 'aria-label': ` ${title}${keyIndex < 0 ? '' : ` (access key "${keys[i]})"`}.`,
+ },
+ nameElt,
+ );
+ }),
+ ),
diagnostic.ignore &&
elt(
'div',
@@ -499,6 +505,15 @@ const baseTheme = EditorView.baseTheme({
padding: '0.25rem',
},
+ '.cm-diagnosticActionCont': {
+ display: 'flex',
+ flexWrap: 'wrap',
+ justifyContent: 'flex-start',
+ alignItems: 'flex-start',
+ alignContent: 'flex-start',
+ gap: 'var(--size-4-2)',
+ },
+
'.cm-diagnosticAction': {
font: 'inherit',
border: 'none',
@@ -511,7 +526,6 @@ const baseTheme = EditorView.baseTheme({
fontSize: 'var(--font-ui-small)',
borderRadius: 'var(--radius-s)',
whiteSpace: 'nowrap',
- width: '100%',
},
'.cm-tooltip': {