index.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';
  2. import { Slice, Fragment } from 'prosemirror-model';
  3. import { NodeSelection, Selection, TextSelection, AllSelection } from 'prosemirror-state';
  4. /**
  5. Delete the selection, if there is one.
  6. */
  7. const deleteSelection = (state, dispatch) => {
  8. if (state.selection.empty)
  9. return false;
  10. if (dispatch)
  11. dispatch(state.tr.deleteSelection().scrollIntoView());
  12. return true;
  13. };
  14. function atBlockStart(state, view) {
  15. let { $cursor } = state.selection;
  16. if (!$cursor || (view ? !view.endOfTextblock("backward", state)
  17. : $cursor.parentOffset > 0))
  18. return null;
  19. return $cursor;
  20. }
  21. /**
  22. If the selection is empty and at the start of a textblock, try to
  23. reduce the distance between that block and the one before it—if
  24. there's a block directly before it that can be joined, join them.
  25. If not, try to move the selected block closer to the next one in
  26. the document structure by lifting it out of its parent or moving it
  27. into a parent of the previous block. Will use the view for accurate
  28. (bidi-aware) start-of-textblock detection if given.
  29. */
  30. const joinBackward = (state, dispatch, view) => {
  31. let $cursor = atBlockStart(state, view);
  32. if (!$cursor)
  33. return false;
  34. let $cut = findCutBefore($cursor);
  35. // If there is no node before this, try to lift
  36. if (!$cut) {
  37. let range = $cursor.blockRange(), target = range && liftTarget(range);
  38. if (target == null)
  39. return false;
  40. if (dispatch)
  41. dispatch(state.tr.lift(range, target).scrollIntoView());
  42. return true;
  43. }
  44. let before = $cut.nodeBefore;
  45. // Apply the joining algorithm
  46. if (!before.type.spec.isolating && deleteBarrier(state, $cut, dispatch))
  47. return true;
  48. // If the node below has no content and the node above is
  49. // selectable, delete the node below and select the one above.
  50. if ($cursor.parent.content.size == 0 &&
  51. (textblockAt(before, "end") || NodeSelection.isSelectable(before))) {
  52. let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
  53. if (delStep && delStep.slice.size < delStep.to - delStep.from) {
  54. if (dispatch) {
  55. let tr = state.tr.step(delStep);
  56. tr.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)
  57. : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));
  58. dispatch(tr.scrollIntoView());
  59. }
  60. return true;
  61. }
  62. }
  63. // If the node before is an atom, delete it
  64. if (before.isAtom && $cut.depth == $cursor.depth - 1) {
  65. if (dispatch)
  66. dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
  67. return true;
  68. }
  69. return false;
  70. };
  71. /**
  72. A more limited form of [`joinBackward`]($commands.joinBackward)
  73. that only tries to join the current textblock to the one before
  74. it, if the cursor is at the start of a textblock.
  75. */
  76. const joinTextblockBackward = (state, dispatch, view) => {
  77. let $cursor = atBlockStart(state, view);
  78. if (!$cursor)
  79. return false;
  80. let $cut = findCutBefore($cursor);
  81. return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
  82. };
  83. /**
  84. A more limited form of [`joinForward`]($commands.joinForward)
  85. that only tries to join the current textblock to the one after
  86. it, if the cursor is at the end of a textblock.
  87. */
  88. const joinTextblockForward = (state, dispatch, view) => {
  89. let $cursor = atBlockEnd(state, view);
  90. if (!$cursor)
  91. return false;
  92. let $cut = findCutAfter($cursor);
  93. return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
  94. };
  95. function joinTextblocksAround(state, $cut, dispatch) {
  96. let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;
  97. for (; !beforeText.isTextblock; beforePos--) {
  98. if (beforeText.type.spec.isolating)
  99. return false;
  100. let child = beforeText.lastChild;
  101. if (!child)
  102. return false;
  103. beforeText = child;
  104. }
  105. let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;
  106. for (; !afterText.isTextblock; afterPos++) {
  107. if (afterText.type.spec.isolating)
  108. return false;
  109. let child = afterText.firstChild;
  110. if (!child)
  111. return false;
  112. afterText = child;
  113. }
  114. let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);
  115. if (!step || step.from != beforePos ||
  116. step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)
  117. return false;
  118. if (dispatch) {
  119. let tr = state.tr.step(step);
  120. tr.setSelection(TextSelection.create(tr.doc, beforePos));
  121. dispatch(tr.scrollIntoView());
  122. }
  123. return true;
  124. }
  125. function textblockAt(node, side, only = false) {
  126. for (let scan = node; scan; scan = (side == "start" ? scan.firstChild : scan.lastChild)) {
  127. if (scan.isTextblock)
  128. return true;
  129. if (only && scan.childCount != 1)
  130. return false;
  131. }
  132. return false;
  133. }
  134. /**
  135. When the selection is empty and at the start of a textblock, select
  136. the node before that textblock, if possible. This is intended to be
  137. bound to keys like backspace, after
  138. [`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting
  139. commands, as a fall-back behavior when the schema doesn't allow
  140. deletion at the selected point.
  141. */
  142. const selectNodeBackward = (state, dispatch, view) => {
  143. let { $head, empty } = state.selection, $cut = $head;
  144. if (!empty)
  145. return false;
  146. if ($head.parent.isTextblock) {
  147. if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0)
  148. return false;
  149. $cut = findCutBefore($head);
  150. }
  151. let node = $cut && $cut.nodeBefore;
  152. if (!node || !NodeSelection.isSelectable(node))
  153. return false;
  154. if (dispatch)
  155. dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
  156. return true;
  157. };
  158. function findCutBefore($pos) {
  159. if (!$pos.parent.type.spec.isolating)
  160. for (let i = $pos.depth - 1; i >= 0; i--) {
  161. if ($pos.index(i) > 0)
  162. return $pos.doc.resolve($pos.before(i + 1));
  163. if ($pos.node(i).type.spec.isolating)
  164. break;
  165. }
  166. return null;
  167. }
  168. function atBlockEnd(state, view) {
  169. let { $cursor } = state.selection;
  170. if (!$cursor || (view ? !view.endOfTextblock("forward", state)
  171. : $cursor.parentOffset < $cursor.parent.content.size))
  172. return null;
  173. return $cursor;
  174. }
  175. /**
  176. If the selection is empty and the cursor is at the end of a
  177. textblock, try to reduce or remove the boundary between that block
  178. and the one after it, either by joining them or by moving the other
  179. block closer to this one in the tree structure. Will use the view
  180. for accurate start-of-textblock detection if given.
  181. */
  182. const joinForward = (state, dispatch, view) => {
  183. let $cursor = atBlockEnd(state, view);
  184. if (!$cursor)
  185. return false;
  186. let $cut = findCutAfter($cursor);
  187. // If there is no node after this, there's nothing to do
  188. if (!$cut)
  189. return false;
  190. let after = $cut.nodeAfter;
  191. // Try the joining algorithm
  192. if (deleteBarrier(state, $cut, dispatch))
  193. return true;
  194. // If the node above has no content and the node below is
  195. // selectable, delete the node above and select the one below.
  196. if ($cursor.parent.content.size == 0 &&
  197. (textblockAt(after, "start") || NodeSelection.isSelectable(after))) {
  198. let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
  199. if (delStep && delStep.slice.size < delStep.to - delStep.from) {
  200. if (dispatch) {
  201. let tr = state.tr.step(delStep);
  202. tr.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)
  203. : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));
  204. dispatch(tr.scrollIntoView());
  205. }
  206. return true;
  207. }
  208. }
  209. // If the next node is an atom, delete it
  210. if (after.isAtom && $cut.depth == $cursor.depth - 1) {
  211. if (dispatch)
  212. dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
  213. return true;
  214. }
  215. return false;
  216. };
  217. /**
  218. When the selection is empty and at the end of a textblock, select
  219. the node coming after that textblock, if possible. This is intended
  220. to be bound to keys like delete, after
  221. [`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting
  222. commands, to provide a fall-back behavior when the schema doesn't
  223. allow deletion at the selected point.
  224. */
  225. const selectNodeForward = (state, dispatch, view) => {
  226. let { $head, empty } = state.selection, $cut = $head;
  227. if (!empty)
  228. return false;
  229. if ($head.parent.isTextblock) {
  230. if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
  231. return false;
  232. $cut = findCutAfter($head);
  233. }
  234. let node = $cut && $cut.nodeAfter;
  235. if (!node || !NodeSelection.isSelectable(node))
  236. return false;
  237. if (dispatch)
  238. dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  239. return true;
  240. };
  241. function findCutAfter($pos) {
  242. if (!$pos.parent.type.spec.isolating)
  243. for (let i = $pos.depth - 1; i >= 0; i--) {
  244. let parent = $pos.node(i);
  245. if ($pos.index(i) + 1 < parent.childCount)
  246. return $pos.doc.resolve($pos.after(i + 1));
  247. if (parent.type.spec.isolating)
  248. break;
  249. }
  250. return null;
  251. }
  252. /**
  253. Join the selected block or, if there is a text selection, the
  254. closest ancestor block of the selection that can be joined, with
  255. the sibling above it.
  256. */
  257. const joinUp = (state, dispatch) => {
  258. let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;
  259. if (nodeSel) {
  260. if (sel.node.isTextblock || !canJoin(state.doc, sel.from))
  261. return false;
  262. point = sel.from;
  263. }
  264. else {
  265. point = joinPoint(state.doc, sel.from, -1);
  266. if (point == null)
  267. return false;
  268. }
  269. if (dispatch) {
  270. let tr = state.tr.join(point);
  271. if (nodeSel)
  272. tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));
  273. dispatch(tr.scrollIntoView());
  274. }
  275. return true;
  276. };
  277. /**
  278. Join the selected block, or the closest ancestor of the selection
  279. that can be joined, with the sibling after it.
  280. */
  281. const joinDown = (state, dispatch) => {
  282. let sel = state.selection, point;
  283. if (sel instanceof NodeSelection) {
  284. if (sel.node.isTextblock || !canJoin(state.doc, sel.to))
  285. return false;
  286. point = sel.to;
  287. }
  288. else {
  289. point = joinPoint(state.doc, sel.to, 1);
  290. if (point == null)
  291. return false;
  292. }
  293. if (dispatch)
  294. dispatch(state.tr.join(point).scrollIntoView());
  295. return true;
  296. };
  297. /**
  298. Lift the selected block, or the closest ancestor block of the
  299. selection that can be lifted, out of its parent node.
  300. */
  301. const lift = (state, dispatch) => {
  302. let { $from, $to } = state.selection;
  303. let range = $from.blockRange($to), target = range && liftTarget(range);
  304. if (target == null)
  305. return false;
  306. if (dispatch)
  307. dispatch(state.tr.lift(range, target).scrollIntoView());
  308. return true;
  309. };
  310. /**
  311. If the selection is in a node whose type has a truthy
  312. [`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the
  313. selection with a newline character.
  314. */
  315. const newlineInCode = (state, dispatch) => {
  316. let { $head, $anchor } = state.selection;
  317. if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
  318. return false;
  319. if (dispatch)
  320. dispatch(state.tr.insertText("\n").scrollIntoView());
  321. return true;
  322. };
  323. function defaultBlockAt(match) {
  324. for (let i = 0; i < match.edgeCount; i++) {
  325. let { type } = match.edge(i);
  326. if (type.isTextblock && !type.hasRequiredAttrs())
  327. return type;
  328. }
  329. return null;
  330. }
  331. /**
  332. When the selection is in a node with a truthy
  333. [`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a
  334. default block after the code block, and move the cursor there.
  335. */
  336. const exitCode = (state, dispatch) => {
  337. let { $head, $anchor } = state.selection;
  338. if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
  339. return false;
  340. let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));
  341. if (!type || !above.canReplaceWith(after, after, type))
  342. return false;
  343. if (dispatch) {
  344. let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());
  345. tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));
  346. dispatch(tr.scrollIntoView());
  347. }
  348. return true;
  349. };
  350. /**
  351. If a block node is selected, create an empty paragraph before (if
  352. it is its parent's first child) or after it.
  353. */
  354. const createParagraphNear = (state, dispatch) => {
  355. let sel = state.selection, { $from, $to } = sel;
  356. if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)
  357. return false;
  358. let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
  359. if (!type || !type.isTextblock)
  360. return false;
  361. if (dispatch) {
  362. let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
  363. let tr = state.tr.insert(side, type.createAndFill());
  364. tr.setSelection(TextSelection.create(tr.doc, side + 1));
  365. dispatch(tr.scrollIntoView());
  366. }
  367. return true;
  368. };
  369. /**
  370. If the cursor is in an empty textblock that can be lifted, lift the
  371. block.
  372. */
  373. const liftEmptyBlock = (state, dispatch) => {
  374. let { $cursor } = state.selection;
  375. if (!$cursor || $cursor.parent.content.size)
  376. return false;
  377. if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
  378. let before = $cursor.before();
  379. if (canSplit(state.doc, before)) {
  380. if (dispatch)
  381. dispatch(state.tr.split(before).scrollIntoView());
  382. return true;
  383. }
  384. }
  385. let range = $cursor.blockRange(), target = range && liftTarget(range);
  386. if (target == null)
  387. return false;
  388. if (dispatch)
  389. dispatch(state.tr.lift(range, target).scrollIntoView());
  390. return true;
  391. };
  392. /**
  393. Create a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses
  394. a custom function to determine the type of the newly split off block.
  395. */
  396. function splitBlockAs(splitNode) {
  397. return (state, dispatch) => {
  398. let { $from, $to } = state.selection;
  399. if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
  400. if (!$from.parentOffset || !canSplit(state.doc, $from.pos))
  401. return false;
  402. if (dispatch)
  403. dispatch(state.tr.split($from.pos).scrollIntoView());
  404. return true;
  405. }
  406. if (!$from.parent.isBlock)
  407. return false;
  408. if (dispatch) {
  409. let atEnd = $to.parentOffset == $to.parent.content.size;
  410. let tr = state.tr;
  411. if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)
  412. tr.deleteSelection();
  413. let deflt = $from.depth == 0 ? null : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
  414. let splitType = splitNode && splitNode($to.parent, atEnd);
  415. let types = splitType ? [splitType] : atEnd && deflt ? [{ type: deflt }] : undefined;
  416. let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);
  417. if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)) {
  418. if (deflt)
  419. types = [{ type: deflt }];
  420. can = true;
  421. }
  422. if (can) {
  423. tr.split(tr.mapping.map($from.pos), 1, types);
  424. if (!atEnd && !$from.parentOffset && $from.parent.type != deflt) {
  425. let first = tr.mapping.map($from.before()), $first = tr.doc.resolve(first);
  426. if (deflt && $from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt))
  427. tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
  428. }
  429. }
  430. dispatch(tr.scrollIntoView());
  431. }
  432. return true;
  433. };
  434. }
  435. /**
  436. Split the parent block of the selection. If the selection is a text
  437. selection, also delete its content.
  438. */
  439. const splitBlock = splitBlockAs();
  440. /**
  441. Acts like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without
  442. resetting the set of active marks at the cursor.
  443. */
  444. const splitBlockKeepMarks = (state, dispatch) => {
  445. return splitBlock(state, dispatch && (tr => {
  446. let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());
  447. if (marks)
  448. tr.ensureMarks(marks);
  449. dispatch(tr);
  450. }));
  451. };
  452. /**
  453. Move the selection to the node wrapping the current selection, if
  454. any. (Will not select the document node.)
  455. */
  456. const selectParentNode = (state, dispatch) => {
  457. let { $from, to } = state.selection, pos;
  458. let same = $from.sharedDepth(to);
  459. if (same == 0)
  460. return false;
  461. pos = $from.before(same);
  462. if (dispatch)
  463. dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));
  464. return true;
  465. };
  466. /**
  467. Select the whole document.
  468. */
  469. const selectAll = (state, dispatch) => {
  470. if (dispatch)
  471. dispatch(state.tr.setSelection(new AllSelection(state.doc)));
  472. return true;
  473. };
  474. function joinMaybeClear(state, $pos, dispatch) {
  475. let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();
  476. if (!before || !after || !before.type.compatibleContent(after.type))
  477. return false;
  478. if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {
  479. if (dispatch)
  480. dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
  481. return true;
  482. }
  483. if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))
  484. return false;
  485. if (dispatch)
  486. dispatch(state.tr
  487. .clearIncompatible($pos.pos, before.type, before.contentMatchAt(before.childCount))
  488. .join($pos.pos)
  489. .scrollIntoView());
  490. return true;
  491. }
  492. function deleteBarrier(state, $cut, dispatch) {
  493. let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;
  494. if (before.type.spec.isolating || after.type.spec.isolating)
  495. return false;
  496. if (joinMaybeClear(state, $cut, dispatch))
  497. return true;
  498. let canDelAfter = $cut.parent.canReplace($cut.index(), $cut.index() + 1);
  499. if (canDelAfter &&
  500. (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&
  501. match.matchType(conn[0] || after.type).validEnd) {
  502. if (dispatch) {
  503. let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;
  504. for (let i = conn.length - 1; i >= 0; i--)
  505. wrap = Fragment.from(conn[i].create(null, wrap));
  506. wrap = Fragment.from(before.copy(wrap));
  507. let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));
  508. let joinAt = end + 2 * conn.length;
  509. if (canJoin(tr.doc, joinAt))
  510. tr.join(joinAt);
  511. dispatch(tr.scrollIntoView());
  512. }
  513. return true;
  514. }
  515. let selAfter = Selection.findFrom($cut, 1);
  516. let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);
  517. if (target != null && target >= $cut.depth) {
  518. if (dispatch)
  519. dispatch(state.tr.lift(range, target).scrollIntoView());
  520. return true;
  521. }
  522. if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) {
  523. let at = before, wrap = [];
  524. for (;;) {
  525. wrap.push(at);
  526. if (at.isTextblock)
  527. break;
  528. at = at.lastChild;
  529. }
  530. let afterText = after, afterDepth = 1;
  531. for (; !afterText.isTextblock; afterText = afterText.firstChild)
  532. afterDepth++;
  533. if (at.canReplace(at.childCount, at.childCount, afterText.content)) {
  534. if (dispatch) {
  535. let end = Fragment.empty;
  536. for (let i = wrap.length - 1; i >= 0; i--)
  537. end = Fragment.from(wrap[i].copy(end));
  538. let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));
  539. dispatch(tr.scrollIntoView());
  540. }
  541. return true;
  542. }
  543. }
  544. return false;
  545. }
  546. function selectTextblockSide(side) {
  547. return function (state, dispatch) {
  548. let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
  549. let depth = $pos.depth;
  550. while ($pos.node(depth).isInline) {
  551. if (!depth)
  552. return false;
  553. depth--;
  554. }
  555. if (!$pos.node(depth).isTextblock)
  556. return false;
  557. if (dispatch)
  558. dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));
  559. return true;
  560. };
  561. }
  562. /**
  563. Moves the cursor to the start of current text block.
  564. */
  565. const selectTextblockStart = selectTextblockSide(-1);
  566. /**
  567. Moves the cursor to the end of current text block.
  568. */
  569. const selectTextblockEnd = selectTextblockSide(1);
  570. // Parameterized commands
  571. /**
  572. Wrap the selection in a node of the given type with the given
  573. attributes.
  574. */
  575. function wrapIn(nodeType, attrs = null) {
  576. return function (state, dispatch) {
  577. let { $from, $to } = state.selection;
  578. let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);
  579. if (!wrapping)
  580. return false;
  581. if (dispatch)
  582. dispatch(state.tr.wrap(range, wrapping).scrollIntoView());
  583. return true;
  584. };
  585. }
  586. /**
  587. Returns a command that tries to set the selected textblocks to the
  588. given node type with the given attributes.
  589. */
  590. function setBlockType(nodeType, attrs = null) {
  591. return function (state, dispatch) {
  592. let applicable = false;
  593. for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {
  594. let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];
  595. state.doc.nodesBetween(from, to, (node, pos) => {
  596. if (applicable)
  597. return false;
  598. if (!node.isTextblock || node.hasMarkup(nodeType, attrs))
  599. return;
  600. if (node.type == nodeType) {
  601. applicable = true;
  602. }
  603. else {
  604. let $pos = state.doc.resolve(pos), index = $pos.index();
  605. applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);
  606. }
  607. });
  608. }
  609. if (!applicable)
  610. return false;
  611. if (dispatch) {
  612. let tr = state.tr;
  613. for (let i = 0; i < state.selection.ranges.length; i++) {
  614. let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];
  615. tr.setBlockType(from, to, nodeType, attrs);
  616. }
  617. dispatch(tr.scrollIntoView());
  618. }
  619. return true;
  620. };
  621. }
  622. function markApplies(doc, ranges, type) {
  623. for (let i = 0; i < ranges.length; i++) {
  624. let { $from, $to } = ranges[i];
  625. let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;
  626. doc.nodesBetween($from.pos, $to.pos, node => {
  627. if (can)
  628. return false;
  629. can = node.inlineContent && node.type.allowsMarkType(type);
  630. });
  631. if (can)
  632. return true;
  633. }
  634. return false;
  635. }
  636. /**
  637. Create a command function that toggles the given mark with the
  638. given attributes. Will return `false` when the current selection
  639. doesn't support that mark. This will remove the mark if any marks
  640. of that type exist in the selection, or add it otherwise. If the
  641. selection is empty, this applies to the [stored
  642. marks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the
  643. document.
  644. */
  645. function toggleMark(markType, attrs = null) {
  646. return function (state, dispatch) {
  647. let { empty, $cursor, ranges } = state.selection;
  648. if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType))
  649. return false;
  650. if (dispatch) {
  651. if ($cursor) {
  652. if (markType.isInSet(state.storedMarks || $cursor.marks()))
  653. dispatch(state.tr.removeStoredMark(markType));
  654. else
  655. dispatch(state.tr.addStoredMark(markType.create(attrs)));
  656. }
  657. else {
  658. let has = false, tr = state.tr;
  659. for (let i = 0; !has && i < ranges.length; i++) {
  660. let { $from, $to } = ranges[i];
  661. has = state.doc.rangeHasMark($from.pos, $to.pos, markType);
  662. }
  663. for (let i = 0; i < ranges.length; i++) {
  664. let { $from, $to } = ranges[i];
  665. if (has) {
  666. tr.removeMark($from.pos, $to.pos, markType);
  667. }
  668. else {
  669. let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;
  670. let spaceStart = start && start.isText ? /^\s*/.exec(start.text)[0].length : 0;
  671. let spaceEnd = end && end.isText ? /\s*$/.exec(end.text)[0].length : 0;
  672. if (from + spaceStart < to) {
  673. from += spaceStart;
  674. to -= spaceEnd;
  675. }
  676. tr.addMark(from, to, markType.create(attrs));
  677. }
  678. }
  679. dispatch(tr.scrollIntoView());
  680. }
  681. }
  682. return true;
  683. };
  684. }
  685. function wrapDispatchForJoin(dispatch, isJoinable) {
  686. return (tr) => {
  687. if (!tr.isGeneric)
  688. return dispatch(tr);
  689. let ranges = [];
  690. for (let i = 0; i < tr.mapping.maps.length; i++) {
  691. let map = tr.mapping.maps[i];
  692. for (let j = 0; j < ranges.length; j++)
  693. ranges[j] = map.map(ranges[j]);
  694. map.forEach((_s, _e, from, to) => ranges.push(from, to));
  695. }
  696. // Figure out which joinable points exist inside those ranges,
  697. // by checking all node boundaries in their parent nodes.
  698. let joinable = [];
  699. for (let i = 0; i < ranges.length; i += 2) {
  700. let from = ranges[i], to = ranges[i + 1];
  701. let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);
  702. for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {
  703. let after = parent.maybeChild(index);
  704. if (!after)
  705. break;
  706. if (index && joinable.indexOf(pos) == -1) {
  707. let before = parent.child(index - 1);
  708. if (before.type == after.type && isJoinable(before, after))
  709. joinable.push(pos);
  710. }
  711. pos += after.nodeSize;
  712. }
  713. }
  714. // Join the joinable points
  715. joinable.sort((a, b) => a - b);
  716. for (let i = joinable.length - 1; i >= 0; i--) {
  717. if (canJoin(tr.doc, joinable[i]))
  718. tr.join(joinable[i]);
  719. }
  720. dispatch(tr);
  721. };
  722. }
  723. /**
  724. Wrap a command so that, when it produces a transform that causes
  725. two joinable nodes to end up next to each other, those are joined.
  726. Nodes are considered joinable when they are of the same type and
  727. when the `isJoinable` predicate returns true for them or, if an
  728. array of strings was passed, if their node type name is in that
  729. array.
  730. */
  731. function autoJoin(command, isJoinable) {
  732. let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1
  733. : isJoinable;
  734. return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);
  735. }
  736. /**
  737. Combine a number of command functions into a single function (which
  738. calls them one by one until one returns true).
  739. */
  740. function chainCommands(...commands) {
  741. return function (state, dispatch, view) {
  742. for (let i = 0; i < commands.length; i++)
  743. if (commands[i](state, dispatch, view))
  744. return true;
  745. return false;
  746. };
  747. }
  748. let backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
  749. let del = chainCommands(deleteSelection, joinForward, selectNodeForward);
  750. /**
  751. A basic keymap containing bindings not specific to any schema.
  752. Binds the following keys (when multiple commands are listed, they
  753. are chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):
  754. * **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`
  755. * **Mod-Enter** to `exitCode`
  756. * **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`
  757. * **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`
  758. * **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`
  759. * **Mod-a** to `selectAll`
  760. */
  761. const pcBaseKeymap = {
  762. "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
  763. "Mod-Enter": exitCode,
  764. "Backspace": backspace,
  765. "Mod-Backspace": backspace,
  766. "Shift-Backspace": backspace,
  767. "Delete": del,
  768. "Mod-Delete": del,
  769. "Mod-a": selectAll
  770. };
  771. /**
  772. A copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,
  773. **Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and
  774. **Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like
  775. Ctrl-Delete.
  776. */
  777. const macBaseKeymap = {
  778. "Ctrl-h": pcBaseKeymap["Backspace"],
  779. "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
  780. "Ctrl-d": pcBaseKeymap["Delete"],
  781. "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
  782. "Alt-Delete": pcBaseKeymap["Mod-Delete"],
  783. "Alt-d": pcBaseKeymap["Mod-Delete"],
  784. "Ctrl-a": selectTextblockStart,
  785. "Ctrl-e": selectTextblockEnd
  786. };
  787. for (let key in pcBaseKeymap)
  788. macBaseKeymap[key] = pcBaseKeymap[key];
  789. const mac = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)
  790. // @ts-ignore
  791. : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;
  792. /**
  793. Depending on the detected platform, this will hold
  794. [`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or
  795. [`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).
  796. */
  797. const baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;
  798. export { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };