ConceptPortal-public/rsconcept/frontend/src/components/RSInput/tooltip.ts

47 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-12-28 14:04:44 +03:00
import { syntaxTree } from '@codemirror/language';
import { Extension } from '@codemirror/state';
import { hoverTooltip } from '@codemirror/view';
2023-09-27 23:36:51 +03:00
import { EditorState } from '@uiw/react-codemirror';
2023-08-13 21:25:59 +03:00
import { IConstituenta } from '@/models/rsform';
import { findEnvelopingNodes } from '@/utils/codemirror';
import { domTooltipConstituenta } from '@/utils/codemirror';
2023-09-27 23:36:51 +03:00
import { GlobalTokens } from './rslang';
2023-08-15 00:41:09 +03:00
2023-09-27 23:36:51 +03:00
function findAliasAt(pos: number, state: EditorState) {
const { from: lineStart, to: lineEnd, text } = state.doc.lineAt(pos);
const nodes = findEnvelopingNodes(pos, pos, syntaxTree(state), GlobalTokens);
let alias = '';
let start = 0;
let end = 0;
2023-12-28 14:04:44 +03:00
nodes.forEach(node => {
2023-09-27 23:36:51 +03:00
if (node.to <= lineEnd && node.from >= lineStart) {
alias = text.slice(node.from - lineStart, node.to - lineStart);
start = node.from;
end = node.to;
}
});
2023-12-28 14:04:44 +03:00
return { alias, start, end };
2023-08-13 21:25:59 +03:00
}
2023-09-27 23:36:51 +03:00
const globalsHoverTooltip = (items: IConstituenta[]) => {
return hoverTooltip((view, pos) => {
const { alias, start, end } = findAliasAt(pos, view.state);
2023-08-15 00:41:09 +03:00
const cst = items.find(cst => cst.alias === alias);
if (!cst) {
return null;
2023-08-13 21:25:59 +03:00
}
2023-08-15 00:41:09 +03:00
return {
pos: start,
end: end,
above: false,
2023-09-27 23:36:51 +03:00
create: () => domTooltipConstituenta(cst)
2023-12-28 14:04:44 +03:00
};
2023-08-15 00:41:09 +03:00
});
2023-12-28 14:04:44 +03:00
};
2023-08-13 21:25:59 +03:00
2023-09-27 23:36:51 +03:00
export function rsHoverTooltip(items: IConstituenta[]): Extension {
return [globalsHoverTooltip(items)];
2023-12-28 14:04:44 +03:00
}