Total Complexity | 6 |
Complexity/F | 2 |
Lines of Code | 42 |
Function Count | 3 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import { inputRules, InputRule } from 'prosemirror-inputrules'; |
||
2 | import { TextSelection } from 'prosemirror-state'; |
||
3 | import SmileyConf from '../../custom/SmileyConf'; |
||
4 | |||
5 | /** |
||
6 | * Smiley input rule |
||
7 | * |
||
8 | * @returns {InputRule} |
||
9 | */ |
||
10 | export function smileyRule() { |
||
11 | return new InputRule(SmileyConf.getRegex(), ((state, match) => { |
||
12 | const { tr } = state; |
||
13 | const syntax = match[0]; |
||
14 | |||
15 | // get icon corresponding to the captured group |
||
16 | let group = 0; |
||
17 | for (let i = 0; i < match.length; i += 1) { |
||
18 | if (i > 0 && match[i] === syntax) { |
||
19 | group = i; |
||
20 | break; |
||
21 | } |
||
22 | } |
||
23 | const { icon } = SmileyConf.getSmileys()[group - 1]; |
||
24 | |||
25 | tr.setSelection(TextSelection.create(tr.doc, tr.selection.from, tr.selection.from - syntax.length + 1)); |
||
26 | return tr.replaceSelectionWith(state.schema.nodes.smiley.create({ icon, syntax })); |
||
27 | })); |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * Rules for transforming user input |
||
32 | * |
||
33 | * @param {prosemirrorModel.Schema} schema |
||
34 | * @returns {Plugin} |
||
35 | */ |
||
36 | export default function buildInputRules(schema) { |
||
37 | const rules = []; |
||
38 | if (schema.nodes.smiley) { |
||
39 | rules.push(smileyRule()); |
||
40 | } |
||
41 | return inputRules({ rules }); |
||
42 | } |
||
43 |