Skip to content

Commit

Permalink
fix(SelectionContext): save editor state when start to select content…
Browse files Browse the repository at this point in the history
… with mouse (#395)
  • Loading branch information
d3m1d0v authored Oct 2, 2024
1 parent 669d2eb commit 74d3b80
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/extensions/behavior/SelectionContext/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {keydownHandler} from 'prosemirror-keymap';
import {EditorState, Plugin, PluginSpec, TextSelection} from 'prosemirror-state';
import {EditorProps, EditorView} from 'prosemirror-view';
import {type EditorState, Plugin, type PluginSpec, TextSelection} from 'prosemirror-state';
import type {EditorProps, EditorView} from 'prosemirror-view';

import {ActionStorage, ExtensionAuto} from '../../../core';
import {isCodeBlock} from '../../../utils/nodes';
Expand All @@ -22,13 +22,14 @@ export const SelectionContext: ExtensionAuto<SelectionContextOptions> = (builder
}
};

type TinyState = Pick<EditorState, 'doc' | 'selection'>;

class SelectionTooltip implements PluginSpec<unknown> {
private destroyed = false;

private tooltip: TooltipView;
private hideTimeoutRef: ReturnType<typeof setTimeout> | null = null;

private _prevState?: EditorState | null;
private _isMousePressed = false;

constructor(actions: ActionStorage, menuConfig: ContextConfig) {
Expand All @@ -50,14 +51,18 @@ class SelectionTooltip implements PluginSpec<unknown> {
}),
handleDOMEvents: {
mousedown: (view) => {
const startState: TinyState = {
doc: view.state.doc,
selection: view.state.selection,
};
this._isMousePressed = true;
this.cancelTooltipHiding();
this.tooltip.hide(view);

const onMouseUp = () => {
if (this.destroyed) return;
this._isMousePressed = false;
this.update(view, this._prevState);
this.update(view, startState);
};

document.addEventListener('mouseup', onMouseUp, {once: true});
Expand All @@ -78,11 +83,9 @@ class SelectionTooltip implements PluginSpec<unknown> {
};
}

private update(view: EditorView, prevState?: EditorState | null) {
this._prevState = prevState;
private update(view: EditorView, prevState?: TinyState) {
if (this._isMousePressed) return;

this._prevState = null;
this.cancelTooltipHiding();

// Don't show tooltip if editor not mounted to the DOM
Expand Down

0 comments on commit 74d3b80

Please sign in to comment.