Skip to content

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

fix: removed dead code

Elijah Potter9dbc702444ef
diff --git a/packages/obsidian-plugin/src/lint.ts b/packages/obsidian-plugin/src/lint.ts
index 999ef2998..10d05fc81 100644
--- a/packages/obsidian-plugin/src/lint.ts
+++ b/packages/obsidian-plugin/src/lint.ts
@@ -5,21 +5,11 @@ import {
DecorationSet,
WidgetType,
ViewUpdate,
- Command,
logException,
- KeyBinding,
hoverTooltip,
- Tooltip,
- showTooltip,
- gutter,
- GutterMarker,
- PanelConstructor,
- Panel,
- showPanel,
- getPanel
+ Tooltip
} from '@codemirror/view';
import {
- Text,
StateEffect,
StateField,
Extension,
@@ -28,8 +18,7 @@ import {
EditorState,
Facet,
combineConfig,
- RangeSet,
- Range
+ RangeSet
} from '@codemirror/state';
import elt from 'crelt';
@@ -101,17 +90,6 @@ interface LintConfig {
autoPanel?: boolean;
}
-interface LintGutterConfig {
- /// The delay before showing a tooltip when hovering over a lint gutter marker.
- hoverTime?: number;
- /// Optional filter determining which diagnostics show a marker in
- /// the gutter.
- markerFilter?: null | DiagnosticFilter;
- /// Optional filter for diagnostics displayed in a tooltip, which
- /// can also be used to prevent a tooltip appearing.
- tooltipFilter?: null | DiagnosticFilter;
-}
-
class SelectedDiagnostic {
constructor(
readonly from: number,
@@ -123,15 +101,10 @@ class SelectedDiagnostic {
class LintState {
constructor(
readonly diagnostics: DecorationSet,
- readonly panel: PanelConstructor | null,
readonly selected: SelectedDiagnostic | null
) {}
- static init(
- diagnostics: readonly Diagnostic[],
- panel: PanelConstructor | null,
- state: EditorState
- ) {
+ static init(diagnostics: readonly Diagnostic[], state: EditorState) {
// Filter the list of diagnostics for which to create markers
let markedDiagnostics = diagnostics;
const diagnosticFilter = state.facet(lintConfig).markerFilter;
@@ -155,7 +128,7 @@ class LintState {
}),
true
);
- return new LintState(ranges, panel, findDiagnostic(ranges));
+ return new LintState(ranges, findDiagnostic(ranges));
}
}
@@ -207,62 +180,38 @@ export function setDiagnostics(
/// be useful when writing an extension that needs to track these.
export const setDiagnosticsEffect = StateEffect.define<readonly Diagnostic[]>();
-const togglePanel = StateEffect.define<boolean>();
-
const movePanelSelection = StateEffect.define<SelectedDiagnostic>();
const lintState = StateField.define<LintState>({
create() {
- return new LintState(Decoration.none, null, null);
+ return new LintState(Decoration.none, null);
},
update(value, tr) {
if (tr.docChanged && value.diagnostics.size) {
const mapped = value.diagnostics.map(tr.changes);
- let selected = null;
- const panel = value.panel;
+ let selected: SelectedDiagnostic | null = null;
if (value.selected) {
const selPos = tr.changes.mapPos(value.selected.from, 1);
selected =
findDiagnostic(mapped, value.selected.diagnostic, selPos) ||
findDiagnostic(mapped, null, selPos);
}
- if (!mapped.size && panel && tr.state.facet(lintConfig).autoPanel) panel = null;
- value = new LintState(mapped, panel, selected);
+ value = new LintState(mapped, selected);
}
for (const effect of tr.effects) {
if (effect.is(setDiagnosticsEffect)) {
- const panel = !tr.state.facet(lintConfig).autoPanel
- ? value.panel
- : effect.value.length
- ? LintPanel.open
- : null;
- value = LintState.init(effect.value, panel, tr.state);
- } else if (effect.is(togglePanel)) {
- value = new LintState(
- value.diagnostics,
- effect.value ? LintPanel.open : null,
- value.selected
- );
+ value = LintState.init(effect.value, tr.state);
} else if (effect.is(movePanelSelection)) {
- value = new LintState(value.diagnostics, value.panel, effect.value);
+ value = new LintState(value.diagnostics, effect.value);
}
}
return value;
},
- provide: (f) => [
- showPanel.from(f, (val) => val.panel),
- EditorView.decorations.from(f, (s) => s.diagnostics)
- ]
+ provide: (f) => [EditorView.decorations.from(f, (s) => s.diagnostics)]
});
-/// Returns the number of active lint diagnostics in the given state.
-export function diagnosticCount(state: EditorState) {
- const lint = state.field(lintState, false);
- return lint ? lint.diagnostics.size : 0;
-}
-
const activeMark = Decoration.mark({ class: 'cm-lintRange cm-lintRange-active' });
function lintTooltip(view: EditorView, pos: number, side: -1 | 1) {
@@ -305,75 +254,6 @@ function diagnosticsTooltip(view: EditorView, diagnostics: readonly Diagnostic[]
);
}
-/// Command to open and focus the lint panel.
-export const openLintPanel: Command = (view: EditorView) => {
- const field = view.state.field(lintState, false);
- if (!field || !field.panel)
- view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) });
- const panel = getPanel(view, LintPanel.open);
- if (panel) (panel.dom.querySelector('.cm-panel-lint ul') as HTMLElement).focus();
- return true;
-};
-
-/// Command to close the lint panel, when open.
-export const closeLintPanel: Command = (view: EditorView) => {
- const field = view.state.field(lintState, false);
- if (!field || !field.panel) return false;
- view.dispatch({ effects: togglePanel.of(false) });
- return true;
-};
-
-/// Move the selection to the next diagnostic.
-export const nextDiagnostic: Command = (view: EditorView) => {
- const field = view.state.field(lintState, false);
- if (!field) return false;
- const sel = view.state.selection.main;
- let next = field.diagnostics.iter(sel.to + 1);
- if (!next.value) {
- next = field.diagnostics.iter(0);
- if (!next.value || (next.from == sel.from && next.to == sel.to)) return false;
- }
- view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
- return true;
-};
-
-/// Move the selection to the previous diagnostic.
-export const previousDiagnostic: Command = (view: EditorView) => {
- const { state } = view;
- const field = state.field(lintState, false);
- if (!field) return false;
- const sel = state.selection.main;
- let prevFrom: number | undefined,
- prevTo: number | undefined,
- lastFrom: number | undefined,
- lastTo: number | undefined;
- field.diagnostics.between(0, state.doc.length, (from, to) => {
- if (to < sel.to && (prevFrom == null || prevFrom < from)) {
- prevFrom = from;
- prevTo = to;
- }
- if (lastFrom == null || from > lastFrom) {
- lastFrom = from;
- lastTo = to;
- }
- });
- if (lastFrom == null || (prevFrom == null && lastFrom == sel.from)) return false;
- view.dispatch({
- selection: { anchor: prevFrom ?? lastFrom, head: prevTo ?? lastTo },
- scrollIntoView: true
- });
- return true;
-};
-
-/// A set of default key bindings for the lint functionality.
-///
-/// - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](#lint.openLintPanel)
-/// - F8: [`nextDiagnostic`](#lint.nextDiagnostic)
-export const lintKeymap: readonly KeyBinding[] = [
- { key: 'Mod-Shift-m', run: openLintPanel, preventDefault: true },
- { key: 'F8', run: nextDiagnostic }
-];
-
/// The type of a function that produces diagnostics.
export type LintSource = (
view: EditorView
@@ -558,215 +438,13 @@ class DiagnosticWidget extends WidgetType {
}
}
-class PanelItem {
- id = 'item_' + Math.floor(Math.random() * 0xffffffff).toString(16);
- dom: HTMLElement;
-
- constructor(
- view: EditorView,
- readonly diagnostic: Diagnostic
- ) {
- this.dom = renderDiagnostic(view, diagnostic, true);
- this.dom.id = this.id;
- this.dom.setAttribute('role', 'option');
- }
-}
-
-class LintPanel implements Panel {
- items: PanelItem[] = [];
- dom: HTMLElement;
- list: HTMLElement;
-
- constructor(readonly view: EditorView) {
- const onkeydown = (event: KeyboardEvent) => {
- if (event.keyCode == 27) {
- // Escape
- closeLintPanel(this.view);
- this.view.focus();
- } else if (event.keyCode == 38 || event.keyCode == 33) {
- // ArrowUp, PageUp
- this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
- } else if (event.keyCode == 40 || event.keyCode == 34) {
- // ArrowDown, PageDown
- this.moveSelection((this.selectedIndex + 1) % this.items.length);
- } else if (event.keyCode == 36) {
- // Home
- this.moveSelection(0);
- } else if (event.keyCode == 35) {
- // End
- this.moveSelection(this.items.length - 1);
- } else if (event.keyCode == 13) {
- // Enter
- this.view.focus();
- } else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) {
- // A-Z
- const { diagnostic } = this.items[this.selectedIndex],
- keys = assignKeys(diagnostic.actions);
- for (let i = 0; i < keys.length; i++)
- if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) {
- const found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
- if (found) diagnostic.actions![i].apply(view, found.from, found.to);
- }
- } else {
- return;
- }
- event.preventDefault();
- };
- const onclick = (event: MouseEvent) => {
- for (let i = 0; i < this.items.length; i++) {
- if (this.items[i].dom.contains(event.target as HTMLElement)) this.moveSelection(i);
- }
- };
-
- this.list = elt('ul', {
- tabIndex: 0,
- role: 'listbox',
- 'aria-label': this.view.state.phrase('Diagnostics'),
- onkeydown,
- onclick
- });
- this.dom = elt(
- 'div',
- { class: 'cm-panel-lint' },
- this.list,
- elt(
- 'button',
- {
- type: 'button',
- name: 'close',
- 'aria-label': this.view.state.phrase('close'),
- onclick: () => closeLintPanel(this.view)
- },
- '×'
- )
- );
- this.update();
- }
-
- get selectedIndex() {
- const selected = this.view.state.field(lintState).selected;
- if (!selected) return -1;
- for (let i = 0; i < this.items.length; i++)
- if (this.items[i].diagnostic == selected.diagnostic) return i;
- return -1;
- }
-
- update() {
- const { diagnostics, selected } = this.view.state.field(lintState);
- let i = 0,
- needsSync = false,
- newSelectedItem: PanelItem | null = null;
- diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
- let found = -1,
- item;
- for (let j = i; j < this.items.length; j++)
- if (this.items[j].diagnostic == spec.diagnostic) {
- found = j;
- break;
- }
- if (found < 0) {
- item = new PanelItem(this.view, spec.diagnostic);
- this.items.splice(i, 0, item);
- needsSync = true;
- } else {
- item = this.items[found];
- if (found > i) {
- this.items.splice(i, found - i);
- needsSync = true;
- }
- }
- if (selected && item.diagnostic == selected.diagnostic) {
- if (!item.dom.hasAttribute('aria-selected')) {
- item.dom.setAttribute('aria-selected', 'true');
- newSelectedItem = item;
- }
- } else if (item.dom.hasAttribute('aria-selected')) {
- item.dom.removeAttribute('aria-selected');
- }
- i++;
- });
- while (
- i < this.items.length &&
- !(this.items.length == 1 && this.items[0].diagnostic.from < 0)
- ) {
- needsSync = true;
- this.items.pop();
- }
- if (this.items.length == 0) {
- this.items.push(
- new PanelItem(this.view, {
- from: -1,
- to: -1,
- severity: 'info',
- message: this.view.state.phrase('No diagnostics')
- })
- );
- needsSync = true;
- }
- if (newSelectedItem) {
- this.list.setAttribute('aria-activedescendant', newSelectedItem!.id);
- this.view.requestMeasure({
- key: this,
- read: () => ({
- sel: newSelectedItem!.dom.getBoundingClientRect(),
- panel: this.list.getBoundingClientRect()
- }),
- write: ({ sel, panel }) => {
- const scaleY = panel.height / this.list.offsetHeight;
- if (sel.top < panel.top) this.list.scrollTop -= (panel.top - sel.top) / scaleY;
- else if (sel.bottom > panel.bottom)
- this.list.scrollTop += (sel.bottom - panel.bottom) / scaleY;
- }
- });
- } else if (this.selectedIndex < 0) {
- this.list.removeAttribute('aria-activedescendant');
- }
- if (needsSync) this.sync();
- }
-
- sync() {
- let domPos: ChildNode | null = this.list.firstChild;
- function rm() {
- const prev = domPos!;
- domPos = prev.nextSibling;
- prev.remove();
- }
-
- for (const item of this.items) {
- if (item.dom.parentNode == this.list) {
- while (domPos != item.dom) rm();
- domPos = item.dom.nextSibling;
- } else {
- this.list.insertBefore(item.dom, domPos);
- }
- }
- while (domPos) rm();
- }
-
- moveSelection(selectedIndex: number) {
- if (this.selectedIndex < 0) return;
- const field = this.view.state.field(lintState);
- const selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
- if (!selection) return;
- this.view.dispatch({
- selection: { anchor: selection.from, head: selection.to },
- scrollIntoView: true,
- effects: movePanelSelection.of(selection)
- });
- }
-
- static open(view: EditorView) {
- return new LintPanel(view);
- }
-}
-
function svg(content: string, attrs = `viewBox="0 0 40 40"`) {
return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;
}
function underline(color: string) {
return svg(
- `<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`,
+ `<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width="1"/>`,
`width="6" height="3"`
);
}
@@ -895,177 +573,6 @@ const baseTheme = EditorView.baseTheme({
}
});
-function severityWeight(sev: Severity) {
- return sev == 'error' ? 4 : sev == 'warning' ? 3 : sev == 'info' ? 2 : 1;
-}
-
-class LintGutterMarker extends GutterMarker {
- severity: Severity;
- constructor(readonly diagnostics: readonly Diagnostic[]) {
- super();
- this.severity = diagnostics.reduce(
- (max, d) => (severityWeight(max) < severityWeight(d.severity) ? d.severity : max),
- 'hint' as Severity
- );
- }
-
- toDOM(view: EditorView) {
- const elt = document.createElement('div');
- elt.className = 'cm-lint-marker cm-lint-marker-' + this.severity;
-
- let diagnostics = this.diagnostics;
- const diagnosticsFilter = view.state.facet(lintGutterConfig).tooltipFilter;
- if (diagnosticsFilter) diagnostics = diagnosticsFilter(diagnostics, view.state);
-
- if (diagnostics.length) elt.onmouseover = () => gutterMarkerMouseOver(view, elt, diagnostics);
-
- return elt;
- }
-}
-
-const enum Hover {
- Time = 300,
- Margin = 10
-}
-
-function trackHoverOn(view: EditorView, marker: HTMLElement) {
- const mousemove = (event: MouseEvent) => {
- const rect = marker.getBoundingClientRect();
- if (
- event.clientX > rect.left - Hover.Margin &&
- event.clientX < rect.right + Hover.Margin &&
- event.clientY > rect.top - Hover.Margin &&
- event.clientY < rect.bottom + Hover.Margin
- )
- return;
- for (let target = event.target as Node | null; target; target = target.parentNode) {
- if (target.nodeType == 1 && (target as HTMLElement).classList.contains('cm-tooltip-lint'))
- return;
- }
- window.removeEventListener('mousemove', mousemove);
- if (view.state.field(lintGutterTooltip))
- view.dispatch({ effects: setLintGutterTooltip.of(null) });
- };
- window.addEventListener('mousemove', mousemove);
-}
-
-function gutterMarkerMouseOver(
- view: EditorView,
- marker: HTMLElement,
- diagnostics: readonly Diagnostic[]
-) {
- function hovered() {
- const line = view.elementAtHeight(marker.getBoundingClientRect().top + 5 - view.documentTop);
- const linePos = view.coordsAtPos(line.from);
- if (linePos) {
- view.dispatch({
- effects: setLintGutterTooltip.of({
- pos: line.from,
- above: false,
- create() {
- return {
- dom: diagnosticsTooltip(view, diagnostics),
- getCoords: () => marker.getBoundingClientRect()
- };
- }
- })
- });
- }
- marker.onmouseout = marker.onmousemove = null;
- trackHoverOn(view, marker);
- }
-
- const { hoverTime } = view.state.facet(lintGutterConfig);
-
- let hoverTimeout = setTimeout(hovered, hoverTime);
- marker.onmouseout = () => {
- clearTimeout(hoverTimeout);
- marker.onmouseout = marker.onmousemove = null;
- };
- marker.onmousemove = () => {
- clearTimeout(hoverTimeout);
- hoverTimeout = setTimeout(hovered, hoverTime);
- };
-}
-
-function markersForDiagnostics(doc: Text, diagnostics: readonly Diagnostic[]) {
- const byLine: { [line: number]: Diagnostic[] } = Object.create(null);
- for (const diagnostic of diagnostics) {
- const line = doc.lineAt(diagnostic.from);
- (byLine[line.from] || (byLine[line.from] = [])).push(diagnostic);
- }
- const markers: Range<GutterMarker>[] = [];
- for (const line in byLine) {
- markers.push(new LintGutterMarker(byLine[line]).range(+line));
- }
- return RangeSet.of(markers, true);
-}
-
-const lintGutterExtension = gutter({
- class: 'cm-gutter-lint',
- markers: (view) => view.state.field(lintGutterMarkers)
-});
-
-const lintGutterMarkers = StateField.define<RangeSet<GutterMarker>>({
- create() {
- return RangeSet.empty;
- },
- update(markers, tr) {
- markers = markers.map(tr.changes);
- const diagnosticFilter = tr.state.facet(lintGutterConfig).markerFilter;
- for (const effect of tr.effects) {
- if (effect.is(setDiagnosticsEffect)) {
- let diagnostics = effect.value;
- if (diagnosticFilter) diagnostics = diagnosticFilter(diagnostics || [], tr.state);
- markers = markersForDiagnostics(tr.state.doc, diagnostics.slice(0));
- }
- }
- return markers;
- }
-});
-
-const setLintGutterTooltip = StateEffect.define<Tooltip | null>();
-
-const lintGutterTooltip = StateField.define<Tooltip | null>({
- create() {
- return null;
- },
- update(tooltip, tr) {
- if (tooltip && tr.docChanged)
- tooltip = hideTooltip(tr, tooltip)
- ? null
- : { ...tooltip, pos: tr.changes.mapPos(tooltip.pos) };
- return tr.effects.reduce((t, e) => (e.is(setLintGutterTooltip) ? e.value : t), tooltip);
- },
- provide: (field) => showTooltip.from(field)
-});
-
-const lintGutterTheme = EditorView.baseTheme({
- '.cm-gutter-lint': {
- width: '1.4em',
- '& .cm-gutterElement': {
- padding: '.2em'
- }
- },
- '.cm-lint-marker': {
- width: '1em',
- height: '1em'
- },
- '.cm-lint-marker-info': {
- content: svg(
- `<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>`
- )
- },
- '.cm-lint-marker-warning': {
- content: svg(
- `<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`
- )
- },
- '.cm-lint-marker-error': {
- content: svg(`<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`)
- }
-});
-
const lintExtensions = [
lintState,
EditorView.decorations.compute([lintState], (state) => {
@@ -1078,29 +585,6 @@ const lintExtensions = [
baseTheme
];
-const lintGutterConfig = Facet.define<LintGutterConfig, Required<LintGutterConfig>>({
- combine(configs) {
- return combineConfig(configs, {
- hoverTime: Hover.Time,
- markerFilter: null,
- tooltipFilter: null
- });
- }
-});
-
-/// Returns an extension that installs a gutter showing markers for
-/// each line that has diagnostics, which can be hovered over to see
-/// the diagnostics.
-export function lintGutter(config: LintGutterConfig = {}): Extension {
- return [
- lintGutterConfig.of(config),
- lintGutterMarkers,
- lintGutterExtension,
- lintGutterTheme,
- lintGutterTooltip
- ];
-}
-
/// Iterate over the marked diagnostics for the given editor state,
/// calling `f` for each of them. Note that, if the document changed
/// since the diagnostics were created, the `Diagnostic` object will