index.js 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  1. import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';
  2. // Recovery values encode a range index and an offset. They are
  3. // represented as numbers, because tons of them will be created when
  4. // mapping, for example, a large number of decorations. The number's
  5. // lower 16 bits provide the index, the remaining bits the offset.
  6. //
  7. // Note: We intentionally don't use bit shift operators to en- and
  8. // decode these, since those clip to 32 bits, which we might in rare
  9. // cases want to overflow. A 64-bit float can represent 48-bit
  10. // integers precisely.
  11. const lower16 = 0xffff;
  12. const factor16 = Math.pow(2, 16);
  13. function makeRecover(index, offset) { return index + offset * factor16; }
  14. function recoverIndex(value) { return value & lower16; }
  15. function recoverOffset(value) { return (value - (value & lower16)) / factor16; }
  16. const DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;
  17. /**
  18. An object representing a mapped position with extra
  19. information.
  20. */
  21. class MapResult {
  22. /**
  23. @internal
  24. */
  25. constructor(
  26. /**
  27. The mapped version of the position.
  28. */
  29. pos,
  30. /**
  31. @internal
  32. */
  33. delInfo,
  34. /**
  35. @internal
  36. */
  37. recover) {
  38. this.pos = pos;
  39. this.delInfo = delInfo;
  40. this.recover = recover;
  41. }
  42. /**
  43. Tells you whether the position was deleted, that is, whether the
  44. step removed the token on the side queried (via the `assoc`)
  45. argument from the document.
  46. */
  47. get deleted() { return (this.delInfo & DEL_SIDE) > 0; }
  48. /**
  49. Tells you whether the token before the mapped position was deleted.
  50. */
  51. get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }
  52. /**
  53. True when the token after the mapped position was deleted.
  54. */
  55. get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }
  56. /**
  57. Tells whether any of the steps mapped through deletes across the
  58. position (including both the token before and after the
  59. position).
  60. */
  61. get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }
  62. }
  63. /**
  64. A map describing the deletions and insertions made by a step, which
  65. can be used to find the correspondence between positions in the
  66. pre-step version of a document and the same position in the
  67. post-step version.
  68. */
  69. class StepMap {
  70. /**
  71. Create a position map. The modifications to the document are
  72. represented as an array of numbers, in which each group of three
  73. represents a modified chunk as `[start, oldSize, newSize]`.
  74. */
  75. constructor(
  76. /**
  77. @internal
  78. */
  79. ranges,
  80. /**
  81. @internal
  82. */
  83. inverted = false) {
  84. this.ranges = ranges;
  85. this.inverted = inverted;
  86. if (!ranges.length && StepMap.empty)
  87. return StepMap.empty;
  88. }
  89. /**
  90. @internal
  91. */
  92. recover(value) {
  93. let diff = 0, index = recoverIndex(value);
  94. if (!this.inverted)
  95. for (let i = 0; i < index; i++)
  96. diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];
  97. return this.ranges[index * 3] + diff + recoverOffset(value);
  98. }
  99. mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }
  100. map(pos, assoc = 1) { return this._map(pos, assoc, true); }
  101. /**
  102. @internal
  103. */
  104. _map(pos, assoc, simple) {
  105. let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
  106. for (let i = 0; i < this.ranges.length; i += 3) {
  107. let start = this.ranges[i] - (this.inverted ? diff : 0);
  108. if (start > pos)
  109. break;
  110. let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;
  111. if (pos <= end) {
  112. let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;
  113. let result = start + diff + (side < 0 ? 0 : newSize);
  114. if (simple)
  115. return result;
  116. let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);
  117. let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
  118. if (assoc < 0 ? pos != start : pos != end)
  119. del |= DEL_SIDE;
  120. return new MapResult(result, del, recover);
  121. }
  122. diff += newSize - oldSize;
  123. }
  124. return simple ? pos + diff : new MapResult(pos + diff, 0, null);
  125. }
  126. /**
  127. @internal
  128. */
  129. touches(pos, recover) {
  130. let diff = 0, index = recoverIndex(recover);
  131. let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
  132. for (let i = 0; i < this.ranges.length; i += 3) {
  133. let start = this.ranges[i] - (this.inverted ? diff : 0);
  134. if (start > pos)
  135. break;
  136. let oldSize = this.ranges[i + oldIndex], end = start + oldSize;
  137. if (pos <= end && i == index * 3)
  138. return true;
  139. diff += this.ranges[i + newIndex] - oldSize;
  140. }
  141. return false;
  142. }
  143. /**
  144. Calls the given function on each of the changed ranges included in
  145. this map.
  146. */
  147. forEach(f) {
  148. let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
  149. for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {
  150. let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);
  151. let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];
  152. f(oldStart, oldStart + oldSize, newStart, newStart + newSize);
  153. diff += newSize - oldSize;
  154. }
  155. }
  156. /**
  157. Create an inverted version of this map. The result can be used to
  158. map positions in the post-step document to the pre-step document.
  159. */
  160. invert() {
  161. return new StepMap(this.ranges, !this.inverted);
  162. }
  163. /**
  164. @internal
  165. */
  166. toString() {
  167. return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
  168. }
  169. /**
  170. Create a map that moves all positions by offset `n` (which may be
  171. negative). This can be useful when applying steps meant for a
  172. sub-document to a larger document, or vice-versa.
  173. */
  174. static offset(n) {
  175. return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
  176. }
  177. }
  178. /**
  179. A StepMap that contains no changed ranges.
  180. */
  181. StepMap.empty = new StepMap([]);
  182. /**
  183. A mapping represents a pipeline of zero or more [step
  184. maps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly
  185. handling mapping positions through a series of steps in which some
  186. steps are inverted versions of earlier steps. (This comes up when
  187. ‘[rebasing](/docs/guide/#transform.rebasing)’ steps for
  188. collaboration or history management.)
  189. */
  190. class Mapping {
  191. /**
  192. Create a new mapping with the given position maps.
  193. */
  194. constructor(
  195. /**
  196. The step maps in this mapping.
  197. */
  198. maps = [],
  199. /**
  200. @internal
  201. */
  202. mirror,
  203. /**
  204. The starting position in the `maps` array, used when `map` or
  205. `mapResult` is called.
  206. */
  207. from = 0,
  208. /**
  209. The end position in the `maps` array.
  210. */
  211. to = maps.length) {
  212. this.maps = maps;
  213. this.mirror = mirror;
  214. this.from = from;
  215. this.to = to;
  216. }
  217. /**
  218. Create a mapping that maps only through a part of this one.
  219. */
  220. slice(from = 0, to = this.maps.length) {
  221. return new Mapping(this.maps, this.mirror, from, to);
  222. }
  223. /**
  224. @internal
  225. */
  226. copy() {
  227. return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);
  228. }
  229. /**
  230. Add a step map to the end of this mapping. If `mirrors` is
  231. given, it should be the index of the step map that is the mirror
  232. image of this one.
  233. */
  234. appendMap(map, mirrors) {
  235. this.to = this.maps.push(map);
  236. if (mirrors != null)
  237. this.setMirror(this.maps.length - 1, mirrors);
  238. }
  239. /**
  240. Add all the step maps in a given mapping to this one (preserving
  241. mirroring information).
  242. */
  243. appendMapping(mapping) {
  244. for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {
  245. let mirr = mapping.getMirror(i);
  246. this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);
  247. }
  248. }
  249. /**
  250. Finds the offset of the step map that mirrors the map at the
  251. given offset, in this mapping (as per the second argument to
  252. `appendMap`).
  253. */
  254. getMirror(n) {
  255. if (this.mirror)
  256. for (let i = 0; i < this.mirror.length; i++)
  257. if (this.mirror[i] == n)
  258. return this.mirror[i + (i % 2 ? -1 : 1)];
  259. }
  260. /**
  261. @internal
  262. */
  263. setMirror(n, m) {
  264. if (!this.mirror)
  265. this.mirror = [];
  266. this.mirror.push(n, m);
  267. }
  268. /**
  269. Append the inverse of the given mapping to this one.
  270. */
  271. appendMappingInverted(mapping) {
  272. for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {
  273. let mirr = mapping.getMirror(i);
  274. this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);
  275. }
  276. }
  277. /**
  278. Create an inverted version of this mapping.
  279. */
  280. invert() {
  281. let inverse = new Mapping;
  282. inverse.appendMappingInverted(this);
  283. return inverse;
  284. }
  285. /**
  286. Map a position through this mapping.
  287. */
  288. map(pos, assoc = 1) {
  289. if (this.mirror)
  290. return this._map(pos, assoc, true);
  291. for (let i = this.from; i < this.to; i++)
  292. pos = this.maps[i].map(pos, assoc);
  293. return pos;
  294. }
  295. /**
  296. Map a position through this mapping, returning a mapping
  297. result.
  298. */
  299. mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }
  300. /**
  301. @internal
  302. */
  303. _map(pos, assoc, simple) {
  304. let delInfo = 0;
  305. for (let i = this.from; i < this.to; i++) {
  306. let map = this.maps[i], result = map.mapResult(pos, assoc);
  307. if (result.recover != null) {
  308. let corr = this.getMirror(i);
  309. if (corr != null && corr > i && corr < this.to) {
  310. i = corr;
  311. pos = this.maps[corr].recover(result.recover);
  312. continue;
  313. }
  314. }
  315. delInfo |= result.delInfo;
  316. pos = result.pos;
  317. }
  318. return simple ? pos : new MapResult(pos, delInfo, null);
  319. }
  320. }
  321. const stepsByID = Object.create(null);
  322. /**
  323. A step object represents an atomic change. It generally applies
  324. only to the document it was created for, since the positions
  325. stored in it will only make sense for that document.
  326. New steps are defined by creating classes that extend `Step`,
  327. overriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`
  328. methods, and registering your class with a unique
  329. JSON-serialization identifier using
  330. [`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).
  331. */
  332. class Step {
  333. /**
  334. Get the step map that represents the changes made by this step,
  335. and which can be used to transform between positions in the old
  336. and the new document.
  337. */
  338. getMap() { return StepMap.empty; }
  339. /**
  340. Try to merge this step with another one, to be applied directly
  341. after it. Returns the merged step when possible, null if the
  342. steps can't be merged.
  343. */
  344. merge(other) { return null; }
  345. /**
  346. Deserialize a step from its JSON representation. Will call
  347. through to the step class' own implementation of this method.
  348. */
  349. static fromJSON(schema, json) {
  350. if (!json || !json.stepType)
  351. throw new RangeError("Invalid input for Step.fromJSON");
  352. let type = stepsByID[json.stepType];
  353. if (!type)
  354. throw new RangeError(`No step type ${json.stepType} defined`);
  355. return type.fromJSON(schema, json);
  356. }
  357. /**
  358. To be able to serialize steps to JSON, each step needs a string
  359. ID to attach to its JSON representation. Use this method to
  360. register an ID for your step classes. Try to pick something
  361. that's unlikely to clash with steps from other modules.
  362. */
  363. static jsonID(id, stepClass) {
  364. if (id in stepsByID)
  365. throw new RangeError("Duplicate use of step JSON ID " + id);
  366. stepsByID[id] = stepClass;
  367. stepClass.prototype.jsonID = id;
  368. return stepClass;
  369. }
  370. }
  371. /**
  372. The result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a
  373. new document or a failure value.
  374. */
  375. class StepResult {
  376. /**
  377. @internal
  378. */
  379. constructor(
  380. /**
  381. The transformed document, if successful.
  382. */
  383. doc,
  384. /**
  385. The failure message, if unsuccessful.
  386. */
  387. failed) {
  388. this.doc = doc;
  389. this.failed = failed;
  390. }
  391. /**
  392. Create a successful step result.
  393. */
  394. static ok(doc) { return new StepResult(doc, null); }
  395. /**
  396. Create a failed step result.
  397. */
  398. static fail(message) { return new StepResult(null, message); }
  399. /**
  400. Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given
  401. arguments. Create a successful result if it succeeds, and a
  402. failed one if it throws a `ReplaceError`.
  403. */
  404. static fromReplace(doc, from, to, slice) {
  405. try {
  406. return StepResult.ok(doc.replace(from, to, slice));
  407. }
  408. catch (e) {
  409. if (e instanceof ReplaceError)
  410. return StepResult.fail(e.message);
  411. throw e;
  412. }
  413. }
  414. }
  415. function mapFragment(fragment, f, parent) {
  416. let mapped = [];
  417. for (let i = 0; i < fragment.childCount; i++) {
  418. let child = fragment.child(i);
  419. if (child.content.size)
  420. child = child.copy(mapFragment(child.content, f, child));
  421. if (child.isInline)
  422. child = f(child, parent, i);
  423. mapped.push(child);
  424. }
  425. return Fragment.fromArray(mapped);
  426. }
  427. /**
  428. Add a mark to all inline content between two positions.
  429. */
  430. class AddMarkStep extends Step {
  431. /**
  432. Create a mark step.
  433. */
  434. constructor(
  435. /**
  436. The start of the marked range.
  437. */
  438. from,
  439. /**
  440. The end of the marked range.
  441. */
  442. to,
  443. /**
  444. The mark to add.
  445. */
  446. mark) {
  447. super();
  448. this.from = from;
  449. this.to = to;
  450. this.mark = mark;
  451. }
  452. apply(doc) {
  453. let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);
  454. let parent = $from.node($from.sharedDepth(this.to));
  455. let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {
  456. if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))
  457. return node;
  458. return node.mark(this.mark.addToSet(node.marks));
  459. }, parent), oldSlice.openStart, oldSlice.openEnd);
  460. return StepResult.fromReplace(doc, this.from, this.to, slice);
  461. }
  462. invert() {
  463. return new RemoveMarkStep(this.from, this.to, this.mark);
  464. }
  465. map(mapping) {
  466. let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
  467. if (from.deleted && to.deleted || from.pos >= to.pos)
  468. return null;
  469. return new AddMarkStep(from.pos, to.pos, this.mark);
  470. }
  471. merge(other) {
  472. if (other instanceof AddMarkStep &&
  473. other.mark.eq(this.mark) &&
  474. this.from <= other.to && this.to >= other.from)
  475. return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
  476. return null;
  477. }
  478. toJSON() {
  479. return { stepType: "addMark", mark: this.mark.toJSON(),
  480. from: this.from, to: this.to };
  481. }
  482. /**
  483. @internal
  484. */
  485. static fromJSON(schema, json) {
  486. if (typeof json.from != "number" || typeof json.to != "number")
  487. throw new RangeError("Invalid input for AddMarkStep.fromJSON");
  488. return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  489. }
  490. }
  491. Step.jsonID("addMark", AddMarkStep);
  492. /**
  493. Remove a mark from all inline content between two positions.
  494. */
  495. class RemoveMarkStep extends Step {
  496. /**
  497. Create a mark-removing step.
  498. */
  499. constructor(
  500. /**
  501. The start of the unmarked range.
  502. */
  503. from,
  504. /**
  505. The end of the unmarked range.
  506. */
  507. to,
  508. /**
  509. The mark to remove.
  510. */
  511. mark) {
  512. super();
  513. this.from = from;
  514. this.to = to;
  515. this.mark = mark;
  516. }
  517. apply(doc) {
  518. let oldSlice = doc.slice(this.from, this.to);
  519. let slice = new Slice(mapFragment(oldSlice.content, node => {
  520. return node.mark(this.mark.removeFromSet(node.marks));
  521. }, doc), oldSlice.openStart, oldSlice.openEnd);
  522. return StepResult.fromReplace(doc, this.from, this.to, slice);
  523. }
  524. invert() {
  525. return new AddMarkStep(this.from, this.to, this.mark);
  526. }
  527. map(mapping) {
  528. let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
  529. if (from.deleted && to.deleted || from.pos >= to.pos)
  530. return null;
  531. return new RemoveMarkStep(from.pos, to.pos, this.mark);
  532. }
  533. merge(other) {
  534. if (other instanceof RemoveMarkStep &&
  535. other.mark.eq(this.mark) &&
  536. this.from <= other.to && this.to >= other.from)
  537. return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
  538. return null;
  539. }
  540. toJSON() {
  541. return { stepType: "removeMark", mark: this.mark.toJSON(),
  542. from: this.from, to: this.to };
  543. }
  544. /**
  545. @internal
  546. */
  547. static fromJSON(schema, json) {
  548. if (typeof json.from != "number" || typeof json.to != "number")
  549. throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
  550. return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  551. }
  552. }
  553. Step.jsonID("removeMark", RemoveMarkStep);
  554. /**
  555. Add a mark to a specific node.
  556. */
  557. class AddNodeMarkStep extends Step {
  558. /**
  559. Create a node mark step.
  560. */
  561. constructor(
  562. /**
  563. The position of the target node.
  564. */
  565. pos,
  566. /**
  567. The mark to add.
  568. */
  569. mark) {
  570. super();
  571. this.pos = pos;
  572. this.mark = mark;
  573. }
  574. apply(doc) {
  575. let node = doc.nodeAt(this.pos);
  576. if (!node)
  577. return StepResult.fail("No node at mark step's position");
  578. let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));
  579. return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  580. }
  581. invert(doc) {
  582. let node = doc.nodeAt(this.pos);
  583. if (node) {
  584. let newSet = this.mark.addToSet(node.marks);
  585. if (newSet.length == node.marks.length) {
  586. for (let i = 0; i < node.marks.length; i++)
  587. if (!node.marks[i].isInSet(newSet))
  588. return new AddNodeMarkStep(this.pos, node.marks[i]);
  589. return new AddNodeMarkStep(this.pos, this.mark);
  590. }
  591. }
  592. return new RemoveNodeMarkStep(this.pos, this.mark);
  593. }
  594. map(mapping) {
  595. let pos = mapping.mapResult(this.pos, 1);
  596. return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);
  597. }
  598. toJSON() {
  599. return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  600. }
  601. /**
  602. @internal
  603. */
  604. static fromJSON(schema, json) {
  605. if (typeof json.pos != "number")
  606. throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
  607. return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  608. }
  609. }
  610. Step.jsonID("addNodeMark", AddNodeMarkStep);
  611. /**
  612. Remove a mark from a specific node.
  613. */
  614. class RemoveNodeMarkStep extends Step {
  615. /**
  616. Create a mark-removing step.
  617. */
  618. constructor(
  619. /**
  620. The position of the target node.
  621. */
  622. pos,
  623. /**
  624. The mark to remove.
  625. */
  626. mark) {
  627. super();
  628. this.pos = pos;
  629. this.mark = mark;
  630. }
  631. apply(doc) {
  632. let node = doc.nodeAt(this.pos);
  633. if (!node)
  634. return StepResult.fail("No node at mark step's position");
  635. let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));
  636. return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  637. }
  638. invert(doc) {
  639. let node = doc.nodeAt(this.pos);
  640. if (!node || !this.mark.isInSet(node.marks))
  641. return this;
  642. return new AddNodeMarkStep(this.pos, this.mark);
  643. }
  644. map(mapping) {
  645. let pos = mapping.mapResult(this.pos, 1);
  646. return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);
  647. }
  648. toJSON() {
  649. return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  650. }
  651. /**
  652. @internal
  653. */
  654. static fromJSON(schema, json) {
  655. if (typeof json.pos != "number")
  656. throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
  657. return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  658. }
  659. }
  660. Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
  661. /**
  662. Replace a part of the document with a slice of new content.
  663. */
  664. class ReplaceStep extends Step {
  665. /**
  666. The given `slice` should fit the 'gap' between `from` and
  667. `to`—the depths must line up, and the surrounding nodes must be
  668. able to be joined with the open sides of the slice. When
  669. `structure` is true, the step will fail if the content between
  670. from and to is not just a sequence of closing and then opening
  671. tokens (this is to guard against rebased replace steps
  672. overwriting something they weren't supposed to).
  673. */
  674. constructor(
  675. /**
  676. The start position of the replaced range.
  677. */
  678. from,
  679. /**
  680. The end position of the replaced range.
  681. */
  682. to,
  683. /**
  684. The slice to insert.
  685. */
  686. slice,
  687. /**
  688. @internal
  689. */
  690. structure = false) {
  691. super();
  692. this.from = from;
  693. this.to = to;
  694. this.slice = slice;
  695. this.structure = structure;
  696. }
  697. apply(doc) {
  698. if (this.structure && contentBetween(doc, this.from, this.to))
  699. return StepResult.fail("Structure replace would overwrite content");
  700. return StepResult.fromReplace(doc, this.from, this.to, this.slice);
  701. }
  702. getMap() {
  703. return new StepMap([this.from, this.to - this.from, this.slice.size]);
  704. }
  705. invert(doc) {
  706. return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));
  707. }
  708. map(mapping) {
  709. let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
  710. if (from.deletedAcross && to.deletedAcross)
  711. return null;
  712. return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);
  713. }
  714. merge(other) {
  715. if (!(other instanceof ReplaceStep) || other.structure || this.structure)
  716. return null;
  717. if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
  718. let slice = this.slice.size + other.slice.size == 0 ? Slice.empty
  719. : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
  720. return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);
  721. }
  722. else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
  723. let slice = this.slice.size + other.slice.size == 0 ? Slice.empty
  724. : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
  725. return new ReplaceStep(other.from, this.to, slice, this.structure);
  726. }
  727. else {
  728. return null;
  729. }
  730. }
  731. toJSON() {
  732. let json = { stepType: "replace", from: this.from, to: this.to };
  733. if (this.slice.size)
  734. json.slice = this.slice.toJSON();
  735. if (this.structure)
  736. json.structure = true;
  737. return json;
  738. }
  739. /**
  740. @internal
  741. */
  742. static fromJSON(schema, json) {
  743. if (typeof json.from != "number" || typeof json.to != "number")
  744. throw new RangeError("Invalid input for ReplaceStep.fromJSON");
  745. return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);
  746. }
  747. }
  748. Step.jsonID("replace", ReplaceStep);
  749. /**
  750. Replace a part of the document with a slice of content, but
  751. preserve a range of the replaced content by moving it into the
  752. slice.
  753. */
  754. class ReplaceAroundStep extends Step {
  755. /**
  756. Create a replace-around step with the given range and gap.
  757. `insert` should be the point in the slice into which the content
  758. of the gap should be moved. `structure` has the same meaning as
  759. it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.
  760. */
  761. constructor(
  762. /**
  763. The start position of the replaced range.
  764. */
  765. from,
  766. /**
  767. The end position of the replaced range.
  768. */
  769. to,
  770. /**
  771. The start of preserved range.
  772. */
  773. gapFrom,
  774. /**
  775. The end of preserved range.
  776. */
  777. gapTo,
  778. /**
  779. The slice to insert.
  780. */
  781. slice,
  782. /**
  783. The position in the slice where the preserved range should be
  784. inserted.
  785. */
  786. insert,
  787. /**
  788. @internal
  789. */
  790. structure = false) {
  791. super();
  792. this.from = from;
  793. this.to = to;
  794. this.gapFrom = gapFrom;
  795. this.gapTo = gapTo;
  796. this.slice = slice;
  797. this.insert = insert;
  798. this.structure = structure;
  799. }
  800. apply(doc) {
  801. if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||
  802. contentBetween(doc, this.gapTo, this.to)))
  803. return StepResult.fail("Structure gap-replace would overwrite content");
  804. let gap = doc.slice(this.gapFrom, this.gapTo);
  805. if (gap.openStart || gap.openEnd)
  806. return StepResult.fail("Gap is not a flat range");
  807. let inserted = this.slice.insertAt(this.insert, gap.content);
  808. if (!inserted)
  809. return StepResult.fail("Content does not fit in gap");
  810. return StepResult.fromReplace(doc, this.from, this.to, inserted);
  811. }
  812. getMap() {
  813. return new StepMap([this.from, this.gapFrom - this.from, this.insert,
  814. this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);
  815. }
  816. invert(doc) {
  817. let gap = this.gapTo - this.gapFrom;
  818. return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  819. }
  820. map(mapping) {
  821. let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
  822. let gapFrom = mapping.map(this.gapFrom, -1), gapTo = mapping.map(this.gapTo, 1);
  823. if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)
  824. return null;
  825. return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
  826. }
  827. toJSON() {
  828. let json = { stepType: "replaceAround", from: this.from, to: this.to,
  829. gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };
  830. if (this.slice.size)
  831. json.slice = this.slice.toJSON();
  832. if (this.structure)
  833. json.structure = true;
  834. return json;
  835. }
  836. /**
  837. @internal
  838. */
  839. static fromJSON(schema, json) {
  840. if (typeof json.from != "number" || typeof json.to != "number" ||
  841. typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
  842. throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
  843. return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
  844. }
  845. }
  846. Step.jsonID("replaceAround", ReplaceAroundStep);
  847. function contentBetween(doc, from, to) {
  848. let $from = doc.resolve(from), dist = to - from, depth = $from.depth;
  849. while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
  850. depth--;
  851. dist--;
  852. }
  853. if (dist > 0) {
  854. let next = $from.node(depth).maybeChild($from.indexAfter(depth));
  855. while (dist > 0) {
  856. if (!next || next.isLeaf)
  857. return true;
  858. next = next.firstChild;
  859. dist--;
  860. }
  861. }
  862. return false;
  863. }
  864. function addMark(tr, from, to, mark) {
  865. let removed = [], added = [];
  866. let removing, adding;
  867. tr.doc.nodesBetween(from, to, (node, pos, parent) => {
  868. if (!node.isInline)
  869. return;
  870. let marks = node.marks;
  871. if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {
  872. let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);
  873. let newSet = mark.addToSet(marks);
  874. for (let i = 0; i < marks.length; i++) {
  875. if (!marks[i].isInSet(newSet)) {
  876. if (removing && removing.to == start && removing.mark.eq(marks[i]))
  877. removing.to = end;
  878. else
  879. removed.push(removing = new RemoveMarkStep(start, end, marks[i]));
  880. }
  881. }
  882. if (adding && adding.to == start)
  883. adding.to = end;
  884. else
  885. added.push(adding = new AddMarkStep(start, end, mark));
  886. }
  887. });
  888. removed.forEach(s => tr.step(s));
  889. added.forEach(s => tr.step(s));
  890. }
  891. function removeMark(tr, from, to, mark) {
  892. let matched = [], step = 0;
  893. tr.doc.nodesBetween(from, to, (node, pos) => {
  894. if (!node.isInline)
  895. return;
  896. step++;
  897. let toRemove = null;
  898. if (mark instanceof MarkType) {
  899. let set = node.marks, found;
  900. while (found = mark.isInSet(set)) {
  901. (toRemove || (toRemove = [])).push(found);
  902. set = found.removeFromSet(set);
  903. }
  904. }
  905. else if (mark) {
  906. if (mark.isInSet(node.marks))
  907. toRemove = [mark];
  908. }
  909. else {
  910. toRemove = node.marks;
  911. }
  912. if (toRemove && toRemove.length) {
  913. let end = Math.min(pos + node.nodeSize, to);
  914. for (let i = 0; i < toRemove.length; i++) {
  915. let style = toRemove[i], found;
  916. for (let j = 0; j < matched.length; j++) {
  917. let m = matched[j];
  918. if (m.step == step - 1 && style.eq(matched[j].style))
  919. found = m;
  920. }
  921. if (found) {
  922. found.to = end;
  923. found.step = step;
  924. }
  925. else {
  926. matched.push({ style, from: Math.max(pos, from), to: end, step });
  927. }
  928. }
  929. }
  930. });
  931. matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));
  932. }
  933. function clearIncompatible(tr, pos, parentType, match = parentType.contentMatch) {
  934. let node = tr.doc.nodeAt(pos);
  935. let replSteps = [], cur = pos + 1;
  936. for (let i = 0; i < node.childCount; i++) {
  937. let child = node.child(i), end = cur + child.nodeSize;
  938. let allowed = match.matchType(child.type);
  939. if (!allowed) {
  940. replSteps.push(new ReplaceStep(cur, end, Slice.empty));
  941. }
  942. else {
  943. match = allowed;
  944. for (let j = 0; j < child.marks.length; j++)
  945. if (!parentType.allowsMarkType(child.marks[j].type))
  946. tr.step(new RemoveMarkStep(cur, end, child.marks[j]));
  947. if (child.isText && !parentType.spec.code) {
  948. let m, newline = /\r?\n|\r/g, slice;
  949. while (m = newline.exec(child.text)) {
  950. if (!slice)
  951. slice = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0);
  952. replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));
  953. }
  954. }
  955. }
  956. cur = end;
  957. }
  958. if (!match.validEnd) {
  959. let fill = match.fillBefore(Fragment.empty, true);
  960. tr.replace(cur, cur, new Slice(fill, 0, 0));
  961. }
  962. for (let i = replSteps.length - 1; i >= 0; i--)
  963. tr.step(replSteps[i]);
  964. }
  965. function canCut(node, start, end) {
  966. return (start == 0 || node.canReplace(start, node.childCount)) &&
  967. (end == node.childCount || node.canReplace(0, end));
  968. }
  969. /**
  970. Try to find a target depth to which the content in the given range
  971. can be lifted. Will not go across
  972. [isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.
  973. */
  974. function liftTarget(range) {
  975. let parent = range.parent;
  976. let content = parent.content.cutByIndex(range.startIndex, range.endIndex);
  977. for (let depth = range.depth;; --depth) {
  978. let node = range.$from.node(depth);
  979. let index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);
  980. if (depth < range.depth && node.canReplace(index, endIndex, content))
  981. return depth;
  982. if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))
  983. break;
  984. }
  985. return null;
  986. }
  987. function lift(tr, range, target) {
  988. let { $from, $to, depth } = range;
  989. let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
  990. let start = gapStart, end = gapEnd;
  991. let before = Fragment.empty, openStart = 0;
  992. for (let d = depth, splitting = false; d > target; d--)
  993. if (splitting || $from.index(d) > 0) {
  994. splitting = true;
  995. before = Fragment.from($from.node(d).copy(before));
  996. openStart++;
  997. }
  998. else {
  999. start--;
  1000. }
  1001. let after = Fragment.empty, openEnd = 0;
  1002. for (let d = depth, splitting = false; d > target; d--)
  1003. if (splitting || $to.after(d + 1) < $to.end(d)) {
  1004. splitting = true;
  1005. after = Fragment.from($to.node(d).copy(after));
  1006. openEnd++;
  1007. }
  1008. else {
  1009. end++;
  1010. }
  1011. tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
  1012. }
  1013. /**
  1014. Try to find a valid way to wrap the content in the given range in a
  1015. node of the given type. May introduce extra nodes around and inside
  1016. the wrapper node, if necessary. Returns null if no valid wrapping
  1017. could be found. When `innerRange` is given, that range's content is
  1018. used as the content to fit into the wrapping, instead of the
  1019. content of `range`.
  1020. */
  1021. function findWrapping(range, nodeType, attrs = null, innerRange = range) {
  1022. let around = findWrappingOutside(range, nodeType);
  1023. let inner = around && findWrappingInside(innerRange, nodeType);
  1024. if (!inner)
  1025. return null;
  1026. return around.map(withAttrs)
  1027. .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));
  1028. }
  1029. function withAttrs(type) { return { type, attrs: null }; }
  1030. function findWrappingOutside(range, type) {
  1031. let { parent, startIndex, endIndex } = range;
  1032. let around = parent.contentMatchAt(startIndex).findWrapping(type);
  1033. if (!around)
  1034. return null;
  1035. let outer = around.length ? around[0] : type;
  1036. return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
  1037. }
  1038. function findWrappingInside(range, type) {
  1039. let { parent, startIndex, endIndex } = range;
  1040. let inner = parent.child(startIndex);
  1041. let inside = type.contentMatch.findWrapping(inner.type);
  1042. if (!inside)
  1043. return null;
  1044. let lastType = inside.length ? inside[inside.length - 1] : type;
  1045. let innerMatch = lastType.contentMatch;
  1046. for (let i = startIndex; innerMatch && i < endIndex; i++)
  1047. innerMatch = innerMatch.matchType(parent.child(i).type);
  1048. if (!innerMatch || !innerMatch.validEnd)
  1049. return null;
  1050. return inside;
  1051. }
  1052. function wrap(tr, range, wrappers) {
  1053. let content = Fragment.empty;
  1054. for (let i = wrappers.length - 1; i >= 0; i--) {
  1055. if (content.size) {
  1056. let match = wrappers[i].type.contentMatch.matchFragment(content);
  1057. if (!match || !match.validEnd)
  1058. throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
  1059. }
  1060. content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  1061. }
  1062. let start = range.start, end = range.end;
  1063. tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));
  1064. }
  1065. function setBlockType(tr, from, to, type, attrs) {
  1066. if (!type.isTextblock)
  1067. throw new RangeError("Type given to setBlockType should be a textblock");
  1068. let mapFrom = tr.steps.length;
  1069. tr.doc.nodesBetween(from, to, (node, pos) => {
  1070. if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {
  1071. // Ensure all markup that isn't allowed in the new node type is cleared
  1072. tr.clearIncompatible(tr.mapping.slice(mapFrom).map(pos, 1), type);
  1073. let mapping = tr.mapping.slice(mapFrom);
  1074. let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);
  1075. tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true));
  1076. return false;
  1077. }
  1078. });
  1079. }
  1080. function canChangeType(doc, pos, type) {
  1081. let $pos = doc.resolve(pos), index = $pos.index();
  1082. return $pos.parent.canReplaceWith(index, index + 1, type);
  1083. }
  1084. /**
  1085. Change the type, attributes, and/or marks of the node at `pos`.
  1086. When `type` isn't given, the existing node type is preserved,
  1087. */
  1088. function setNodeMarkup(tr, pos, type, attrs, marks) {
  1089. let node = tr.doc.nodeAt(pos);
  1090. if (!node)
  1091. throw new RangeError("No node at given position");
  1092. if (!type)
  1093. type = node.type;
  1094. let newNode = type.create(attrs, null, marks || node.marks);
  1095. if (node.isLeaf)
  1096. return tr.replaceWith(pos, pos + node.nodeSize, newNode);
  1097. if (!type.validContent(node.content))
  1098. throw new RangeError("Invalid content for node type " + type.name);
  1099. tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
  1100. }
  1101. /**
  1102. Check whether splitting at the given position is allowed.
  1103. */
  1104. function canSplit(doc, pos, depth = 1, typesAfter) {
  1105. let $pos = doc.resolve(pos), base = $pos.depth - depth;
  1106. let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;
  1107. if (base < 0 || $pos.parent.type.spec.isolating ||
  1108. !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||
  1109. !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))
  1110. return false;
  1111. for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {
  1112. let node = $pos.node(d), index = $pos.index(d);
  1113. if (node.type.spec.isolating)
  1114. return false;
  1115. let rest = node.content.cutByIndex(index, node.childCount);
  1116. let overrideChild = typesAfter && typesAfter[i + 1];
  1117. if (overrideChild)
  1118. rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));
  1119. let after = (typesAfter && typesAfter[i]) || node;
  1120. if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))
  1121. return false;
  1122. }
  1123. let index = $pos.indexAfter(base);
  1124. let baseType = typesAfter && typesAfter[0];
  1125. return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);
  1126. }
  1127. function split(tr, pos, depth = 1, typesAfter) {
  1128. let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;
  1129. for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {
  1130. before = Fragment.from($pos.node(d).copy(before));
  1131. let typeAfter = typesAfter && typesAfter[i];
  1132. after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));
  1133. }
  1134. tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));
  1135. }
  1136. /**
  1137. Test whether the blocks before and after a given position can be
  1138. joined.
  1139. */
  1140. function canJoin(doc, pos) {
  1141. let $pos = doc.resolve(pos), index = $pos.index();
  1142. return joinable($pos.nodeBefore, $pos.nodeAfter) &&
  1143. $pos.parent.canReplace(index, index + 1);
  1144. }
  1145. function joinable(a, b) {
  1146. return !!(a && b && !a.isLeaf && a.canAppend(b));
  1147. }
  1148. /**
  1149. Find an ancestor of the given position that can be joined to the
  1150. block before (or after if `dir` is positive). Returns the joinable
  1151. point, if any.
  1152. */
  1153. function joinPoint(doc, pos, dir = -1) {
  1154. let $pos = doc.resolve(pos);
  1155. for (let d = $pos.depth;; d--) {
  1156. let before, after, index = $pos.index(d);
  1157. if (d == $pos.depth) {
  1158. before = $pos.nodeBefore;
  1159. after = $pos.nodeAfter;
  1160. }
  1161. else if (dir > 0) {
  1162. before = $pos.node(d + 1);
  1163. index++;
  1164. after = $pos.node(d).maybeChild(index);
  1165. }
  1166. else {
  1167. before = $pos.node(d).maybeChild(index - 1);
  1168. after = $pos.node(d + 1);
  1169. }
  1170. if (before && !before.isTextblock && joinable(before, after) &&
  1171. $pos.node(d).canReplace(index, index + 1))
  1172. return pos;
  1173. if (d == 0)
  1174. break;
  1175. pos = dir < 0 ? $pos.before(d) : $pos.after(d);
  1176. }
  1177. }
  1178. function join(tr, pos, depth) {
  1179. let step = new ReplaceStep(pos - depth, pos + depth, Slice.empty, true);
  1180. tr.step(step);
  1181. }
  1182. /**
  1183. Try to find a point where a node of the given type can be inserted
  1184. near `pos`, by searching up the node hierarchy when `pos` itself
  1185. isn't a valid place but is at the start or end of a node. Return
  1186. null if no position was found.
  1187. */
  1188. function insertPoint(doc, pos, nodeType) {
  1189. let $pos = doc.resolve(pos);
  1190. if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))
  1191. return pos;
  1192. if ($pos.parentOffset == 0)
  1193. for (let d = $pos.depth - 1; d >= 0; d--) {
  1194. let index = $pos.index(d);
  1195. if ($pos.node(d).canReplaceWith(index, index, nodeType))
  1196. return $pos.before(d + 1);
  1197. if (index > 0)
  1198. return null;
  1199. }
  1200. if ($pos.parentOffset == $pos.parent.content.size)
  1201. for (let d = $pos.depth - 1; d >= 0; d--) {
  1202. let index = $pos.indexAfter(d);
  1203. if ($pos.node(d).canReplaceWith(index, index, nodeType))
  1204. return $pos.after(d + 1);
  1205. if (index < $pos.node(d).childCount)
  1206. return null;
  1207. }
  1208. return null;
  1209. }
  1210. /**
  1211. Finds a position at or around the given position where the given
  1212. slice can be inserted. Will look at parent nodes' nearest boundary
  1213. and try there, even if the original position wasn't directly at the
  1214. start or end of that node. Returns null when no position was found.
  1215. */
  1216. function dropPoint(doc, pos, slice) {
  1217. let $pos = doc.resolve(pos);
  1218. if (!slice.content.size)
  1219. return pos;
  1220. let content = slice.content;
  1221. for (let i = 0; i < slice.openStart; i++)
  1222. content = content.firstChild.content;
  1223. for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {
  1224. for (let d = $pos.depth; d >= 0; d--) {
  1225. let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;
  1226. let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);
  1227. let parent = $pos.node(d), fits = false;
  1228. if (pass == 1) {
  1229. fits = parent.canReplace(insertPos, insertPos, content);
  1230. }
  1231. else {
  1232. let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);
  1233. fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);
  1234. }
  1235. if (fits)
  1236. return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);
  1237. }
  1238. }
  1239. return null;
  1240. }
  1241. /**
  1242. ‘Fit’ a slice into a given position in the document, producing a
  1243. [step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if
  1244. there's no meaningful way to insert the slice here, or inserting it
  1245. would be a no-op (an empty slice over an empty range).
  1246. */
  1247. function replaceStep(doc, from, to = from, slice = Slice.empty) {
  1248. if (from == to && !slice.size)
  1249. return null;
  1250. let $from = doc.resolve(from), $to = doc.resolve(to);
  1251. // Optimization -- avoid work if it's obvious that it's not needed.
  1252. if (fitsTrivially($from, $to, slice))
  1253. return new ReplaceStep(from, to, slice);
  1254. return new Fitter($from, $to, slice).fit();
  1255. }
  1256. function fitsTrivially($from, $to, slice) {
  1257. return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&
  1258. $from.parent.canReplace($from.index(), $to.index(), slice.content);
  1259. }
  1260. // Algorithm for 'placing' the elements of a slice into a gap:
  1261. //
  1262. // We consider the content of each node that is open to the left to be
  1263. // independently placeable. I.e. in <p("foo"), p("bar")>, when the
  1264. // paragraph on the left is open, "foo" can be placed (somewhere on
  1265. // the left side of the replacement gap) independently from p("bar").
  1266. //
  1267. // This class tracks the state of the placement progress in the
  1268. // following properties:
  1269. //
  1270. // - `frontier` holds a stack of `{type, match}` objects that
  1271. // represent the open side of the replacement. It starts at
  1272. // `$from`, then moves forward as content is placed, and is finally
  1273. // reconciled with `$to`.
  1274. //
  1275. // - `unplaced` is a slice that represents the content that hasn't
  1276. // been placed yet.
  1277. //
  1278. // - `placed` is a fragment of placed content. Its open-start value
  1279. // is implicit in `$from`, and its open-end value in `frontier`.
  1280. class Fitter {
  1281. constructor($from, $to, unplaced) {
  1282. this.$from = $from;
  1283. this.$to = $to;
  1284. this.unplaced = unplaced;
  1285. this.frontier = [];
  1286. this.placed = Fragment.empty;
  1287. for (let i = 0; i <= $from.depth; i++) {
  1288. let node = $from.node(i);
  1289. this.frontier.push({
  1290. type: node.type,
  1291. match: node.contentMatchAt($from.indexAfter(i))
  1292. });
  1293. }
  1294. for (let i = $from.depth; i > 0; i--)
  1295. this.placed = Fragment.from($from.node(i).copy(this.placed));
  1296. }
  1297. get depth() { return this.frontier.length - 1; }
  1298. fit() {
  1299. // As long as there's unplaced content, try to place some of it.
  1300. // If that fails, either increase the open score of the unplaced
  1301. // slice, or drop nodes from it, and then try again.
  1302. while (this.unplaced.size) {
  1303. let fit = this.findFittable();
  1304. if (fit)
  1305. this.placeNodes(fit);
  1306. else
  1307. this.openMore() || this.dropNode();
  1308. }
  1309. // When there's inline content directly after the frontier _and_
  1310. // directly after `this.$to`, we must generate a `ReplaceAround`
  1311. // step that pulls that content into the node after the frontier.
  1312. // That means the fitting must be done to the end of the textblock
  1313. // node after `this.$to`, not `this.$to` itself.
  1314. let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
  1315. let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
  1316. if (!$to)
  1317. return null;
  1318. // If closing to `$to` succeeded, create a step
  1319. let content = this.placed, openStart = $from.depth, openEnd = $to.depth;
  1320. while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes
  1321. content = content.firstChild.content;
  1322. openStart--;
  1323. openEnd--;
  1324. }
  1325. let slice = new Slice(content, openStart, openEnd);
  1326. if (moveInline > -1)
  1327. return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);
  1328. if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps
  1329. return new ReplaceStep($from.pos, $to.pos, slice);
  1330. return null;
  1331. }
  1332. // Find a position on the start spine of `this.unplaced` that has
  1333. // content that can be moved somewhere on the frontier. Returns two
  1334. // depths, one for the slice and one for the frontier.
  1335. findFittable() {
  1336. let startDepth = this.unplaced.openStart;
  1337. for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {
  1338. let node = cur.firstChild;
  1339. if (cur.childCount > 1)
  1340. openEnd = 0;
  1341. if (node.type.spec.isolating && openEnd <= d) {
  1342. startDepth = d;
  1343. break;
  1344. }
  1345. cur = node.content;
  1346. }
  1347. // Only try wrapping nodes (pass 2) after finding a place without
  1348. // wrapping failed.
  1349. for (let pass = 1; pass <= 2; pass++) {
  1350. for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
  1351. let fragment, parent = null;
  1352. if (sliceDepth) {
  1353. parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
  1354. fragment = parent.content;
  1355. }
  1356. else {
  1357. fragment = this.unplaced.content;
  1358. }
  1359. let first = fragment.firstChild;
  1360. for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
  1361. let { type, match } = this.frontier[frontierDepth], wrap, inject = null;
  1362. // In pass 1, if the next node matches, or there is no next
  1363. // node but the parents look compatible, we've found a
  1364. // place.
  1365. if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))
  1366. : parent && type.compatibleContent(parent.type)))
  1367. return { sliceDepth, frontierDepth, parent, inject };
  1368. // In pass 2, look for a set of wrapping nodes that make
  1369. // `first` fit here.
  1370. else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))
  1371. return { sliceDepth, frontierDepth, parent, wrap };
  1372. // Don't continue looking further up if the parent node
  1373. // would fit here.
  1374. if (parent && match.matchType(parent.type))
  1375. break;
  1376. }
  1377. }
  1378. }
  1379. }
  1380. openMore() {
  1381. let { content, openStart, openEnd } = this.unplaced;
  1382. let inner = contentAt(content, openStart);
  1383. if (!inner.childCount || inner.firstChild.isLeaf)
  1384. return false;
  1385. this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));
  1386. return true;
  1387. }
  1388. dropNode() {
  1389. let { content, openStart, openEnd } = this.unplaced;
  1390. let inner = contentAt(content, openStart);
  1391. if (inner.childCount <= 1 && openStart > 0) {
  1392. let openAtEnd = content.size - openStart <= openStart + inner.size;
  1393. this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
  1394. }
  1395. else {
  1396. this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
  1397. }
  1398. }
  1399. // Move content from the unplaced slice at `sliceDepth` to the
  1400. // frontier node at `frontierDepth`. Close that frontier node when
  1401. // applicable.
  1402. placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {
  1403. while (this.depth > frontierDepth)
  1404. this.closeFrontierNode();
  1405. if (wrap)
  1406. for (let i = 0; i < wrap.length; i++)
  1407. this.openFrontierNode(wrap[i]);
  1408. let slice = this.unplaced, fragment = parent ? parent.content : slice.content;
  1409. let openStart = slice.openStart - sliceDepth;
  1410. let taken = 0, add = [];
  1411. let { match, type } = this.frontier[frontierDepth];
  1412. if (inject) {
  1413. for (let i = 0; i < inject.childCount; i++)
  1414. add.push(inject.child(i));
  1415. match = match.matchFragment(inject);
  1416. }
  1417. // Computes the amount of (end) open nodes at the end of the
  1418. // fragment. When 0, the parent is open, but no more. When
  1419. // negative, nothing is open.
  1420. let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);
  1421. // Scan over the fragment, fitting as many child nodes as
  1422. // possible.
  1423. while (taken < fragment.childCount) {
  1424. let next = fragment.child(taken), matches = match.matchType(next.type);
  1425. if (!matches)
  1426. break;
  1427. taken++;
  1428. if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes
  1429. match = matches;
  1430. add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
  1431. }
  1432. }
  1433. let toEnd = taken == fragment.childCount;
  1434. if (!toEnd)
  1435. openEndCount = -1;
  1436. this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));
  1437. this.frontier[frontierDepth].match = match;
  1438. // If the parent types match, and the entire node was moved, and
  1439. // it's not open, close this frontier node right away.
  1440. if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)
  1441. this.closeFrontierNode();
  1442. // Add new frontier nodes for any open nodes at the end.
  1443. for (let i = 0, cur = fragment; i < openEndCount; i++) {
  1444. let node = cur.lastChild;
  1445. this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });
  1446. cur = node.content;
  1447. }
  1448. // Update `this.unplaced`. Drop the entire node from which we
  1449. // placed it we got to its end, otherwise just drop the placed
  1450. // nodes.
  1451. this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)
  1452. : sliceDepth == 0 ? Slice.empty
  1453. : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);
  1454. }
  1455. mustMoveInline() {
  1456. if (!this.$to.parent.isTextblock)
  1457. return -1;
  1458. let top = this.frontier[this.depth], level;
  1459. if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||
  1460. (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))
  1461. return -1;
  1462. let { depth } = this.$to, after = this.$to.after(depth);
  1463. while (depth > 1 && after == this.$to.end(--depth))
  1464. ++after;
  1465. return after;
  1466. }
  1467. findCloseLevel($to) {
  1468. scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {
  1469. let { match, type } = this.frontier[i];
  1470. let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));
  1471. let fit = contentAfterFits($to, i, type, match, dropInner);
  1472. if (!fit)
  1473. continue;
  1474. for (let d = i - 1; d >= 0; d--) {
  1475. let { match, type } = this.frontier[d];
  1476. let matches = contentAfterFits($to, d, type, match, true);
  1477. if (!matches || matches.childCount)
  1478. continue scan;
  1479. }
  1480. return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };
  1481. }
  1482. }
  1483. close($to) {
  1484. let close = this.findCloseLevel($to);
  1485. if (!close)
  1486. return null;
  1487. while (this.depth > close.depth)
  1488. this.closeFrontierNode();
  1489. if (close.fit.childCount)
  1490. this.placed = addToFragment(this.placed, close.depth, close.fit);
  1491. $to = close.move;
  1492. for (let d = close.depth + 1; d <= $to.depth; d++) {
  1493. let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));
  1494. this.openFrontierNode(node.type, node.attrs, add);
  1495. }
  1496. return $to;
  1497. }
  1498. openFrontierNode(type, attrs = null, content) {
  1499. let top = this.frontier[this.depth];
  1500. top.match = top.match.matchType(type);
  1501. this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));
  1502. this.frontier.push({ type, match: type.contentMatch });
  1503. }
  1504. closeFrontierNode() {
  1505. let open = this.frontier.pop();
  1506. let add = open.match.fillBefore(Fragment.empty, true);
  1507. if (add.childCount)
  1508. this.placed = addToFragment(this.placed, this.frontier.length, add);
  1509. }
  1510. }
  1511. function dropFromFragment(fragment, depth, count) {
  1512. if (depth == 0)
  1513. return fragment.cutByIndex(count, fragment.childCount);
  1514. return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));
  1515. }
  1516. function addToFragment(fragment, depth, content) {
  1517. if (depth == 0)
  1518. return fragment.append(content);
  1519. return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));
  1520. }
  1521. function contentAt(fragment, depth) {
  1522. for (let i = 0; i < depth; i++)
  1523. fragment = fragment.firstChild.content;
  1524. return fragment;
  1525. }
  1526. function closeNodeStart(node, openStart, openEnd) {
  1527. if (openStart <= 0)
  1528. return node;
  1529. let frag = node.content;
  1530. if (openStart > 1)
  1531. frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
  1532. if (openStart > 0) {
  1533. frag = node.type.contentMatch.fillBefore(frag).append(frag);
  1534. if (openEnd <= 0)
  1535. frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
  1536. }
  1537. return node.copy(frag);
  1538. }
  1539. function contentAfterFits($to, depth, type, match, open) {
  1540. let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);
  1541. if (index == node.childCount && !type.compatibleContent(node.type))
  1542. return null;
  1543. let fit = match.fillBefore(node.content, true, index);
  1544. return fit && !invalidMarks(type, node.content, index) ? fit : null;
  1545. }
  1546. function invalidMarks(type, fragment, start) {
  1547. for (let i = start; i < fragment.childCount; i++)
  1548. if (!type.allowsMarks(fragment.child(i).marks))
  1549. return true;
  1550. return false;
  1551. }
  1552. function definesContent(type) {
  1553. return type.spec.defining || type.spec.definingForContent;
  1554. }
  1555. function replaceRange(tr, from, to, slice) {
  1556. if (!slice.size)
  1557. return tr.deleteRange(from, to);
  1558. let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);
  1559. if (fitsTrivially($from, $to, slice))
  1560. return tr.step(new ReplaceStep(from, to, slice));
  1561. let targetDepths = coveredDepths($from, tr.doc.resolve(to));
  1562. // Can't replace the whole document, so remove 0 if it's present
  1563. if (targetDepths[targetDepths.length - 1] == 0)
  1564. targetDepths.pop();
  1565. // Negative numbers represent not expansion over the whole node at
  1566. // that depth, but replacing from $from.before(-D) to $to.pos.
  1567. let preferredTarget = -($from.depth + 1);
  1568. targetDepths.unshift(preferredTarget);
  1569. // This loop picks a preferred target depth, if one of the covering
  1570. // depths is not outside of a defining node, and adds negative
  1571. // depths for any depth that has $from at its start and does not
  1572. // cross a defining node.
  1573. for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {
  1574. let spec = $from.node(d).type.spec;
  1575. if (spec.defining || spec.definingAsContext || spec.isolating)
  1576. break;
  1577. if (targetDepths.indexOf(d) > -1)
  1578. preferredTarget = d;
  1579. else if ($from.before(d) == pos)
  1580. targetDepths.splice(1, 0, -d);
  1581. }
  1582. // Try to fit each possible depth of the slice into each possible
  1583. // target depth, starting with the preferred depths.
  1584. let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
  1585. let leftNodes = [], preferredDepth = slice.openStart;
  1586. for (let content = slice.content, i = 0;; i++) {
  1587. let node = content.firstChild;
  1588. leftNodes.push(node);
  1589. if (i == slice.openStart)
  1590. break;
  1591. content = node.content;
  1592. }
  1593. // Back up preferredDepth to cover defining textblocks directly
  1594. // above it, possibly skipping a non-defining textblock.
  1595. for (let d = preferredDepth - 1; d >= 0; d--) {
  1596. let leftNode = leftNodes[d], def = definesContent(leftNode.type);
  1597. if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))
  1598. preferredDepth = d;
  1599. else if (def || !leftNode.type.isTextblock)
  1600. break;
  1601. }
  1602. for (let j = slice.openStart; j >= 0; j--) {
  1603. let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);
  1604. let insert = leftNodes[openDepth];
  1605. if (!insert)
  1606. continue;
  1607. for (let i = 0; i < targetDepths.length; i++) {
  1608. // Loop over possible expansion levels, starting with the
  1609. // preferred one
  1610. let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;
  1611. if (targetDepth < 0) {
  1612. expand = false;
  1613. targetDepth = -targetDepth;
  1614. }
  1615. let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);
  1616. if (parent.canReplaceWith(index, index, insert.type, insert.marks))
  1617. return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));
  1618. }
  1619. }
  1620. let startSteps = tr.steps.length;
  1621. for (let i = targetDepths.length - 1; i >= 0; i--) {
  1622. tr.replace(from, to, slice);
  1623. if (tr.steps.length > startSteps)
  1624. break;
  1625. let depth = targetDepths[i];
  1626. if (depth < 0)
  1627. continue;
  1628. from = $from.before(depth);
  1629. to = $to.after(depth);
  1630. }
  1631. }
  1632. function closeFragment(fragment, depth, oldOpen, newOpen, parent) {
  1633. if (depth < oldOpen) {
  1634. let first = fragment.firstChild;
  1635. fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));
  1636. }
  1637. if (depth > newOpen) {
  1638. let match = parent.contentMatchAt(0);
  1639. let start = match.fillBefore(fragment).append(fragment);
  1640. fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));
  1641. }
  1642. return fragment;
  1643. }
  1644. function replaceRangeWith(tr, from, to, node) {
  1645. if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {
  1646. let point = insertPoint(tr.doc, from, node.type);
  1647. if (point != null)
  1648. from = to = point;
  1649. }
  1650. tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));
  1651. }
  1652. function deleteRange(tr, from, to) {
  1653. let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);
  1654. let covered = coveredDepths($from, $to);
  1655. for (let i = 0; i < covered.length; i++) {
  1656. let depth = covered[i], last = i == covered.length - 1;
  1657. if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)
  1658. return tr.delete($from.start(depth), $to.end(depth));
  1659. if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
  1660. return tr.delete($from.before(depth), $to.after(depth));
  1661. }
  1662. for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {
  1663. if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d)
  1664. return tr.delete($from.before(d), to);
  1665. }
  1666. tr.delete(from, to);
  1667. }
  1668. // Returns an array of all depths for which $from - $to spans the
  1669. // whole content of the nodes at that depth.
  1670. function coveredDepths($from, $to) {
  1671. let result = [], minDepth = Math.min($from.depth, $to.depth);
  1672. for (let d = minDepth; d >= 0; d--) {
  1673. let start = $from.start(d);
  1674. if (start < $from.pos - ($from.depth - d) ||
  1675. $to.end(d) > $to.pos + ($to.depth - d) ||
  1676. $from.node(d).type.spec.isolating ||
  1677. $to.node(d).type.spec.isolating)
  1678. break;
  1679. if (start == $to.start(d) ||
  1680. (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&
  1681. d && $to.start(d - 1) == start - 1))
  1682. result.push(d);
  1683. }
  1684. return result;
  1685. }
  1686. /**
  1687. Update an attribute in a specific node.
  1688. */
  1689. class AttrStep extends Step {
  1690. /**
  1691. Construct an attribute step.
  1692. */
  1693. constructor(
  1694. /**
  1695. The position of the target node.
  1696. */
  1697. pos,
  1698. /**
  1699. The attribute to set.
  1700. */
  1701. attr,
  1702. // The attribute's new value.
  1703. value) {
  1704. super();
  1705. this.pos = pos;
  1706. this.attr = attr;
  1707. this.value = value;
  1708. }
  1709. apply(doc) {
  1710. let node = doc.nodeAt(this.pos);
  1711. if (!node)
  1712. return StepResult.fail("No node at attribute step's position");
  1713. let attrs = Object.create(null);
  1714. for (let name in node.attrs)
  1715. attrs[name] = node.attrs[name];
  1716. attrs[this.attr] = this.value;
  1717. let updated = node.type.create(attrs, null, node.marks);
  1718. return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  1719. }
  1720. getMap() {
  1721. return StepMap.empty;
  1722. }
  1723. invert(doc) {
  1724. return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);
  1725. }
  1726. map(mapping) {
  1727. let pos = mapping.mapResult(this.pos, 1);
  1728. return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);
  1729. }
  1730. toJSON() {
  1731. return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
  1732. }
  1733. static fromJSON(schema, json) {
  1734. if (typeof json.pos != "number" || typeof json.attr != "string")
  1735. throw new RangeError("Invalid input for AttrStep.fromJSON");
  1736. return new AttrStep(json.pos, json.attr, json.value);
  1737. }
  1738. }
  1739. Step.jsonID("attr", AttrStep);
  1740. /**
  1741. Update an attribute in the doc node.
  1742. */
  1743. class DocAttrStep extends Step {
  1744. /**
  1745. Construct an attribute step.
  1746. */
  1747. constructor(
  1748. /**
  1749. The attribute to set.
  1750. */
  1751. attr,
  1752. // The attribute's new value.
  1753. value) {
  1754. super();
  1755. this.attr = attr;
  1756. this.value = value;
  1757. }
  1758. apply(doc) {
  1759. let attrs = Object.create(null);
  1760. for (let name in doc.attrs)
  1761. attrs[name] = doc.attrs[name];
  1762. attrs[this.attr] = this.value;
  1763. let updated = doc.type.create(attrs, doc.content, doc.marks);
  1764. return StepResult.ok(updated);
  1765. }
  1766. getMap() {
  1767. return StepMap.empty;
  1768. }
  1769. invert(doc) {
  1770. return new DocAttrStep(this.attr, doc.attrs[this.attr]);
  1771. }
  1772. map(mapping) {
  1773. return this;
  1774. }
  1775. toJSON() {
  1776. return { stepType: "docAttr", attr: this.attr, value: this.value };
  1777. }
  1778. static fromJSON(schema, json) {
  1779. if (typeof json.attr != "string")
  1780. throw new RangeError("Invalid input for DocAttrStep.fromJSON");
  1781. return new DocAttrStep(json.attr, json.value);
  1782. }
  1783. }
  1784. Step.jsonID("docAttr", DocAttrStep);
  1785. /**
  1786. @internal
  1787. */
  1788. let TransformError = class extends Error {
  1789. };
  1790. TransformError = function TransformError(message) {
  1791. let err = Error.call(this, message);
  1792. err.__proto__ = TransformError.prototype;
  1793. return err;
  1794. };
  1795. TransformError.prototype = Object.create(Error.prototype);
  1796. TransformError.prototype.constructor = TransformError;
  1797. TransformError.prototype.name = "TransformError";
  1798. /**
  1799. Abstraction to build up and track an array of
  1800. [steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.
  1801. Most transforming methods return the `Transform` object itself, so
  1802. that they can be chained.
  1803. */
  1804. class Transform {
  1805. /**
  1806. Create a transform that starts with the given document.
  1807. */
  1808. constructor(
  1809. /**
  1810. The current document (the result of applying the steps in the
  1811. transform).
  1812. */
  1813. doc) {
  1814. this.doc = doc;
  1815. /**
  1816. The steps in this transform.
  1817. */
  1818. this.steps = [];
  1819. /**
  1820. The documents before each of the steps.
  1821. */
  1822. this.docs = [];
  1823. /**
  1824. A mapping with the maps for each of the steps in this transform.
  1825. */
  1826. this.mapping = new Mapping;
  1827. }
  1828. /**
  1829. The starting document.
  1830. */
  1831. get before() { return this.docs.length ? this.docs[0] : this.doc; }
  1832. /**
  1833. Apply a new step in this transform, saving the result. Throws an
  1834. error when the step fails.
  1835. */
  1836. step(step) {
  1837. let result = this.maybeStep(step);
  1838. if (result.failed)
  1839. throw new TransformError(result.failed);
  1840. return this;
  1841. }
  1842. /**
  1843. Try to apply a step in this transformation, ignoring it if it
  1844. fails. Returns the step result.
  1845. */
  1846. maybeStep(step) {
  1847. let result = step.apply(this.doc);
  1848. if (!result.failed)
  1849. this.addStep(step, result.doc);
  1850. return result;
  1851. }
  1852. /**
  1853. True when the document has been changed (when there are any
  1854. steps).
  1855. */
  1856. get docChanged() {
  1857. return this.steps.length > 0;
  1858. }
  1859. /**
  1860. @internal
  1861. */
  1862. addStep(step, doc) {
  1863. this.docs.push(this.doc);
  1864. this.steps.push(step);
  1865. this.mapping.appendMap(step.getMap());
  1866. this.doc = doc;
  1867. }
  1868. /**
  1869. Replace the part of the document between `from` and `to` with the
  1870. given `slice`.
  1871. */
  1872. replace(from, to = from, slice = Slice.empty) {
  1873. let step = replaceStep(this.doc, from, to, slice);
  1874. if (step)
  1875. this.step(step);
  1876. return this;
  1877. }
  1878. /**
  1879. Replace the given range with the given content, which may be a
  1880. fragment, node, or array of nodes.
  1881. */
  1882. replaceWith(from, to, content) {
  1883. return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));
  1884. }
  1885. /**
  1886. Delete the content between the given positions.
  1887. */
  1888. delete(from, to) {
  1889. return this.replace(from, to, Slice.empty);
  1890. }
  1891. /**
  1892. Insert the given content at the given position.
  1893. */
  1894. insert(pos, content) {
  1895. return this.replaceWith(pos, pos, content);
  1896. }
  1897. /**
  1898. Replace a range of the document with a given slice, using
  1899. `from`, `to`, and the slice's
  1900. [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather
  1901. than fixed start and end points. This method may grow the
  1902. replaced area or close open nodes in the slice in order to get a
  1903. fit that is more in line with WYSIWYG expectations, by dropping
  1904. fully covered parent nodes of the replaced region when they are
  1905. marked [non-defining as
  1906. context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an
  1907. open parent node from the slice that _is_ marked as [defining
  1908. its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).
  1909. This is the method, for example, to handle paste. The similar
  1910. [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more
  1911. primitive tool which will _not_ move the start and end of its given
  1912. range, and is useful in situations where you need more precise
  1913. control over what happens.
  1914. */
  1915. replaceRange(from, to, slice) {
  1916. replaceRange(this, from, to, slice);
  1917. return this;
  1918. }
  1919. /**
  1920. Replace the given range with a node, but use `from` and `to` as
  1921. hints, rather than precise positions. When from and to are the same
  1922. and are at the start or end of a parent node in which the given
  1923. node doesn't fit, this method may _move_ them out towards a parent
  1924. that does allow the given node to be placed. When the given range
  1925. completely covers a parent node, this method may completely replace
  1926. that parent node.
  1927. */
  1928. replaceRangeWith(from, to, node) {
  1929. replaceRangeWith(this, from, to, node);
  1930. return this;
  1931. }
  1932. /**
  1933. Delete the given range, expanding it to cover fully covered
  1934. parent nodes until a valid replace is found.
  1935. */
  1936. deleteRange(from, to) {
  1937. deleteRange(this, from, to);
  1938. return this;
  1939. }
  1940. /**
  1941. Split the content in the given range off from its parent, if there
  1942. is sibling content before or after it, and move it up the tree to
  1943. the depth specified by `target`. You'll probably want to use
  1944. [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make
  1945. sure the lift is valid.
  1946. */
  1947. lift(range, target) {
  1948. lift(this, range, target);
  1949. return this;
  1950. }
  1951. /**
  1952. Join the blocks around the given position. If depth is 2, their
  1953. last and first siblings are also joined, and so on.
  1954. */
  1955. join(pos, depth = 1) {
  1956. join(this, pos, depth);
  1957. return this;
  1958. }
  1959. /**
  1960. Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.
  1961. The wrappers are assumed to be valid in this position, and should
  1962. probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).
  1963. */
  1964. wrap(range, wrappers) {
  1965. wrap(this, range, wrappers);
  1966. return this;
  1967. }
  1968. /**
  1969. Set the type of all textblocks (partly) between `from` and `to` to
  1970. the given node type with the given attributes.
  1971. */
  1972. setBlockType(from, to = from, type, attrs = null) {
  1973. setBlockType(this, from, to, type, attrs);
  1974. return this;
  1975. }
  1976. /**
  1977. Change the type, attributes, and/or marks of the node at `pos`.
  1978. When `type` isn't given, the existing node type is preserved,
  1979. */
  1980. setNodeMarkup(pos, type, attrs = null, marks) {
  1981. setNodeMarkup(this, pos, type, attrs, marks);
  1982. return this;
  1983. }
  1984. /**
  1985. Set a single attribute on a given node to a new value.
  1986. The `pos` addresses the document content. Use `setDocAttribute`
  1987. to set attributes on the document itself.
  1988. */
  1989. setNodeAttribute(pos, attr, value) {
  1990. this.step(new AttrStep(pos, attr, value));
  1991. return this;
  1992. }
  1993. /**
  1994. Set a single attribute on the document to a new value.
  1995. */
  1996. setDocAttribute(attr, value) {
  1997. this.step(new DocAttrStep(attr, value));
  1998. return this;
  1999. }
  2000. /**
  2001. Add a mark to the node at position `pos`.
  2002. */
  2003. addNodeMark(pos, mark) {
  2004. this.step(new AddNodeMarkStep(pos, mark));
  2005. return this;
  2006. }
  2007. /**
  2008. Remove a mark (or a mark of the given type) from the node at
  2009. position `pos`.
  2010. */
  2011. removeNodeMark(pos, mark) {
  2012. if (!(mark instanceof Mark)) {
  2013. let node = this.doc.nodeAt(pos);
  2014. if (!node)
  2015. throw new RangeError("No node at position " + pos);
  2016. mark = mark.isInSet(node.marks);
  2017. if (!mark)
  2018. return this;
  2019. }
  2020. this.step(new RemoveNodeMarkStep(pos, mark));
  2021. return this;
  2022. }
  2023. /**
  2024. Split the node at the given position, and optionally, if `depth` is
  2025. greater than one, any number of nodes above that. By default, the
  2026. parts split off will inherit the node type of the original node.
  2027. This can be changed by passing an array of types and attributes to
  2028. use after the split.
  2029. */
  2030. split(pos, depth = 1, typesAfter) {
  2031. split(this, pos, depth, typesAfter);
  2032. return this;
  2033. }
  2034. /**
  2035. Add the given mark to the inline content between `from` and `to`.
  2036. */
  2037. addMark(from, to, mark) {
  2038. addMark(this, from, to, mark);
  2039. return this;
  2040. }
  2041. /**
  2042. Remove marks from inline nodes between `from` and `to`. When
  2043. `mark` is a single mark, remove precisely that mark. When it is
  2044. a mark type, remove all marks of that type. When it is null,
  2045. remove all marks of any type.
  2046. */
  2047. removeMark(from, to, mark) {
  2048. removeMark(this, from, to, mark);
  2049. return this;
  2050. }
  2051. /**
  2052. Removes all marks and nodes from the content of the node at
  2053. `pos` that don't match the given new parent node type. Accepts
  2054. an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as
  2055. third argument.
  2056. */
  2057. clearIncompatible(pos, parentType, match) {
  2058. clearIncompatible(this, pos, parentType, match);
  2059. return this;
  2060. }
  2061. }
  2062. export { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };