Skip to content

Commit

Permalink
feat(YfmCut): auto openning yfm-cut if selection is inside cut's cont…
Browse files Browse the repository at this point in the history
…ent (#46)
  • Loading branch information
d3m1d0v authored Dec 9, 2022
1 parent 723a79d commit f3084f8
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/extensions/yfm/YfmCut/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {fromYfm} from './fromYfm';
import {getSpec, YfmCutSpecOptions} from './spec';
import {createYfmCut, toYfmCut} from './actions/toYfmCut';
import {backToCutTitle, exitFromCutTitle, liftEmptyBlockFromCut, removeCut} from './commands';
import {cutAutoOpenPlugin} from './plugins/auto-open';

const cutAction = 'toYfmCut';

Expand Down Expand Up @@ -51,6 +52,7 @@ export const YfmCut: ExtensionAuto<YfmCutOptions> = (builder, opts) => {
tokenSpec: fromYfm[CutNode.CutContent],
},
}))
.addPlugin(cutAutoOpenPlugin)
.addAction(cutAction, () => toYfmCut)
.addKeymap(() => ({
Backspace: chainCommands(backToCutTitle, removeCut),
Expand Down
46 changes: 46 additions & 0 deletions src/extensions/yfm/YfmCut/plugins/auto-open.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {Plugin, PluginKey} from 'prosemirror-state';
import type {EditorView} from 'prosemirror-view';
import type {ResolvedPos} from 'prosemirror-model';
import {isTextSelection} from '../../../../utils/selection';
import {cutContentType, cutType} from '../const';

const key = new PluginKey('yfm-cut-auto-open');

export const cutAutoOpenPlugin = () =>
new Plugin({
key,
view(view) {
update(view);
return {
update: (view) => update(view),
};
},
});

function update(view: EditorView) {
const sel = view.state.selection;
const domAtPos = view.domAtPos.bind(view);
if (isTextSelection(sel)) {
if (sel.$cursor) {
openParentYfmCuts(sel.$cursor, domAtPos);
} else {
openParentYfmCuts(sel.$head, domAtPos);
openParentYfmCuts(sel.$anchor, domAtPos);
}
}
}

function openParentYfmCuts($pos: ResolvedPos, domAtPos: EditorView['domAtPos']): void {
let {depth} = $pos;
const {schema} = $pos.parent.type;
while (depth > 0) {
if ($pos.node(depth).type === cutContentType(schema)) {
if ($pos.node(depth - 1).type === cutType(schema)) {
const {node: cutDomNode} = domAtPos($pos.start(depth - 1), 0);
(cutDomNode as Element).classList.add('open');
depth--;
}
}
depth--;
}
}

0 comments on commit f3084f8

Please sign in to comment.