index.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. import { Slice, Fragment, Mark, Node } from 'prosemirror-model';
  2. import { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';
  3. const classesById = Object.create(null);
  4. /**
  5. Superclass for editor selections. Every selection type should
  6. extend this. Should not be instantiated directly.
  7. */
  8. class Selection {
  9. /**
  10. Initialize a selection with the head and anchor and ranges. If no
  11. ranges are given, constructs a single range across `$anchor` and
  12. `$head`.
  13. */
  14. constructor(
  15. /**
  16. The resolved anchor of the selection (the side that stays in
  17. place when the selection is modified).
  18. */
  19. $anchor,
  20. /**
  21. The resolved head of the selection (the side that moves when
  22. the selection is modified).
  23. */
  24. $head, ranges) {
  25. this.$anchor = $anchor;
  26. this.$head = $head;
  27. this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
  28. }
  29. /**
  30. The selection's anchor, as an unresolved position.
  31. */
  32. get anchor() { return this.$anchor.pos; }
  33. /**
  34. The selection's head.
  35. */
  36. get head() { return this.$head.pos; }
  37. /**
  38. The lower bound of the selection's main range.
  39. */
  40. get from() { return this.$from.pos; }
  41. /**
  42. The upper bound of the selection's main range.
  43. */
  44. get to() { return this.$to.pos; }
  45. /**
  46. The resolved lower bound of the selection's main range.
  47. */
  48. get $from() {
  49. return this.ranges[0].$from;
  50. }
  51. /**
  52. The resolved upper bound of the selection's main range.
  53. */
  54. get $to() {
  55. return this.ranges[0].$to;
  56. }
  57. /**
  58. Indicates whether the selection contains any content.
  59. */
  60. get empty() {
  61. let ranges = this.ranges;
  62. for (let i = 0; i < ranges.length; i++)
  63. if (ranges[i].$from.pos != ranges[i].$to.pos)
  64. return false;
  65. return true;
  66. }
  67. /**
  68. Get the content of this selection as a slice.
  69. */
  70. content() {
  71. return this.$from.doc.slice(this.from, this.to, true);
  72. }
  73. /**
  74. Replace the selection with a slice or, if no slice is given,
  75. delete the selection. Will append to the given transaction.
  76. */
  77. replace(tr, content = Slice.empty) {
  78. // Put the new selection at the position after the inserted
  79. // content. When that ended in an inline node, search backwards,
  80. // to get the position after that node. If not, search forward.
  81. let lastNode = content.content.lastChild, lastParent = null;
  82. for (let i = 0; i < content.openEnd; i++) {
  83. lastParent = lastNode;
  84. lastNode = lastNode.lastChild;
  85. }
  86. let mapFrom = tr.steps.length, ranges = this.ranges;
  87. for (let i = 0; i < ranges.length; i++) {
  88. let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);
  89. tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);
  90. if (i == 0)
  91. selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
  92. }
  93. }
  94. /**
  95. Replace the selection with the given node, appending the changes
  96. to the given transaction.
  97. */
  98. replaceWith(tr, node) {
  99. let mapFrom = tr.steps.length, ranges = this.ranges;
  100. for (let i = 0; i < ranges.length; i++) {
  101. let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);
  102. let from = mapping.map($from.pos), to = mapping.map($to.pos);
  103. if (i) {
  104. tr.deleteRange(from, to);
  105. }
  106. else {
  107. tr.replaceRangeWith(from, to, node);
  108. selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);
  109. }
  110. }
  111. }
  112. /**
  113. Find a valid cursor or leaf node selection starting at the given
  114. position and searching back if `dir` is negative, and forward if
  115. positive. When `textOnly` is true, only consider cursor
  116. selections. Will return null when no valid selection position is
  117. found.
  118. */
  119. static findFrom($pos, dir, textOnly = false) {
  120. let inner = $pos.parent.inlineContent ? new TextSelection($pos)
  121. : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
  122. if (inner)
  123. return inner;
  124. for (let depth = $pos.depth - 1; depth >= 0; depth--) {
  125. let found = dir < 0
  126. ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)
  127. : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
  128. if (found)
  129. return found;
  130. }
  131. return null;
  132. }
  133. /**
  134. Find a valid cursor or leaf node selection near the given
  135. position. Searches forward first by default, but if `bias` is
  136. negative, it will search backwards first.
  137. */
  138. static near($pos, bias = 1) {
  139. return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
  140. }
  141. /**
  142. Find the cursor or leaf node selection closest to the start of
  143. the given document. Will return an
  144. [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position
  145. exists.
  146. */
  147. static atStart(doc) {
  148. return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);
  149. }
  150. /**
  151. Find the cursor or leaf node selection closest to the end of the
  152. given document.
  153. */
  154. static atEnd(doc) {
  155. return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);
  156. }
  157. /**
  158. Deserialize the JSON representation of a selection. Must be
  159. implemented for custom classes (as a static class method).
  160. */
  161. static fromJSON(doc, json) {
  162. if (!json || !json.type)
  163. throw new RangeError("Invalid input for Selection.fromJSON");
  164. let cls = classesById[json.type];
  165. if (!cls)
  166. throw new RangeError(`No selection type ${json.type} defined`);
  167. return cls.fromJSON(doc, json);
  168. }
  169. /**
  170. To be able to deserialize selections from JSON, custom selection
  171. classes must register themselves with an ID string, so that they
  172. can be disambiguated. Try to pick something that's unlikely to
  173. clash with classes from other modules.
  174. */
  175. static jsonID(id, selectionClass) {
  176. if (id in classesById)
  177. throw new RangeError("Duplicate use of selection JSON ID " + id);
  178. classesById[id] = selectionClass;
  179. selectionClass.prototype.jsonID = id;
  180. return selectionClass;
  181. }
  182. /**
  183. Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,
  184. which is a value that can be mapped without having access to a
  185. current document, and later resolved to a real selection for a
  186. given document again. (This is used mostly by the history to
  187. track and restore old selections.) The default implementation of
  188. this method just converts the selection to a text selection and
  189. returns the bookmark for that.
  190. */
  191. getBookmark() {
  192. return TextSelection.between(this.$anchor, this.$head).getBookmark();
  193. }
  194. }
  195. Selection.prototype.visible = true;
  196. /**
  197. Represents a selected range in a document.
  198. */
  199. class SelectionRange {
  200. /**
  201. Create a range.
  202. */
  203. constructor(
  204. /**
  205. The lower bound of the range.
  206. */
  207. $from,
  208. /**
  209. The upper bound of the range.
  210. */
  211. $to) {
  212. this.$from = $from;
  213. this.$to = $to;
  214. }
  215. }
  216. let warnedAboutTextSelection = false;
  217. function checkTextSelection($pos) {
  218. if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
  219. warnedAboutTextSelection = true;
  220. console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
  221. }
  222. }
  223. /**
  224. A text selection represents a classical editor selection, with a
  225. head (the moving side) and anchor (immobile side), both of which
  226. point into textblock nodes. It can be empty (a regular cursor
  227. position).
  228. */
  229. class TextSelection extends Selection {
  230. /**
  231. Construct a text selection between the given points.
  232. */
  233. constructor($anchor, $head = $anchor) {
  234. checkTextSelection($anchor);
  235. checkTextSelection($head);
  236. super($anchor, $head);
  237. }
  238. /**
  239. Returns a resolved position if this is a cursor selection (an
  240. empty text selection), and null otherwise.
  241. */
  242. get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }
  243. map(doc, mapping) {
  244. let $head = doc.resolve(mapping.map(this.head));
  245. if (!$head.parent.inlineContent)
  246. return Selection.near($head);
  247. let $anchor = doc.resolve(mapping.map(this.anchor));
  248. return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
  249. }
  250. replace(tr, content = Slice.empty) {
  251. super.replace(tr, content);
  252. if (content == Slice.empty) {
  253. let marks = this.$from.marksAcross(this.$to);
  254. if (marks)
  255. tr.ensureMarks(marks);
  256. }
  257. }
  258. eq(other) {
  259. return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;
  260. }
  261. getBookmark() {
  262. return new TextBookmark(this.anchor, this.head);
  263. }
  264. toJSON() {
  265. return { type: "text", anchor: this.anchor, head: this.head };
  266. }
  267. /**
  268. @internal
  269. */
  270. static fromJSON(doc, json) {
  271. if (typeof json.anchor != "number" || typeof json.head != "number")
  272. throw new RangeError("Invalid input for TextSelection.fromJSON");
  273. return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));
  274. }
  275. /**
  276. Create a text selection from non-resolved positions.
  277. */
  278. static create(doc, anchor, head = anchor) {
  279. let $anchor = doc.resolve(anchor);
  280. return new this($anchor, head == anchor ? $anchor : doc.resolve(head));
  281. }
  282. /**
  283. Return a text selection that spans the given positions or, if
  284. they aren't text positions, find a text selection near them.
  285. `bias` determines whether the method searches forward (default)
  286. or backwards (negative number) first. Will fall back to calling
  287. [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document
  288. doesn't contain a valid text position.
  289. */
  290. static between($anchor, $head, bias) {
  291. let dPos = $anchor.pos - $head.pos;
  292. if (!bias || dPos)
  293. bias = dPos >= 0 ? 1 : -1;
  294. if (!$head.parent.inlineContent) {
  295. let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
  296. if (found)
  297. $head = found.$head;
  298. else
  299. return Selection.near($head, bias);
  300. }
  301. if (!$anchor.parent.inlineContent) {
  302. if (dPos == 0) {
  303. $anchor = $head;
  304. }
  305. else {
  306. $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
  307. if (($anchor.pos < $head.pos) != (dPos < 0))
  308. $anchor = $head;
  309. }
  310. }
  311. return new TextSelection($anchor, $head);
  312. }
  313. }
  314. Selection.jsonID("text", TextSelection);
  315. class TextBookmark {
  316. constructor(anchor, head) {
  317. this.anchor = anchor;
  318. this.head = head;
  319. }
  320. map(mapping) {
  321. return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
  322. }
  323. resolve(doc) {
  324. return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));
  325. }
  326. }
  327. /**
  328. A node selection is a selection that points at a single node. All
  329. nodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the
  330. target of a node selection. In such a selection, `from` and `to`
  331. point directly before and after the selected node, `anchor` equals
  332. `from`, and `head` equals `to`..
  333. */
  334. class NodeSelection extends Selection {
  335. /**
  336. Create a node selection. Does not verify the validity of its
  337. argument.
  338. */
  339. constructor($pos) {
  340. let node = $pos.nodeAfter;
  341. let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);
  342. super($pos, $end);
  343. this.node = node;
  344. }
  345. map(doc, mapping) {
  346. let { deleted, pos } = mapping.mapResult(this.anchor);
  347. let $pos = doc.resolve(pos);
  348. if (deleted)
  349. return Selection.near($pos);
  350. return new NodeSelection($pos);
  351. }
  352. content() {
  353. return new Slice(Fragment.from(this.node), 0, 0);
  354. }
  355. eq(other) {
  356. return other instanceof NodeSelection && other.anchor == this.anchor;
  357. }
  358. toJSON() {
  359. return { type: "node", anchor: this.anchor };
  360. }
  361. getBookmark() { return new NodeBookmark(this.anchor); }
  362. /**
  363. @internal
  364. */
  365. static fromJSON(doc, json) {
  366. if (typeof json.anchor != "number")
  367. throw new RangeError("Invalid input for NodeSelection.fromJSON");
  368. return new NodeSelection(doc.resolve(json.anchor));
  369. }
  370. /**
  371. Create a node selection from non-resolved positions.
  372. */
  373. static create(doc, from) {
  374. return new NodeSelection(doc.resolve(from));
  375. }
  376. /**
  377. Determines whether the given node may be selected as a node
  378. selection.
  379. */
  380. static isSelectable(node) {
  381. return !node.isText && node.type.spec.selectable !== false;
  382. }
  383. }
  384. NodeSelection.prototype.visible = false;
  385. Selection.jsonID("node", NodeSelection);
  386. class NodeBookmark {
  387. constructor(anchor) {
  388. this.anchor = anchor;
  389. }
  390. map(mapping) {
  391. let { deleted, pos } = mapping.mapResult(this.anchor);
  392. return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);
  393. }
  394. resolve(doc) {
  395. let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;
  396. if (node && NodeSelection.isSelectable(node))
  397. return new NodeSelection($pos);
  398. return Selection.near($pos);
  399. }
  400. }
  401. /**
  402. A selection type that represents selecting the whole document
  403. (which can not necessarily be expressed with a text selection, when
  404. there are for example leaf block nodes at the start or end of the
  405. document).
  406. */
  407. class AllSelection extends Selection {
  408. /**
  409. Create an all-selection over the given document.
  410. */
  411. constructor(doc) {
  412. super(doc.resolve(0), doc.resolve(doc.content.size));
  413. }
  414. replace(tr, content = Slice.empty) {
  415. if (content == Slice.empty) {
  416. tr.delete(0, tr.doc.content.size);
  417. let sel = Selection.atStart(tr.doc);
  418. if (!sel.eq(tr.selection))
  419. tr.setSelection(sel);
  420. }
  421. else {
  422. super.replace(tr, content);
  423. }
  424. }
  425. toJSON() { return { type: "all" }; }
  426. /**
  427. @internal
  428. */
  429. static fromJSON(doc) { return new AllSelection(doc); }
  430. map(doc) { return new AllSelection(doc); }
  431. eq(other) { return other instanceof AllSelection; }
  432. getBookmark() { return AllBookmark; }
  433. }
  434. Selection.jsonID("all", AllSelection);
  435. const AllBookmark = {
  436. map() { return this; },
  437. resolve(doc) { return new AllSelection(doc); }
  438. };
  439. // FIXME we'll need some awareness of text direction when scanning for selections
  440. // Try to find a selection inside the given node. `pos` points at the
  441. // position where the search starts. When `text` is true, only return
  442. // text selections.
  443. function findSelectionIn(doc, node, pos, index, dir, text = false) {
  444. if (node.inlineContent)
  445. return TextSelection.create(doc, pos);
  446. for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {
  447. let child = node.child(i);
  448. if (!child.isAtom) {
  449. let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);
  450. if (inner)
  451. return inner;
  452. }
  453. else if (!text && NodeSelection.isSelectable(child)) {
  454. return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));
  455. }
  456. pos += child.nodeSize * dir;
  457. }
  458. return null;
  459. }
  460. function selectionToInsertionEnd(tr, startLen, bias) {
  461. let last = tr.steps.length - 1;
  462. if (last < startLen)
  463. return;
  464. let step = tr.steps[last];
  465. if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
  466. return;
  467. let map = tr.mapping.maps[last], end;
  468. map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)
  469. end = newTo; });
  470. tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
  471. }
  472. const UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;
  473. /**
  474. An editor state transaction, which can be applied to a state to
  475. create an updated state. Use
  476. [`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.
  477. Transactions track changes to the document (they are a subclass of
  478. [`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,
  479. like selection updates and adjustments of the set of [stored
  480. marks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store
  481. metadata properties in a transaction, which are extra pieces of
  482. information that client code or plugins can use to describe what a
  483. transaction represents, so that they can update their [own
  484. state](https://prosemirror.net/docs/ref/#state.StateField) accordingly.
  485. The [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata
  486. properties: it will attach a property `"pointer"` with the value
  487. `true` to selection transactions directly caused by mouse or touch
  488. input, a `"composition"` property holding an ID identifying the
  489. composition that caused it to transactions caused by composed DOM
  490. input, and a `"uiEvent"` property of that may be `"paste"`,
  491. `"cut"`, or `"drop"`.
  492. */
  493. class Transaction extends Transform {
  494. /**
  495. @internal
  496. */
  497. constructor(state) {
  498. super(state.doc);
  499. // The step count for which the current selection is valid.
  500. this.curSelectionFor = 0;
  501. // Bitfield to track which aspects of the state were updated by
  502. // this transaction.
  503. this.updated = 0;
  504. // Object used to store metadata properties for the transaction.
  505. this.meta = Object.create(null);
  506. this.time = Date.now();
  507. this.curSelection = state.selection;
  508. this.storedMarks = state.storedMarks;
  509. }
  510. /**
  511. The transaction's current selection. This defaults to the editor
  512. selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the
  513. transaction, but can be overwritten with
  514. [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).
  515. */
  516. get selection() {
  517. if (this.curSelectionFor < this.steps.length) {
  518. this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
  519. this.curSelectionFor = this.steps.length;
  520. }
  521. return this.curSelection;
  522. }
  523. /**
  524. Update the transaction's current selection. Will determine the
  525. selection that the editor gets when the transaction is applied.
  526. */
  527. setSelection(selection) {
  528. if (selection.$from.doc != this.doc)
  529. throw new RangeError("Selection passed to setSelection must point at the current document");
  530. this.curSelection = selection;
  531. this.curSelectionFor = this.steps.length;
  532. this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
  533. this.storedMarks = null;
  534. return this;
  535. }
  536. /**
  537. Whether the selection was explicitly updated by this transaction.
  538. */
  539. get selectionSet() {
  540. return (this.updated & UPDATED_SEL) > 0;
  541. }
  542. /**
  543. Set the current stored marks.
  544. */
  545. setStoredMarks(marks) {
  546. this.storedMarks = marks;
  547. this.updated |= UPDATED_MARKS;
  548. return this;
  549. }
  550. /**
  551. Make sure the current stored marks or, if that is null, the marks
  552. at the selection, match the given set of marks. Does nothing if
  553. this is already the case.
  554. */
  555. ensureMarks(marks) {
  556. if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
  557. this.setStoredMarks(marks);
  558. return this;
  559. }
  560. /**
  561. Add a mark to the set of stored marks.
  562. */
  563. addStoredMark(mark) {
  564. return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
  565. }
  566. /**
  567. Remove a mark or mark type from the set of stored marks.
  568. */
  569. removeStoredMark(mark) {
  570. return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  571. }
  572. /**
  573. Whether the stored marks were explicitly set for this transaction.
  574. */
  575. get storedMarksSet() {
  576. return (this.updated & UPDATED_MARKS) > 0;
  577. }
  578. /**
  579. @internal
  580. */
  581. addStep(step, doc) {
  582. super.addStep(step, doc);
  583. this.updated = this.updated & ~UPDATED_MARKS;
  584. this.storedMarks = null;
  585. }
  586. /**
  587. Update the timestamp for the transaction.
  588. */
  589. setTime(time) {
  590. this.time = time;
  591. return this;
  592. }
  593. /**
  594. Replace the current selection with the given slice.
  595. */
  596. replaceSelection(slice) {
  597. this.selection.replace(this, slice);
  598. return this;
  599. }
  600. /**
  601. Replace the selection with the given node. When `inheritMarks` is
  602. true and the content is inline, it inherits the marks from the
  603. place where it is inserted.
  604. */
  605. replaceSelectionWith(node, inheritMarks = true) {
  606. let selection = this.selection;
  607. if (inheritMarks)
  608. node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));
  609. selection.replaceWith(this, node);
  610. return this;
  611. }
  612. /**
  613. Delete the selection.
  614. */
  615. deleteSelection() {
  616. this.selection.replace(this);
  617. return this;
  618. }
  619. /**
  620. Replace the given range, or the selection if no range is given,
  621. with a text node containing the given string.
  622. */
  623. insertText(text, from, to) {
  624. let schema = this.doc.type.schema;
  625. if (from == null) {
  626. if (!text)
  627. return this.deleteSelection();
  628. return this.replaceSelectionWith(schema.text(text), true);
  629. }
  630. else {
  631. if (to == null)
  632. to = from;
  633. to = to == null ? from : to;
  634. if (!text)
  635. return this.deleteRange(from, to);
  636. let marks = this.storedMarks;
  637. if (!marks) {
  638. let $from = this.doc.resolve(from);
  639. marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));
  640. }
  641. this.replaceRangeWith(from, to, schema.text(text, marks));
  642. if (!this.selection.empty)
  643. this.setSelection(Selection.near(this.selection.$to));
  644. return this;
  645. }
  646. }
  647. /**
  648. Store a metadata property in this transaction, keyed either by
  649. name or by plugin.
  650. */
  651. setMeta(key, value) {
  652. this.meta[typeof key == "string" ? key : key.key] = value;
  653. return this;
  654. }
  655. /**
  656. Retrieve a metadata property for a given name or plugin.
  657. */
  658. getMeta(key) {
  659. return this.meta[typeof key == "string" ? key : key.key];
  660. }
  661. /**
  662. Returns true if this transaction doesn't contain any metadata,
  663. and can thus safely be extended.
  664. */
  665. get isGeneric() {
  666. for (let _ in this.meta)
  667. return false;
  668. return true;
  669. }
  670. /**
  671. Indicate that the editor should scroll the selection into view
  672. when updated to the state produced by this transaction.
  673. */
  674. scrollIntoView() {
  675. this.updated |= UPDATED_SCROLL;
  676. return this;
  677. }
  678. /**
  679. True when this transaction has had `scrollIntoView` called on it.
  680. */
  681. get scrolledIntoView() {
  682. return (this.updated & UPDATED_SCROLL) > 0;
  683. }
  684. }
  685. function bind(f, self) {
  686. return !self || !f ? f : f.bind(self);
  687. }
  688. class FieldDesc {
  689. constructor(name, desc, self) {
  690. this.name = name;
  691. this.init = bind(desc.init, self);
  692. this.apply = bind(desc.apply, self);
  693. }
  694. }
  695. const baseFields = [
  696. new FieldDesc("doc", {
  697. init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },
  698. apply(tr) { return tr.doc; }
  699. }),
  700. new FieldDesc("selection", {
  701. init(config, instance) { return config.selection || Selection.atStart(instance.doc); },
  702. apply(tr) { return tr.selection; }
  703. }),
  704. new FieldDesc("storedMarks", {
  705. init(config) { return config.storedMarks || null; },
  706. apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }
  707. }),
  708. new FieldDesc("scrollToSelection", {
  709. init() { return 0; },
  710. apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }
  711. })
  712. ];
  713. // Object wrapping the part of a state object that stays the same
  714. // across transactions. Stored in the state's `config` property.
  715. class Configuration {
  716. constructor(schema, plugins) {
  717. this.schema = schema;
  718. this.plugins = [];
  719. this.pluginsByKey = Object.create(null);
  720. this.fields = baseFields.slice();
  721. if (plugins)
  722. plugins.forEach(plugin => {
  723. if (this.pluginsByKey[plugin.key])
  724. throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
  725. this.plugins.push(plugin);
  726. this.pluginsByKey[plugin.key] = plugin;
  727. if (plugin.spec.state)
  728. this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
  729. });
  730. }
  731. }
  732. /**
  733. The state of a ProseMirror editor is represented by an object of
  734. this type. A state is a persistent data structure—it isn't
  735. updated, but rather a new state value is computed from an old one
  736. using the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.
  737. A state holds a number of built-in fields, and plugins can
  738. [define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.
  739. */
  740. class EditorState {
  741. /**
  742. @internal
  743. */
  744. constructor(
  745. /**
  746. @internal
  747. */
  748. config) {
  749. this.config = config;
  750. }
  751. /**
  752. The schema of the state's document.
  753. */
  754. get schema() {
  755. return this.config.schema;
  756. }
  757. /**
  758. The plugins that are active in this state.
  759. */
  760. get plugins() {
  761. return this.config.plugins;
  762. }
  763. /**
  764. Apply the given transaction to produce a new state.
  765. */
  766. apply(tr) {
  767. return this.applyTransaction(tr).state;
  768. }
  769. /**
  770. @internal
  771. */
  772. filterTransaction(tr, ignore = -1) {
  773. for (let i = 0; i < this.config.plugins.length; i++)
  774. if (i != ignore) {
  775. let plugin = this.config.plugins[i];
  776. if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))
  777. return false;
  778. }
  779. return true;
  780. }
  781. /**
  782. Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that
  783. returns the precise transactions that were applied (which might
  784. be influenced by the [transaction
  785. hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of
  786. plugins) along with the new state.
  787. */
  788. applyTransaction(rootTr) {
  789. if (!this.filterTransaction(rootTr))
  790. return { state: this, transactions: [] };
  791. let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;
  792. // This loop repeatedly gives plugins a chance to respond to
  793. // transactions as new transactions are added, making sure to only
  794. // pass the transactions the plugin did not see before.
  795. for (;;) {
  796. let haveNew = false;
  797. for (let i = 0; i < this.config.plugins.length; i++) {
  798. let plugin = this.config.plugins[i];
  799. if (plugin.spec.appendTransaction) {
  800. let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;
  801. let tr = n < trs.length &&
  802. plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);
  803. if (tr && newState.filterTransaction(tr, i)) {
  804. tr.setMeta("appendedTransaction", rootTr);
  805. if (!seen) {
  806. seen = [];
  807. for (let j = 0; j < this.config.plugins.length; j++)
  808. seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });
  809. }
  810. trs.push(tr);
  811. newState = newState.applyInner(tr);
  812. haveNew = true;
  813. }
  814. if (seen)
  815. seen[i] = { state: newState, n: trs.length };
  816. }
  817. }
  818. if (!haveNew)
  819. return { state: newState, transactions: trs };
  820. }
  821. }
  822. /**
  823. @internal
  824. */
  825. applyInner(tr) {
  826. if (!tr.before.eq(this.doc))
  827. throw new RangeError("Applying a mismatched transaction");
  828. let newInstance = new EditorState(this.config), fields = this.config.fields;
  829. for (let i = 0; i < fields.length; i++) {
  830. let field = fields[i];
  831. newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);
  832. }
  833. return newInstance;
  834. }
  835. /**
  836. Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.
  837. */
  838. get tr() { return new Transaction(this); }
  839. /**
  840. Create a new state.
  841. */
  842. static create(config) {
  843. let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);
  844. let instance = new EditorState($config);
  845. for (let i = 0; i < $config.fields.length; i++)
  846. instance[$config.fields[i].name] = $config.fields[i].init(config, instance);
  847. return instance;
  848. }
  849. /**
  850. Create a new state based on this one, but with an adjusted set
  851. of active plugins. State fields that exist in both sets of
  852. plugins are kept unchanged. Those that no longer exist are
  853. dropped, and those that are new are initialized using their
  854. [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new
  855. configuration object..
  856. */
  857. reconfigure(config) {
  858. let $config = new Configuration(this.schema, config.plugins);
  859. let fields = $config.fields, instance = new EditorState($config);
  860. for (let i = 0; i < fields.length; i++) {
  861. let name = fields[i].name;
  862. instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);
  863. }
  864. return instance;
  865. }
  866. /**
  867. Serialize this state to JSON. If you want to serialize the state
  868. of plugins, pass an object mapping property names to use in the
  869. resulting JSON object to plugin objects. The argument may also be
  870. a string or number, in which case it is ignored, to support the
  871. way `JSON.stringify` calls `toString` methods.
  872. */
  873. toJSON(pluginFields) {
  874. let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
  875. if (this.storedMarks)
  876. result.storedMarks = this.storedMarks.map(m => m.toJSON());
  877. if (pluginFields && typeof pluginFields == 'object')
  878. for (let prop in pluginFields) {
  879. if (prop == "doc" || prop == "selection")
  880. throw new RangeError("The JSON fields `doc` and `selection` are reserved");
  881. let plugin = pluginFields[prop], state = plugin.spec.state;
  882. if (state && state.toJSON)
  883. result[prop] = state.toJSON.call(plugin, this[plugin.key]);
  884. }
  885. return result;
  886. }
  887. /**
  888. Deserialize a JSON representation of a state. `config` should
  889. have at least a `schema` field, and should contain array of
  890. plugins to initialize the state with. `pluginFields` can be used
  891. to deserialize the state of plugins, by associating plugin
  892. instances with the property names they use in the JSON object.
  893. */
  894. static fromJSON(config, json, pluginFields) {
  895. if (!json)
  896. throw new RangeError("Invalid input for EditorState.fromJSON");
  897. if (!config.schema)
  898. throw new RangeError("Required config field 'schema' missing");
  899. let $config = new Configuration(config.schema, config.plugins);
  900. let instance = new EditorState($config);
  901. $config.fields.forEach(field => {
  902. if (field.name == "doc") {
  903. instance.doc = Node.fromJSON(config.schema, json.doc);
  904. }
  905. else if (field.name == "selection") {
  906. instance.selection = Selection.fromJSON(instance.doc, json.selection);
  907. }
  908. else if (field.name == "storedMarks") {
  909. if (json.storedMarks)
  910. instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);
  911. }
  912. else {
  913. if (pluginFields)
  914. for (let prop in pluginFields) {
  915. let plugin = pluginFields[prop], state = plugin.spec.state;
  916. if (plugin.key == field.name && state && state.fromJSON &&
  917. Object.prototype.hasOwnProperty.call(json, prop)) {
  918. instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);
  919. return;
  920. }
  921. }
  922. instance[field.name] = field.init(config, instance);
  923. }
  924. });
  925. return instance;
  926. }
  927. }
  928. function bindProps(obj, self, target) {
  929. for (let prop in obj) {
  930. let val = obj[prop];
  931. if (val instanceof Function)
  932. val = val.bind(self);
  933. else if (prop == "handleDOMEvents")
  934. val = bindProps(val, self, {});
  935. target[prop] = val;
  936. }
  937. return target;
  938. }
  939. /**
  940. Plugins bundle functionality that can be added to an editor.
  941. They are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and
  942. may influence that state and the view that contains it.
  943. */
  944. class Plugin {
  945. /**
  946. Create a plugin.
  947. */
  948. constructor(
  949. /**
  950. The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).
  951. */
  952. spec) {
  953. this.spec = spec;
  954. /**
  955. The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.
  956. */
  957. this.props = {};
  958. if (spec.props)
  959. bindProps(spec.props, this, this.props);
  960. this.key = spec.key ? spec.key.key : createKey("plugin");
  961. }
  962. /**
  963. Extract the plugin's state field from an editor state.
  964. */
  965. getState(state) { return state[this.key]; }
  966. }
  967. const keys = Object.create(null);
  968. function createKey(name) {
  969. if (name in keys)
  970. return name + "$" + ++keys[name];
  971. keys[name] = 0;
  972. return name + "$";
  973. }
  974. /**
  975. A key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way
  976. that makes it possible to find them, given an editor state.
  977. Assigning a key does mean only one plugin of that type can be
  978. active in a state.
  979. */
  980. class PluginKey {
  981. /**
  982. Create a plugin key.
  983. */
  984. constructor(name = "key") { this.key = createKey(name); }
  985. /**
  986. Get the active plugin with this key, if any, from an editor
  987. state.
  988. */
  989. get(state) { return state.config.pluginsByKey[this.key]; }
  990. /**
  991. Get the plugin's state from an editor state.
  992. */
  993. getState(state) { return state[this.key]; }
  994. }
  995. export { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };