index.js 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400
  1. import OrderedMap from 'orderedmap';
  2. function findDiffStart(a, b, pos) {
  3. for (let i = 0;; i++) {
  4. if (i == a.childCount || i == b.childCount)
  5. return a.childCount == b.childCount ? null : pos;
  6. let childA = a.child(i), childB = b.child(i);
  7. if (childA == childB) {
  8. pos += childA.nodeSize;
  9. continue;
  10. }
  11. if (!childA.sameMarkup(childB))
  12. return pos;
  13. if (childA.isText && childA.text != childB.text) {
  14. for (let j = 0; childA.text[j] == childB.text[j]; j++)
  15. pos++;
  16. return pos;
  17. }
  18. if (childA.content.size || childB.content.size) {
  19. let inner = findDiffStart(childA.content, childB.content, pos + 1);
  20. if (inner != null)
  21. return inner;
  22. }
  23. pos += childA.nodeSize;
  24. }
  25. }
  26. function findDiffEnd(a, b, posA, posB) {
  27. for (let iA = a.childCount, iB = b.childCount;;) {
  28. if (iA == 0 || iB == 0)
  29. return iA == iB ? null : { a: posA, b: posB };
  30. let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;
  31. if (childA == childB) {
  32. posA -= size;
  33. posB -= size;
  34. continue;
  35. }
  36. if (!childA.sameMarkup(childB))
  37. return { a: posA, b: posB };
  38. if (childA.isText && childA.text != childB.text) {
  39. let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
  40. while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
  41. same++;
  42. posA--;
  43. posB--;
  44. }
  45. return { a: posA, b: posB };
  46. }
  47. if (childA.content.size || childB.content.size) {
  48. let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
  49. if (inner)
  50. return inner;
  51. }
  52. posA -= size;
  53. posB -= size;
  54. }
  55. }
  56. /**
  57. A fragment represents a node's collection of child nodes.
  58. Like nodes, fragments are persistent data structures, and you
  59. should not mutate them or their content. Rather, you create new
  60. instances whenever needed. The API tries to make this easy.
  61. */
  62. class Fragment {
  63. /**
  64. @internal
  65. */
  66. constructor(
  67. /**
  68. @internal
  69. */
  70. content, size) {
  71. this.content = content;
  72. this.size = size || 0;
  73. if (size == null)
  74. for (let i = 0; i < content.length; i++)
  75. this.size += content[i].nodeSize;
  76. }
  77. /**
  78. Invoke a callback for all descendant nodes between the given two
  79. positions (relative to start of this fragment). Doesn't descend
  80. into a node when the callback returns `false`.
  81. */
  82. nodesBetween(from, to, f, nodeStart = 0, parent) {
  83. for (let i = 0, pos = 0; pos < to; i++) {
  84. let child = this.content[i], end = pos + child.nodeSize;
  85. if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {
  86. let start = pos + 1;
  87. child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);
  88. }
  89. pos = end;
  90. }
  91. }
  92. /**
  93. Call the given callback for every descendant node. `pos` will be
  94. relative to the start of the fragment. The callback may return
  95. `false` to prevent traversal of a given node's children.
  96. */
  97. descendants(f) {
  98. this.nodesBetween(0, this.size, f);
  99. }
  100. /**
  101. Extract the text between `from` and `to`. See the same method on
  102. [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
  103. */
  104. textBetween(from, to, blockSeparator, leafText) {
  105. let text = "", first = true;
  106. this.nodesBetween(from, to, (node, pos) => {
  107. let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)
  108. : !node.isLeaf ? ""
  109. : leafText ? (typeof leafText === "function" ? leafText(node) : leafText)
  110. : node.type.spec.leafText ? node.type.spec.leafText(node)
  111. : "";
  112. if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
  113. if (first)
  114. first = false;
  115. else
  116. text += blockSeparator;
  117. }
  118. text += nodeText;
  119. }, 0);
  120. return text;
  121. }
  122. /**
  123. Create a new fragment containing the combined content of this
  124. fragment and the other.
  125. */
  126. append(other) {
  127. if (!other.size)
  128. return this;
  129. if (!this.size)
  130. return other;
  131. let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;
  132. if (last.isText && last.sameMarkup(first)) {
  133. content[content.length - 1] = last.withText(last.text + first.text);
  134. i = 1;
  135. }
  136. for (; i < other.content.length; i++)
  137. content.push(other.content[i]);
  138. return new Fragment(content, this.size + other.size);
  139. }
  140. /**
  141. Cut out the sub-fragment between the two given positions.
  142. */
  143. cut(from, to = this.size) {
  144. if (from == 0 && to == this.size)
  145. return this;
  146. let result = [], size = 0;
  147. if (to > from)
  148. for (let i = 0, pos = 0; pos < to; i++) {
  149. let child = this.content[i], end = pos + child.nodeSize;
  150. if (end > from) {
  151. if (pos < from || end > to) {
  152. if (child.isText)
  153. child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));
  154. else
  155. child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));
  156. }
  157. result.push(child);
  158. size += child.nodeSize;
  159. }
  160. pos = end;
  161. }
  162. return new Fragment(result, size);
  163. }
  164. /**
  165. @internal
  166. */
  167. cutByIndex(from, to) {
  168. if (from == to)
  169. return Fragment.empty;
  170. if (from == 0 && to == this.content.length)
  171. return this;
  172. return new Fragment(this.content.slice(from, to));
  173. }
  174. /**
  175. Create a new fragment in which the node at the given index is
  176. replaced by the given node.
  177. */
  178. replaceChild(index, node) {
  179. let current = this.content[index];
  180. if (current == node)
  181. return this;
  182. let copy = this.content.slice();
  183. let size = this.size + node.nodeSize - current.nodeSize;
  184. copy[index] = node;
  185. return new Fragment(copy, size);
  186. }
  187. /**
  188. Create a new fragment by prepending the given node to this
  189. fragment.
  190. */
  191. addToStart(node) {
  192. return new Fragment([node].concat(this.content), this.size + node.nodeSize);
  193. }
  194. /**
  195. Create a new fragment by appending the given node to this
  196. fragment.
  197. */
  198. addToEnd(node) {
  199. return new Fragment(this.content.concat(node), this.size + node.nodeSize);
  200. }
  201. /**
  202. Compare this fragment to another one.
  203. */
  204. eq(other) {
  205. if (this.content.length != other.content.length)
  206. return false;
  207. for (let i = 0; i < this.content.length; i++)
  208. if (!this.content[i].eq(other.content[i]))
  209. return false;
  210. return true;
  211. }
  212. /**
  213. The first child of the fragment, or `null` if it is empty.
  214. */
  215. get firstChild() { return this.content.length ? this.content[0] : null; }
  216. /**
  217. The last child of the fragment, or `null` if it is empty.
  218. */
  219. get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }
  220. /**
  221. The number of child nodes in this fragment.
  222. */
  223. get childCount() { return this.content.length; }
  224. /**
  225. Get the child node at the given index. Raise an error when the
  226. index is out of range.
  227. */
  228. child(index) {
  229. let found = this.content[index];
  230. if (!found)
  231. throw new RangeError("Index " + index + " out of range for " + this);
  232. return found;
  233. }
  234. /**
  235. Get the child node at the given index, if it exists.
  236. */
  237. maybeChild(index) {
  238. return this.content[index] || null;
  239. }
  240. /**
  241. Call `f` for every child node, passing the node, its offset
  242. into this parent node, and its index.
  243. */
  244. forEach(f) {
  245. for (let i = 0, p = 0; i < this.content.length; i++) {
  246. let child = this.content[i];
  247. f(child, p, i);
  248. p += child.nodeSize;
  249. }
  250. }
  251. /**
  252. Find the first position at which this fragment and another
  253. fragment differ, or `null` if they are the same.
  254. */
  255. findDiffStart(other, pos = 0) {
  256. return findDiffStart(this, other, pos);
  257. }
  258. /**
  259. Find the first position, searching from the end, at which this
  260. fragment and the given fragment differ, or `null` if they are
  261. the same. Since this position will not be the same in both
  262. nodes, an object with two separate positions is returned.
  263. */
  264. findDiffEnd(other, pos = this.size, otherPos = other.size) {
  265. return findDiffEnd(this, other, pos, otherPos);
  266. }
  267. /**
  268. Find the index and inner offset corresponding to a given relative
  269. position in this fragment. The result object will be reused
  270. (overwritten) the next time the function is called. (Not public.)
  271. */
  272. findIndex(pos, round = -1) {
  273. if (pos == 0)
  274. return retIndex(0, pos);
  275. if (pos == this.size)
  276. return retIndex(this.content.length, pos);
  277. if (pos > this.size || pos < 0)
  278. throw new RangeError(`Position ${pos} outside of fragment (${this})`);
  279. for (let i = 0, curPos = 0;; i++) {
  280. let cur = this.child(i), end = curPos + cur.nodeSize;
  281. if (end >= pos) {
  282. if (end == pos || round > 0)
  283. return retIndex(i + 1, end);
  284. return retIndex(i, curPos);
  285. }
  286. curPos = end;
  287. }
  288. }
  289. /**
  290. Return a debugging string that describes this fragment.
  291. */
  292. toString() { return "<" + this.toStringInner() + ">"; }
  293. /**
  294. @internal
  295. */
  296. toStringInner() { return this.content.join(", "); }
  297. /**
  298. Create a JSON-serializeable representation of this fragment.
  299. */
  300. toJSON() {
  301. return this.content.length ? this.content.map(n => n.toJSON()) : null;
  302. }
  303. /**
  304. Deserialize a fragment from its JSON representation.
  305. */
  306. static fromJSON(schema, value) {
  307. if (!value)
  308. return Fragment.empty;
  309. if (!Array.isArray(value))
  310. throw new RangeError("Invalid input for Fragment.fromJSON");
  311. return new Fragment(value.map(schema.nodeFromJSON));
  312. }
  313. /**
  314. Build a fragment from an array of nodes. Ensures that adjacent
  315. text nodes with the same marks are joined together.
  316. */
  317. static fromArray(array) {
  318. if (!array.length)
  319. return Fragment.empty;
  320. let joined, size = 0;
  321. for (let i = 0; i < array.length; i++) {
  322. let node = array[i];
  323. size += node.nodeSize;
  324. if (i && node.isText && array[i - 1].sameMarkup(node)) {
  325. if (!joined)
  326. joined = array.slice(0, i);
  327. joined[joined.length - 1] = node
  328. .withText(joined[joined.length - 1].text + node.text);
  329. }
  330. else if (joined) {
  331. joined.push(node);
  332. }
  333. }
  334. return new Fragment(joined || array, size);
  335. }
  336. /**
  337. Create a fragment from something that can be interpreted as a
  338. set of nodes. For `null`, it returns the empty fragment. For a
  339. fragment, the fragment itself. For a node or array of nodes, a
  340. fragment containing those nodes.
  341. */
  342. static from(nodes) {
  343. if (!nodes)
  344. return Fragment.empty;
  345. if (nodes instanceof Fragment)
  346. return nodes;
  347. if (Array.isArray(nodes))
  348. return this.fromArray(nodes);
  349. if (nodes.attrs)
  350. return new Fragment([nodes], nodes.nodeSize);
  351. throw new RangeError("Can not convert " + nodes + " to a Fragment" +
  352. (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
  353. }
  354. }
  355. /**
  356. An empty fragment. Intended to be reused whenever a node doesn't
  357. contain anything (rather than allocating a new empty fragment for
  358. each leaf node).
  359. */
  360. Fragment.empty = new Fragment([], 0);
  361. const found = { index: 0, offset: 0 };
  362. function retIndex(index, offset) {
  363. found.index = index;
  364. found.offset = offset;
  365. return found;
  366. }
  367. function compareDeep(a, b) {
  368. if (a === b)
  369. return true;
  370. if (!(a && typeof a == "object") ||
  371. !(b && typeof b == "object"))
  372. return false;
  373. let array = Array.isArray(a);
  374. if (Array.isArray(b) != array)
  375. return false;
  376. if (array) {
  377. if (a.length != b.length)
  378. return false;
  379. for (let i = 0; i < a.length; i++)
  380. if (!compareDeep(a[i], b[i]))
  381. return false;
  382. }
  383. else {
  384. for (let p in a)
  385. if (!(p in b) || !compareDeep(a[p], b[p]))
  386. return false;
  387. for (let p in b)
  388. if (!(p in a))
  389. return false;
  390. }
  391. return true;
  392. }
  393. /**
  394. A mark is a piece of information that can be attached to a node,
  395. such as it being emphasized, in code font, or a link. It has a
  396. type and optionally a set of attributes that provide further
  397. information (such as the target of the link). Marks are created
  398. through a `Schema`, which controls which types exist and which
  399. attributes they have.
  400. */
  401. class Mark {
  402. /**
  403. @internal
  404. */
  405. constructor(
  406. /**
  407. The type of this mark.
  408. */
  409. type,
  410. /**
  411. The attributes associated with this mark.
  412. */
  413. attrs) {
  414. this.type = type;
  415. this.attrs = attrs;
  416. }
  417. /**
  418. Given a set of marks, create a new set which contains this one as
  419. well, in the right position. If this mark is already in the set,
  420. the set itself is returned. If any marks that are set to be
  421. [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
  422. those are replaced by this one.
  423. */
  424. addToSet(set) {
  425. let copy, placed = false;
  426. for (let i = 0; i < set.length; i++) {
  427. let other = set[i];
  428. if (this.eq(other))
  429. return set;
  430. if (this.type.excludes(other.type)) {
  431. if (!copy)
  432. copy = set.slice(0, i);
  433. }
  434. else if (other.type.excludes(this.type)) {
  435. return set;
  436. }
  437. else {
  438. if (!placed && other.type.rank > this.type.rank) {
  439. if (!copy)
  440. copy = set.slice(0, i);
  441. copy.push(this);
  442. placed = true;
  443. }
  444. if (copy)
  445. copy.push(other);
  446. }
  447. }
  448. if (!copy)
  449. copy = set.slice();
  450. if (!placed)
  451. copy.push(this);
  452. return copy;
  453. }
  454. /**
  455. Remove this mark from the given set, returning a new set. If this
  456. mark is not in the set, the set itself is returned.
  457. */
  458. removeFromSet(set) {
  459. for (let i = 0; i < set.length; i++)
  460. if (this.eq(set[i]))
  461. return set.slice(0, i).concat(set.slice(i + 1));
  462. return set;
  463. }
  464. /**
  465. Test whether this mark is in the given set of marks.
  466. */
  467. isInSet(set) {
  468. for (let i = 0; i < set.length; i++)
  469. if (this.eq(set[i]))
  470. return true;
  471. return false;
  472. }
  473. /**
  474. Test whether this mark has the same type and attributes as
  475. another mark.
  476. */
  477. eq(other) {
  478. return this == other ||
  479. (this.type == other.type && compareDeep(this.attrs, other.attrs));
  480. }
  481. /**
  482. Convert this mark to a JSON-serializeable representation.
  483. */
  484. toJSON() {
  485. let obj = { type: this.type.name };
  486. for (let _ in this.attrs) {
  487. obj.attrs = this.attrs;
  488. break;
  489. }
  490. return obj;
  491. }
  492. /**
  493. Deserialize a mark from JSON.
  494. */
  495. static fromJSON(schema, json) {
  496. if (!json)
  497. throw new RangeError("Invalid input for Mark.fromJSON");
  498. let type = schema.marks[json.type];
  499. if (!type)
  500. throw new RangeError(`There is no mark type ${json.type} in this schema`);
  501. return type.create(json.attrs);
  502. }
  503. /**
  504. Test whether two sets of marks are identical.
  505. */
  506. static sameSet(a, b) {
  507. if (a == b)
  508. return true;
  509. if (a.length != b.length)
  510. return false;
  511. for (let i = 0; i < a.length; i++)
  512. if (!a[i].eq(b[i]))
  513. return false;
  514. return true;
  515. }
  516. /**
  517. Create a properly sorted mark set from null, a single mark, or an
  518. unsorted array of marks.
  519. */
  520. static setFrom(marks) {
  521. if (!marks || Array.isArray(marks) && marks.length == 0)
  522. return Mark.none;
  523. if (marks instanceof Mark)
  524. return [marks];
  525. let copy = marks.slice();
  526. copy.sort((a, b) => a.type.rank - b.type.rank);
  527. return copy;
  528. }
  529. }
  530. /**
  531. The empty set of marks.
  532. */
  533. Mark.none = [];
  534. /**
  535. Error type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when
  536. given an invalid replacement.
  537. */
  538. class ReplaceError extends Error {
  539. }
  540. /*
  541. ReplaceError = function(this: any, message: string) {
  542. let err = Error.call(this, message)
  543. ;(err as any).__proto__ = ReplaceError.prototype
  544. return err
  545. } as any
  546. ReplaceError.prototype = Object.create(Error.prototype)
  547. ReplaceError.prototype.constructor = ReplaceError
  548. ReplaceError.prototype.name = "ReplaceError"
  549. */
  550. /**
  551. A slice represents a piece cut out of a larger document. It
  552. stores not only a fragment, but also the depth up to which nodes on
  553. both side are ‘open’ (cut through).
  554. */
  555. class Slice {
  556. /**
  557. Create a slice. When specifying a non-zero open depth, you must
  558. make sure that there are nodes of at least that depth at the
  559. appropriate side of the fragment—i.e. if the fragment is an
  560. empty paragraph node, `openStart` and `openEnd` can't be greater
  561. than 1.
  562. It is not necessary for the content of open nodes to conform to
  563. the schema's content constraints, though it should be a valid
  564. start/end/middle for such a node, depending on which sides are
  565. open.
  566. */
  567. constructor(
  568. /**
  569. The slice's content.
  570. */
  571. content,
  572. /**
  573. The open depth at the start of the fragment.
  574. */
  575. openStart,
  576. /**
  577. The open depth at the end.
  578. */
  579. openEnd) {
  580. this.content = content;
  581. this.openStart = openStart;
  582. this.openEnd = openEnd;
  583. }
  584. /**
  585. The size this slice would add when inserted into a document.
  586. */
  587. get size() {
  588. return this.content.size - this.openStart - this.openEnd;
  589. }
  590. /**
  591. @internal
  592. */
  593. insertAt(pos, fragment) {
  594. let content = insertInto(this.content, pos + this.openStart, fragment);
  595. return content && new Slice(content, this.openStart, this.openEnd);
  596. }
  597. /**
  598. @internal
  599. */
  600. removeBetween(from, to) {
  601. return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);
  602. }
  603. /**
  604. Tests whether this slice is equal to another slice.
  605. */
  606. eq(other) {
  607. return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
  608. }
  609. /**
  610. @internal
  611. */
  612. toString() {
  613. return this.content + "(" + this.openStart + "," + this.openEnd + ")";
  614. }
  615. /**
  616. Convert a slice to a JSON-serializable representation.
  617. */
  618. toJSON() {
  619. if (!this.content.size)
  620. return null;
  621. let json = { content: this.content.toJSON() };
  622. if (this.openStart > 0)
  623. json.openStart = this.openStart;
  624. if (this.openEnd > 0)
  625. json.openEnd = this.openEnd;
  626. return json;
  627. }
  628. /**
  629. Deserialize a slice from its JSON representation.
  630. */
  631. static fromJSON(schema, json) {
  632. if (!json)
  633. return Slice.empty;
  634. let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
  635. if (typeof openStart != "number" || typeof openEnd != "number")
  636. throw new RangeError("Invalid input for Slice.fromJSON");
  637. return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);
  638. }
  639. /**
  640. Create a slice from a fragment by taking the maximum possible
  641. open value on both side of the fragment.
  642. */
  643. static maxOpen(fragment, openIsolating = true) {
  644. let openStart = 0, openEnd = 0;
  645. for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
  646. openStart++;
  647. for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
  648. openEnd++;
  649. return new Slice(fragment, openStart, openEnd);
  650. }
  651. }
  652. /**
  653. The empty slice.
  654. */
  655. Slice.empty = new Slice(Fragment.empty, 0, 0);
  656. function removeRange(content, from, to) {
  657. let { index, offset } = content.findIndex(from), child = content.maybeChild(index);
  658. let { index: indexTo, offset: offsetTo } = content.findIndex(to);
  659. if (offset == from || child.isText) {
  660. if (offsetTo != to && !content.child(indexTo).isText)
  661. throw new RangeError("Removing non-flat range");
  662. return content.cut(0, from).append(content.cut(to));
  663. }
  664. if (index != indexTo)
  665. throw new RangeError("Removing non-flat range");
  666. return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));
  667. }
  668. function insertInto(content, dist, insert, parent) {
  669. let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);
  670. if (offset == dist || child.isText) {
  671. if (parent && !parent.canReplace(index, index, insert))
  672. return null;
  673. return content.cut(0, dist).append(insert).append(content.cut(dist));
  674. }
  675. let inner = insertInto(child.content, dist - offset - 1, insert);
  676. return inner && content.replaceChild(index, child.copy(inner));
  677. }
  678. function replace($from, $to, slice) {
  679. if (slice.openStart > $from.depth)
  680. throw new ReplaceError("Inserted content deeper than insertion position");
  681. if ($from.depth - slice.openStart != $to.depth - slice.openEnd)
  682. throw new ReplaceError("Inconsistent open depths");
  683. return replaceOuter($from, $to, slice, 0);
  684. }
  685. function replaceOuter($from, $to, slice, depth) {
  686. let index = $from.index(depth), node = $from.node(depth);
  687. if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
  688. let inner = replaceOuter($from, $to, slice, depth + 1);
  689. return node.copy(node.content.replaceChild(index, inner));
  690. }
  691. else if (!slice.content.size) {
  692. return close(node, replaceTwoWay($from, $to, depth));
  693. }
  694. else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case
  695. let parent = $from.parent, content = parent.content;
  696. return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));
  697. }
  698. else {
  699. let { start, end } = prepareSliceForReplace(slice, $from);
  700. return close(node, replaceThreeWay($from, start, end, $to, depth));
  701. }
  702. }
  703. function checkJoin(main, sub) {
  704. if (!sub.type.compatibleContent(main.type))
  705. throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
  706. }
  707. function joinable($before, $after, depth) {
  708. let node = $before.node(depth);
  709. checkJoin(node, $after.node(depth));
  710. return node;
  711. }
  712. function addNode(child, target) {
  713. let last = target.length - 1;
  714. if (last >= 0 && child.isText && child.sameMarkup(target[last]))
  715. target[last] = child.withText(target[last].text + child.text);
  716. else
  717. target.push(child);
  718. }
  719. function addRange($start, $end, depth, target) {
  720. let node = ($end || $start).node(depth);
  721. let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
  722. if ($start) {
  723. startIndex = $start.index(depth);
  724. if ($start.depth > depth) {
  725. startIndex++;
  726. }
  727. else if ($start.textOffset) {
  728. addNode($start.nodeAfter, target);
  729. startIndex++;
  730. }
  731. }
  732. for (let i = startIndex; i < endIndex; i++)
  733. addNode(node.child(i), target);
  734. if ($end && $end.depth == depth && $end.textOffset)
  735. addNode($end.nodeBefore, target);
  736. }
  737. function close(node, content) {
  738. node.type.checkContent(content);
  739. return node.copy(content);
  740. }
  741. function replaceThreeWay($from, $start, $end, $to, depth) {
  742. let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
  743. let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
  744. let content = [];
  745. addRange(null, $from, depth, content);
  746. if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
  747. checkJoin(openStart, openEnd);
  748. addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
  749. }
  750. else {
  751. if (openStart)
  752. addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
  753. addRange($start, $end, depth, content);
  754. if (openEnd)
  755. addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
  756. }
  757. addRange($to, null, depth, content);
  758. return new Fragment(content);
  759. }
  760. function replaceTwoWay($from, $to, depth) {
  761. let content = [];
  762. addRange(null, $from, depth, content);
  763. if ($from.depth > depth) {
  764. let type = joinable($from, $to, depth + 1);
  765. addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
  766. }
  767. addRange($to, null, depth, content);
  768. return new Fragment(content);
  769. }
  770. function prepareSliceForReplace(slice, $along) {
  771. let extra = $along.depth - slice.openStart, parent = $along.node(extra);
  772. let node = parent.copy(slice.content);
  773. for (let i = extra - 1; i >= 0; i--)
  774. node = $along.node(i).copy(Fragment.from(node));
  775. return { start: node.resolveNoCache(slice.openStart + extra),
  776. end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };
  777. }
  778. /**
  779. You can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more
  780. information about it. Objects of this class represent such a
  781. resolved position, providing various pieces of context
  782. information, and some helper methods.
  783. Throughout this interface, methods that take an optional `depth`
  784. parameter will interpret undefined as `this.depth` and negative
  785. numbers as `this.depth + value`.
  786. */
  787. class ResolvedPos {
  788. /**
  789. @internal
  790. */
  791. constructor(
  792. /**
  793. The position that was resolved.
  794. */
  795. pos,
  796. /**
  797. @internal
  798. */
  799. path,
  800. /**
  801. The offset this position has into its parent node.
  802. */
  803. parentOffset) {
  804. this.pos = pos;
  805. this.path = path;
  806. this.parentOffset = parentOffset;
  807. this.depth = path.length / 3 - 1;
  808. }
  809. /**
  810. @internal
  811. */
  812. resolveDepth(val) {
  813. if (val == null)
  814. return this.depth;
  815. if (val < 0)
  816. return this.depth + val;
  817. return val;
  818. }
  819. /**
  820. The parent node that the position points into. Note that even if
  821. a position points into a text node, that node is not considered
  822. the parent—text nodes are ‘flat’ in this model, and have no content.
  823. */
  824. get parent() { return this.node(this.depth); }
  825. /**
  826. The root node in which the position was resolved.
  827. */
  828. get doc() { return this.node(0); }
  829. /**
  830. The ancestor node at the given level. `p.node(p.depth)` is the
  831. same as `p.parent`.
  832. */
  833. node(depth) { return this.path[this.resolveDepth(depth) * 3]; }
  834. /**
  835. The index into the ancestor at the given level. If this points
  836. at the 3rd node in the 2nd paragraph on the top level, for
  837. example, `p.index(0)` is 1 and `p.index(1)` is 2.
  838. */
  839. index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }
  840. /**
  841. The index pointing after this position into the ancestor at the
  842. given level.
  843. */
  844. indexAfter(depth) {
  845. depth = this.resolveDepth(depth);
  846. return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
  847. }
  848. /**
  849. The (absolute) position at the start of the node at the given
  850. level.
  851. */
  852. start(depth) {
  853. depth = this.resolveDepth(depth);
  854. return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
  855. }
  856. /**
  857. The (absolute) position at the end of the node at the given
  858. level.
  859. */
  860. end(depth) {
  861. depth = this.resolveDepth(depth);
  862. return this.start(depth) + this.node(depth).content.size;
  863. }
  864. /**
  865. The (absolute) position directly before the wrapping node at the
  866. given level, or, when `depth` is `this.depth + 1`, the original
  867. position.
  868. */
  869. before(depth) {
  870. depth = this.resolveDepth(depth);
  871. if (!depth)
  872. throw new RangeError("There is no position before the top-level node");
  873. return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
  874. }
  875. /**
  876. The (absolute) position directly after the wrapping node at the
  877. given level, or the original position when `depth` is `this.depth + 1`.
  878. */
  879. after(depth) {
  880. depth = this.resolveDepth(depth);
  881. if (!depth)
  882. throw new RangeError("There is no position after the top-level node");
  883. return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
  884. }
  885. /**
  886. When this position points into a text node, this returns the
  887. distance between the position and the start of the text node.
  888. Will be zero for positions that point between nodes.
  889. */
  890. get textOffset() { return this.pos - this.path[this.path.length - 1]; }
  891. /**
  892. Get the node directly after the position, if any. If the position
  893. points into a text node, only the part of that node after the
  894. position is returned.
  895. */
  896. get nodeAfter() {
  897. let parent = this.parent, index = this.index(this.depth);
  898. if (index == parent.childCount)
  899. return null;
  900. let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);
  901. return dOff ? parent.child(index).cut(dOff) : child;
  902. }
  903. /**
  904. Get the node directly before the position, if any. If the
  905. position points into a text node, only the part of that node
  906. before the position is returned.
  907. */
  908. get nodeBefore() {
  909. let index = this.index(this.depth);
  910. let dOff = this.pos - this.path[this.path.length - 1];
  911. if (dOff)
  912. return this.parent.child(index).cut(0, dOff);
  913. return index == 0 ? null : this.parent.child(index - 1);
  914. }
  915. /**
  916. Get the position at the given index in the parent node at the
  917. given depth (which defaults to `this.depth`).
  918. */
  919. posAtIndex(index, depth) {
  920. depth = this.resolveDepth(depth);
  921. let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
  922. for (let i = 0; i < index; i++)
  923. pos += node.child(i).nodeSize;
  924. return pos;
  925. }
  926. /**
  927. Get the marks at this position, factoring in the surrounding
  928. marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
  929. position is at the start of a non-empty node, the marks of the
  930. node after it (if any) are returned.
  931. */
  932. marks() {
  933. let parent = this.parent, index = this.index();
  934. // In an empty parent, return the empty array
  935. if (parent.content.size == 0)
  936. return Mark.none;
  937. // When inside a text node, just return the text node's marks
  938. if (this.textOffset)
  939. return parent.child(index).marks;
  940. let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);
  941. // If the `after` flag is true of there is no node before, make
  942. // the node after this position the main reference.
  943. if (!main) {
  944. let tmp = main;
  945. main = other;
  946. other = tmp;
  947. }
  948. // Use all marks in the main node, except those that have
  949. // `inclusive` set to false and are not present in the other node.
  950. let marks = main.marks;
  951. for (var i = 0; i < marks.length; i++)
  952. if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))
  953. marks = marks[i--].removeFromSet(marks);
  954. return marks;
  955. }
  956. /**
  957. Get the marks after the current position, if any, except those
  958. that are non-inclusive and not present at position `$end`. This
  959. is mostly useful for getting the set of marks to preserve after a
  960. deletion. Will return `null` if this position is at the end of
  961. its parent node or its parent node isn't a textblock (in which
  962. case no marks should be preserved).
  963. */
  964. marksAcross($end) {
  965. let after = this.parent.maybeChild(this.index());
  966. if (!after || !after.isInline)
  967. return null;
  968. let marks = after.marks, next = $end.parent.maybeChild($end.index());
  969. for (var i = 0; i < marks.length; i++)
  970. if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))
  971. marks = marks[i--].removeFromSet(marks);
  972. return marks;
  973. }
  974. /**
  975. The depth up to which this position and the given (non-resolved)
  976. position share the same parent nodes.
  977. */
  978. sharedDepth(pos) {
  979. for (let depth = this.depth; depth > 0; depth--)
  980. if (this.start(depth) <= pos && this.end(depth) >= pos)
  981. return depth;
  982. return 0;
  983. }
  984. /**
  985. Returns a range based on the place where this position and the
  986. given position diverge around block content. If both point into
  987. the same textblock, for example, a range around that textblock
  988. will be returned. If they point into different blocks, the range
  989. around those blocks in their shared ancestor is returned. You can
  990. pass in an optional predicate that will be called with a parent
  991. node to see if a range into that parent is acceptable.
  992. */
  993. blockRange(other = this, pred) {
  994. if (other.pos < this.pos)
  995. return other.blockRange(this);
  996. for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)
  997. if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))
  998. return new NodeRange(this, other, d);
  999. return null;
  1000. }
  1001. /**
  1002. Query whether the given position shares the same parent node.
  1003. */
  1004. sameParent(other) {
  1005. return this.pos - this.parentOffset == other.pos - other.parentOffset;
  1006. }
  1007. /**
  1008. Return the greater of this and the given position.
  1009. */
  1010. max(other) {
  1011. return other.pos > this.pos ? other : this;
  1012. }
  1013. /**
  1014. Return the smaller of this and the given position.
  1015. */
  1016. min(other) {
  1017. return other.pos < this.pos ? other : this;
  1018. }
  1019. /**
  1020. @internal
  1021. */
  1022. toString() {
  1023. let str = "";
  1024. for (let i = 1; i <= this.depth; i++)
  1025. str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
  1026. return str + ":" + this.parentOffset;
  1027. }
  1028. /**
  1029. @internal
  1030. */
  1031. static resolve(doc, pos) {
  1032. if (!(pos >= 0 && pos <= doc.content.size))
  1033. throw new RangeError("Position " + pos + " out of range");
  1034. let path = [];
  1035. let start = 0, parentOffset = pos;
  1036. for (let node = doc;;) {
  1037. let { index, offset } = node.content.findIndex(parentOffset);
  1038. let rem = parentOffset - offset;
  1039. path.push(node, index, start + offset);
  1040. if (!rem)
  1041. break;
  1042. node = node.child(index);
  1043. if (node.isText)
  1044. break;
  1045. parentOffset = rem - 1;
  1046. start += offset + 1;
  1047. }
  1048. return new ResolvedPos(pos, path, parentOffset);
  1049. }
  1050. /**
  1051. @internal
  1052. */
  1053. static resolveCached(doc, pos) {
  1054. for (let i = 0; i < resolveCache.length; i++) {
  1055. let cached = resolveCache[i];
  1056. if (cached.pos == pos && cached.doc == doc)
  1057. return cached;
  1058. }
  1059. let result = resolveCache[resolveCachePos] = ResolvedPos.resolve(doc, pos);
  1060. resolveCachePos = (resolveCachePos + 1) % resolveCacheSize;
  1061. return result;
  1062. }
  1063. }
  1064. let resolveCache = [], resolveCachePos = 0, resolveCacheSize = 12;
  1065. /**
  1066. Represents a flat range of content, i.e. one that starts and
  1067. ends in the same node.
  1068. */
  1069. class NodeRange {
  1070. /**
  1071. Construct a node range. `$from` and `$to` should point into the
  1072. same node until at least the given `depth`, since a node range
  1073. denotes an adjacent set of nodes in a single parent node.
  1074. */
  1075. constructor(
  1076. /**
  1077. A resolved position along the start of the content. May have a
  1078. `depth` greater than this object's `depth` property, since
  1079. these are the positions that were used to compute the range,
  1080. not re-resolved positions directly at its boundaries.
  1081. */
  1082. $from,
  1083. /**
  1084. A position along the end of the content. See
  1085. caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).
  1086. */
  1087. $to,
  1088. /**
  1089. The depth of the node that this range points into.
  1090. */
  1091. depth) {
  1092. this.$from = $from;
  1093. this.$to = $to;
  1094. this.depth = depth;
  1095. }
  1096. /**
  1097. The position at the start of the range.
  1098. */
  1099. get start() { return this.$from.before(this.depth + 1); }
  1100. /**
  1101. The position at the end of the range.
  1102. */
  1103. get end() { return this.$to.after(this.depth + 1); }
  1104. /**
  1105. The parent node that the range points into.
  1106. */
  1107. get parent() { return this.$from.node(this.depth); }
  1108. /**
  1109. The start index of the range in the parent node.
  1110. */
  1111. get startIndex() { return this.$from.index(this.depth); }
  1112. /**
  1113. The end index of the range in the parent node.
  1114. */
  1115. get endIndex() { return this.$to.indexAfter(this.depth); }
  1116. }
  1117. const emptyAttrs = Object.create(null);
  1118. /**
  1119. This class represents a node in the tree that makes up a
  1120. ProseMirror document. So a document is an instance of `Node`, with
  1121. children that are also instances of `Node`.
  1122. Nodes are persistent data structures. Instead of changing them, you
  1123. create new ones with the content you want. Old ones keep pointing
  1124. at the old document shape. This is made cheaper by sharing
  1125. structure between the old and new data as much as possible, which a
  1126. tree shape like this (without back pointers) makes easy.
  1127. **Do not** directly mutate the properties of a `Node` object. See
  1128. [the guide](/docs/guide/#doc) for more information.
  1129. */
  1130. class Node {
  1131. /**
  1132. @internal
  1133. */
  1134. constructor(
  1135. /**
  1136. The type of node that this is.
  1137. */
  1138. type,
  1139. /**
  1140. An object mapping attribute names to values. The kind of
  1141. attributes allowed and required are
  1142. [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.
  1143. */
  1144. attrs,
  1145. // A fragment holding the node's children.
  1146. content,
  1147. /**
  1148. The marks (things like whether it is emphasized or part of a
  1149. link) applied to this node.
  1150. */
  1151. marks = Mark.none) {
  1152. this.type = type;
  1153. this.attrs = attrs;
  1154. this.marks = marks;
  1155. this.content = content || Fragment.empty;
  1156. }
  1157. /**
  1158. The size of this node, as defined by the integer-based [indexing
  1159. scheme](/docs/guide/#doc.indexing). For text nodes, this is the
  1160. amount of characters. For other leaf nodes, it is one. For
  1161. non-leaf nodes, it is the size of the content plus two (the
  1162. start and end token).
  1163. */
  1164. get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }
  1165. /**
  1166. The number of children that the node has.
  1167. */
  1168. get childCount() { return this.content.childCount; }
  1169. /**
  1170. Get the child node at the given index. Raises an error when the
  1171. index is out of range.
  1172. */
  1173. child(index) { return this.content.child(index); }
  1174. /**
  1175. Get the child node at the given index, if it exists.
  1176. */
  1177. maybeChild(index) { return this.content.maybeChild(index); }
  1178. /**
  1179. Call `f` for every child node, passing the node, its offset
  1180. into this parent node, and its index.
  1181. */
  1182. forEach(f) { this.content.forEach(f); }
  1183. /**
  1184. Invoke a callback for all descendant nodes recursively between
  1185. the given two positions that are relative to start of this
  1186. node's content. The callback is invoked with the node, its
  1187. position relative to the original node (method receiver),
  1188. its parent node, and its child index. When the callback returns
  1189. false for a given node, that node's children will not be
  1190. recursed over. The last parameter can be used to specify a
  1191. starting position to count from.
  1192. */
  1193. nodesBetween(from, to, f, startPos = 0) {
  1194. this.content.nodesBetween(from, to, f, startPos, this);
  1195. }
  1196. /**
  1197. Call the given callback for every descendant node. Doesn't
  1198. descend into a node when the callback returns `false`.
  1199. */
  1200. descendants(f) {
  1201. this.nodesBetween(0, this.content.size, f);
  1202. }
  1203. /**
  1204. Concatenates all the text nodes found in this fragment and its
  1205. children.
  1206. */
  1207. get textContent() {
  1208. return (this.isLeaf && this.type.spec.leafText)
  1209. ? this.type.spec.leafText(this)
  1210. : this.textBetween(0, this.content.size, "");
  1211. }
  1212. /**
  1213. Get all text between positions `from` and `to`. When
  1214. `blockSeparator` is given, it will be inserted to separate text
  1215. from different block nodes. If `leafText` is given, it'll be
  1216. inserted for every non-text leaf node encountered, otherwise
  1217. [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec^leafText) will be used.
  1218. */
  1219. textBetween(from, to, blockSeparator, leafText) {
  1220. return this.content.textBetween(from, to, blockSeparator, leafText);
  1221. }
  1222. /**
  1223. Returns this node's first child, or `null` if there are no
  1224. children.
  1225. */
  1226. get firstChild() { return this.content.firstChild; }
  1227. /**
  1228. Returns this node's last child, or `null` if there are no
  1229. children.
  1230. */
  1231. get lastChild() { return this.content.lastChild; }
  1232. /**
  1233. Test whether two nodes represent the same piece of document.
  1234. */
  1235. eq(other) {
  1236. return this == other || (this.sameMarkup(other) && this.content.eq(other.content));
  1237. }
  1238. /**
  1239. Compare the markup (type, attributes, and marks) of this node to
  1240. those of another. Returns `true` if both have the same markup.
  1241. */
  1242. sameMarkup(other) {
  1243. return this.hasMarkup(other.type, other.attrs, other.marks);
  1244. }
  1245. /**
  1246. Check whether this node's markup correspond to the given type,
  1247. attributes, and marks.
  1248. */
  1249. hasMarkup(type, attrs, marks) {
  1250. return this.type == type &&
  1251. compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&
  1252. Mark.sameSet(this.marks, marks || Mark.none);
  1253. }
  1254. /**
  1255. Create a new node with the same markup as this node, containing
  1256. the given content (or empty, if no content is given).
  1257. */
  1258. copy(content = null) {
  1259. if (content == this.content)
  1260. return this;
  1261. return new Node(this.type, this.attrs, content, this.marks);
  1262. }
  1263. /**
  1264. Create a copy of this node, with the given set of marks instead
  1265. of the node's own marks.
  1266. */
  1267. mark(marks) {
  1268. return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);
  1269. }
  1270. /**
  1271. Create a copy of this node with only the content between the
  1272. given positions. If `to` is not given, it defaults to the end of
  1273. the node.
  1274. */
  1275. cut(from, to = this.content.size) {
  1276. if (from == 0 && to == this.content.size)
  1277. return this;
  1278. return this.copy(this.content.cut(from, to));
  1279. }
  1280. /**
  1281. Cut out the part of the document between the given positions, and
  1282. return it as a `Slice` object.
  1283. */
  1284. slice(from, to = this.content.size, includeParents = false) {
  1285. if (from == to)
  1286. return Slice.empty;
  1287. let $from = this.resolve(from), $to = this.resolve(to);
  1288. let depth = includeParents ? 0 : $from.sharedDepth(to);
  1289. let start = $from.start(depth), node = $from.node(depth);
  1290. let content = node.content.cut($from.pos - start, $to.pos - start);
  1291. return new Slice(content, $from.depth - depth, $to.depth - depth);
  1292. }
  1293. /**
  1294. Replace the part of the document between the given positions with
  1295. the given slice. The slice must 'fit', meaning its open sides
  1296. must be able to connect to the surrounding content, and its
  1297. content nodes must be valid children for the node they are placed
  1298. into. If any of this is violated, an error of type
  1299. [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
  1300. */
  1301. replace(from, to, slice) {
  1302. return replace(this.resolve(from), this.resolve(to), slice);
  1303. }
  1304. /**
  1305. Find the node directly after the given position.
  1306. */
  1307. nodeAt(pos) {
  1308. for (let node = this;;) {
  1309. let { index, offset } = node.content.findIndex(pos);
  1310. node = node.maybeChild(index);
  1311. if (!node)
  1312. return null;
  1313. if (offset == pos || node.isText)
  1314. return node;
  1315. pos -= offset + 1;
  1316. }
  1317. }
  1318. /**
  1319. Find the (direct) child node after the given offset, if any,
  1320. and return it along with its index and offset relative to this
  1321. node.
  1322. */
  1323. childAfter(pos) {
  1324. let { index, offset } = this.content.findIndex(pos);
  1325. return { node: this.content.maybeChild(index), index, offset };
  1326. }
  1327. /**
  1328. Find the (direct) child node before the given offset, if any,
  1329. and return it along with its index and offset relative to this
  1330. node.
  1331. */
  1332. childBefore(pos) {
  1333. if (pos == 0)
  1334. return { node: null, index: 0, offset: 0 };
  1335. let { index, offset } = this.content.findIndex(pos);
  1336. if (offset < pos)
  1337. return { node: this.content.child(index), index, offset };
  1338. let node = this.content.child(index - 1);
  1339. return { node, index: index - 1, offset: offset - node.nodeSize };
  1340. }
  1341. /**
  1342. Resolve the given position in the document, returning an
  1343. [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
  1344. */
  1345. resolve(pos) { return ResolvedPos.resolveCached(this, pos); }
  1346. /**
  1347. @internal
  1348. */
  1349. resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }
  1350. /**
  1351. Test whether a given mark or mark type occurs in this document
  1352. between the two given positions.
  1353. */
  1354. rangeHasMark(from, to, type) {
  1355. let found = false;
  1356. if (to > from)
  1357. this.nodesBetween(from, to, node => {
  1358. if (type.isInSet(node.marks))
  1359. found = true;
  1360. return !found;
  1361. });
  1362. return found;
  1363. }
  1364. /**
  1365. True when this is a block (non-inline node)
  1366. */
  1367. get isBlock() { return this.type.isBlock; }
  1368. /**
  1369. True when this is a textblock node, a block node with inline
  1370. content.
  1371. */
  1372. get isTextblock() { return this.type.isTextblock; }
  1373. /**
  1374. True when this node allows inline content.
  1375. */
  1376. get inlineContent() { return this.type.inlineContent; }
  1377. /**
  1378. True when this is an inline node (a text node or a node that can
  1379. appear among text).
  1380. */
  1381. get isInline() { return this.type.isInline; }
  1382. /**
  1383. True when this is a text node.
  1384. */
  1385. get isText() { return this.type.isText; }
  1386. /**
  1387. True when this is a leaf node.
  1388. */
  1389. get isLeaf() { return this.type.isLeaf; }
  1390. /**
  1391. True when this is an atom, i.e. when it does not have directly
  1392. editable content. This is usually the same as `isLeaf`, but can
  1393. be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
  1394. on a node's spec (typically used when the node is displayed as
  1395. an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
  1396. */
  1397. get isAtom() { return this.type.isAtom; }
  1398. /**
  1399. Return a string representation of this node for debugging
  1400. purposes.
  1401. */
  1402. toString() {
  1403. if (this.type.spec.toDebugString)
  1404. return this.type.spec.toDebugString(this);
  1405. let name = this.type.name;
  1406. if (this.content.size)
  1407. name += "(" + this.content.toStringInner() + ")";
  1408. return wrapMarks(this.marks, name);
  1409. }
  1410. /**
  1411. Get the content match in this node at the given index.
  1412. */
  1413. contentMatchAt(index) {
  1414. let match = this.type.contentMatch.matchFragment(this.content, 0, index);
  1415. if (!match)
  1416. throw new Error("Called contentMatchAt on a node with invalid content");
  1417. return match;
  1418. }
  1419. /**
  1420. Test whether replacing the range between `from` and `to` (by
  1421. child index) with the given replacement fragment (which defaults
  1422. to the empty fragment) would leave the node's content valid. You
  1423. can optionally pass `start` and `end` indices into the
  1424. replacement fragment.
  1425. */
  1426. canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
  1427. let one = this.contentMatchAt(from).matchFragment(replacement, start, end);
  1428. let two = one && one.matchFragment(this.content, to);
  1429. if (!two || !two.validEnd)
  1430. return false;
  1431. for (let i = start; i < end; i++)
  1432. if (!this.type.allowsMarks(replacement.child(i).marks))
  1433. return false;
  1434. return true;
  1435. }
  1436. /**
  1437. Test whether replacing the range `from` to `to` (by index) with
  1438. a node of the given type would leave the node's content valid.
  1439. */
  1440. canReplaceWith(from, to, type, marks) {
  1441. if (marks && !this.type.allowsMarks(marks))
  1442. return false;
  1443. let start = this.contentMatchAt(from).matchType(type);
  1444. let end = start && start.matchFragment(this.content, to);
  1445. return end ? end.validEnd : false;
  1446. }
  1447. /**
  1448. Test whether the given node's content could be appended to this
  1449. node. If that node is empty, this will only return true if there
  1450. is at least one node type that can appear in both nodes (to avoid
  1451. merging completely incompatible nodes).
  1452. */
  1453. canAppend(other) {
  1454. if (other.content.size)
  1455. return this.canReplace(this.childCount, this.childCount, other.content);
  1456. else
  1457. return this.type.compatibleContent(other.type);
  1458. }
  1459. /**
  1460. Check whether this node and its descendants conform to the
  1461. schema, and raise error when they do not.
  1462. */
  1463. check() {
  1464. this.type.checkContent(this.content);
  1465. let copy = Mark.none;
  1466. for (let i = 0; i < this.marks.length; i++)
  1467. copy = this.marks[i].addToSet(copy);
  1468. if (!Mark.sameSet(copy, this.marks))
  1469. throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);
  1470. this.content.forEach(node => node.check());
  1471. }
  1472. /**
  1473. Return a JSON-serializeable representation of this node.
  1474. */
  1475. toJSON() {
  1476. let obj = { type: this.type.name };
  1477. for (let _ in this.attrs) {
  1478. obj.attrs = this.attrs;
  1479. break;
  1480. }
  1481. if (this.content.size)
  1482. obj.content = this.content.toJSON();
  1483. if (this.marks.length)
  1484. obj.marks = this.marks.map(n => n.toJSON());
  1485. return obj;
  1486. }
  1487. /**
  1488. Deserialize a node from its JSON representation.
  1489. */
  1490. static fromJSON(schema, json) {
  1491. if (!json)
  1492. throw new RangeError("Invalid input for Node.fromJSON");
  1493. let marks = null;
  1494. if (json.marks) {
  1495. if (!Array.isArray(json.marks))
  1496. throw new RangeError("Invalid mark data for Node.fromJSON");
  1497. marks = json.marks.map(schema.markFromJSON);
  1498. }
  1499. if (json.type == "text") {
  1500. if (typeof json.text != "string")
  1501. throw new RangeError("Invalid text node in JSON");
  1502. return schema.text(json.text, marks);
  1503. }
  1504. let content = Fragment.fromJSON(schema, json.content);
  1505. return schema.nodeType(json.type).create(json.attrs, content, marks);
  1506. }
  1507. }
  1508. Node.prototype.text = undefined;
  1509. class TextNode extends Node {
  1510. /**
  1511. @internal
  1512. */
  1513. constructor(type, attrs, content, marks) {
  1514. super(type, attrs, null, marks);
  1515. if (!content)
  1516. throw new RangeError("Empty text nodes are not allowed");
  1517. this.text = content;
  1518. }
  1519. toString() {
  1520. if (this.type.spec.toDebugString)
  1521. return this.type.spec.toDebugString(this);
  1522. return wrapMarks(this.marks, JSON.stringify(this.text));
  1523. }
  1524. get textContent() { return this.text; }
  1525. textBetween(from, to) { return this.text.slice(from, to); }
  1526. get nodeSize() { return this.text.length; }
  1527. mark(marks) {
  1528. return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);
  1529. }
  1530. withText(text) {
  1531. if (text == this.text)
  1532. return this;
  1533. return new TextNode(this.type, this.attrs, text, this.marks);
  1534. }
  1535. cut(from = 0, to = this.text.length) {
  1536. if (from == 0 && to == this.text.length)
  1537. return this;
  1538. return this.withText(this.text.slice(from, to));
  1539. }
  1540. eq(other) {
  1541. return this.sameMarkup(other) && this.text == other.text;
  1542. }
  1543. toJSON() {
  1544. let base = super.toJSON();
  1545. base.text = this.text;
  1546. return base;
  1547. }
  1548. }
  1549. function wrapMarks(marks, str) {
  1550. for (let i = marks.length - 1; i >= 0; i--)
  1551. str = marks[i].type.name + "(" + str + ")";
  1552. return str;
  1553. }
  1554. /**
  1555. Instances of this class represent a match state of a node type's
  1556. [content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to
  1557. find out whether further content matches here, and whether a given
  1558. position is a valid end of the node.
  1559. */
  1560. class ContentMatch {
  1561. /**
  1562. @internal
  1563. */
  1564. constructor(
  1565. /**
  1566. True when this match state represents a valid end of the node.
  1567. */
  1568. validEnd) {
  1569. this.validEnd = validEnd;
  1570. /**
  1571. @internal
  1572. */
  1573. this.next = [];
  1574. /**
  1575. @internal
  1576. */
  1577. this.wrapCache = [];
  1578. }
  1579. /**
  1580. @internal
  1581. */
  1582. static parse(string, nodeTypes) {
  1583. let stream = new TokenStream(string, nodeTypes);
  1584. if (stream.next == null)
  1585. return ContentMatch.empty;
  1586. let expr = parseExpr(stream);
  1587. if (stream.next)
  1588. stream.err("Unexpected trailing text");
  1589. let match = dfa(nfa(expr));
  1590. checkForDeadEnds(match, stream);
  1591. return match;
  1592. }
  1593. /**
  1594. Match a node type, returning a match after that node if
  1595. successful.
  1596. */
  1597. matchType(type) {
  1598. for (let i = 0; i < this.next.length; i++)
  1599. if (this.next[i].type == type)
  1600. return this.next[i].next;
  1601. return null;
  1602. }
  1603. /**
  1604. Try to match a fragment. Returns the resulting match when
  1605. successful.
  1606. */
  1607. matchFragment(frag, start = 0, end = frag.childCount) {
  1608. let cur = this;
  1609. for (let i = start; cur && i < end; i++)
  1610. cur = cur.matchType(frag.child(i).type);
  1611. return cur;
  1612. }
  1613. /**
  1614. @internal
  1615. */
  1616. get inlineContent() {
  1617. return this.next.length != 0 && this.next[0].type.isInline;
  1618. }
  1619. /**
  1620. Get the first matching node type at this match position that can
  1621. be generated.
  1622. */
  1623. get defaultType() {
  1624. for (let i = 0; i < this.next.length; i++) {
  1625. let { type } = this.next[i];
  1626. if (!(type.isText || type.hasRequiredAttrs()))
  1627. return type;
  1628. }
  1629. return null;
  1630. }
  1631. /**
  1632. @internal
  1633. */
  1634. compatible(other) {
  1635. for (let i = 0; i < this.next.length; i++)
  1636. for (let j = 0; j < other.next.length; j++)
  1637. if (this.next[i].type == other.next[j].type)
  1638. return true;
  1639. return false;
  1640. }
  1641. /**
  1642. Try to match the given fragment, and if that fails, see if it can
  1643. be made to match by inserting nodes in front of it. When
  1644. successful, return a fragment of inserted nodes (which may be
  1645. empty if nothing had to be inserted). When `toEnd` is true, only
  1646. return a fragment if the resulting match goes to the end of the
  1647. content expression.
  1648. */
  1649. fillBefore(after, toEnd = false, startIndex = 0) {
  1650. let seen = [this];
  1651. function search(match, types) {
  1652. let finished = match.matchFragment(after, startIndex);
  1653. if (finished && (!toEnd || finished.validEnd))
  1654. return Fragment.from(types.map(tp => tp.createAndFill()));
  1655. for (let i = 0; i < match.next.length; i++) {
  1656. let { type, next } = match.next[i];
  1657. if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
  1658. seen.push(next);
  1659. let found = search(next, types.concat(type));
  1660. if (found)
  1661. return found;
  1662. }
  1663. }
  1664. return null;
  1665. }
  1666. return search(this, []);
  1667. }
  1668. /**
  1669. Find a set of wrapping node types that would allow a node of the
  1670. given type to appear at this position. The result may be empty
  1671. (when it fits directly) and will be null when no such wrapping
  1672. exists.
  1673. */
  1674. findWrapping(target) {
  1675. for (let i = 0; i < this.wrapCache.length; i += 2)
  1676. if (this.wrapCache[i] == target)
  1677. return this.wrapCache[i + 1];
  1678. let computed = this.computeWrapping(target);
  1679. this.wrapCache.push(target, computed);
  1680. return computed;
  1681. }
  1682. /**
  1683. @internal
  1684. */
  1685. computeWrapping(target) {
  1686. let seen = Object.create(null), active = [{ match: this, type: null, via: null }];
  1687. while (active.length) {
  1688. let current = active.shift(), match = current.match;
  1689. if (match.matchType(target)) {
  1690. let result = [];
  1691. for (let obj = current; obj.type; obj = obj.via)
  1692. result.push(obj.type);
  1693. return result.reverse();
  1694. }
  1695. for (let i = 0; i < match.next.length; i++) {
  1696. let { type, next } = match.next[i];
  1697. if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
  1698. active.push({ match: type.contentMatch, type, via: current });
  1699. seen[type.name] = true;
  1700. }
  1701. }
  1702. }
  1703. return null;
  1704. }
  1705. /**
  1706. The number of outgoing edges this node has in the finite
  1707. automaton that describes the content expression.
  1708. */
  1709. get edgeCount() {
  1710. return this.next.length;
  1711. }
  1712. /**
  1713. Get the _n_​th outgoing edge from this node in the finite
  1714. automaton that describes the content expression.
  1715. */
  1716. edge(n) {
  1717. if (n >= this.next.length)
  1718. throw new RangeError(`There's no ${n}th edge in this content match`);
  1719. return this.next[n];
  1720. }
  1721. /**
  1722. @internal
  1723. */
  1724. toString() {
  1725. let seen = [];
  1726. function scan(m) {
  1727. seen.push(m);
  1728. for (let i = 0; i < m.next.length; i++)
  1729. if (seen.indexOf(m.next[i].next) == -1)
  1730. scan(m.next[i].next);
  1731. }
  1732. scan(this);
  1733. return seen.map((m, i) => {
  1734. let out = i + (m.validEnd ? "*" : " ") + " ";
  1735. for (let i = 0; i < m.next.length; i++)
  1736. out += (i ? ", " : "") + m.next[i].type.name + "->" + seen.indexOf(m.next[i].next);
  1737. return out;
  1738. }).join("\n");
  1739. }
  1740. }
  1741. /**
  1742. @internal
  1743. */
  1744. ContentMatch.empty = new ContentMatch(true);
  1745. class TokenStream {
  1746. constructor(string, nodeTypes) {
  1747. this.string = string;
  1748. this.nodeTypes = nodeTypes;
  1749. this.inline = null;
  1750. this.pos = 0;
  1751. this.tokens = string.split(/\s*(?=\b|\W|$)/);
  1752. if (this.tokens[this.tokens.length - 1] == "")
  1753. this.tokens.pop();
  1754. if (this.tokens[0] == "")
  1755. this.tokens.shift();
  1756. }
  1757. get next() { return this.tokens[this.pos]; }
  1758. eat(tok) { return this.next == tok && (this.pos++ || true); }
  1759. err(str) { throw new SyntaxError(str + " (in content expression '" + this.string + "')"); }
  1760. }
  1761. function parseExpr(stream) {
  1762. let exprs = [];
  1763. do {
  1764. exprs.push(parseExprSeq(stream));
  1765. } while (stream.eat("|"));
  1766. return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
  1767. }
  1768. function parseExprSeq(stream) {
  1769. let exprs = [];
  1770. do {
  1771. exprs.push(parseExprSubscript(stream));
  1772. } while (stream.next && stream.next != ")" && stream.next != "|");
  1773. return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
  1774. }
  1775. function parseExprSubscript(stream) {
  1776. let expr = parseExprAtom(stream);
  1777. for (;;) {
  1778. if (stream.eat("+"))
  1779. expr = { type: "plus", expr };
  1780. else if (stream.eat("*"))
  1781. expr = { type: "star", expr };
  1782. else if (stream.eat("?"))
  1783. expr = { type: "opt", expr };
  1784. else if (stream.eat("{"))
  1785. expr = parseExprRange(stream, expr);
  1786. else
  1787. break;
  1788. }
  1789. return expr;
  1790. }
  1791. function parseNum(stream) {
  1792. if (/\D/.test(stream.next))
  1793. stream.err("Expected number, got '" + stream.next + "'");
  1794. let result = Number(stream.next);
  1795. stream.pos++;
  1796. return result;
  1797. }
  1798. function parseExprRange(stream, expr) {
  1799. let min = parseNum(stream), max = min;
  1800. if (stream.eat(",")) {
  1801. if (stream.next != "}")
  1802. max = parseNum(stream);
  1803. else
  1804. max = -1;
  1805. }
  1806. if (!stream.eat("}"))
  1807. stream.err("Unclosed braced range");
  1808. return { type: "range", min, max, expr };
  1809. }
  1810. function resolveName(stream, name) {
  1811. let types = stream.nodeTypes, type = types[name];
  1812. if (type)
  1813. return [type];
  1814. let result = [];
  1815. for (let typeName in types) {
  1816. let type = types[typeName];
  1817. if (type.groups.indexOf(name) > -1)
  1818. result.push(type);
  1819. }
  1820. if (result.length == 0)
  1821. stream.err("No node type or group '" + name + "' found");
  1822. return result;
  1823. }
  1824. function parseExprAtom(stream) {
  1825. if (stream.eat("(")) {
  1826. let expr = parseExpr(stream);
  1827. if (!stream.eat(")"))
  1828. stream.err("Missing closing paren");
  1829. return expr;
  1830. }
  1831. else if (!/\W/.test(stream.next)) {
  1832. let exprs = resolveName(stream, stream.next).map(type => {
  1833. if (stream.inline == null)
  1834. stream.inline = type.isInline;
  1835. else if (stream.inline != type.isInline)
  1836. stream.err("Mixing inline and block content");
  1837. return { type: "name", value: type };
  1838. });
  1839. stream.pos++;
  1840. return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
  1841. }
  1842. else {
  1843. stream.err("Unexpected token '" + stream.next + "'");
  1844. }
  1845. }
  1846. /**
  1847. Construct an NFA from an expression as returned by the parser. The
  1848. NFA is represented as an array of states, which are themselves
  1849. arrays of edges, which are `{term, to}` objects. The first state is
  1850. the entry state and the last node is the success state.
  1851. Note that unlike typical NFAs, the edge ordering in this one is
  1852. significant, in that it is used to contruct filler content when
  1853. necessary.
  1854. */
  1855. function nfa(expr) {
  1856. let nfa = [[]];
  1857. connect(compile(expr, 0), node());
  1858. return nfa;
  1859. function node() { return nfa.push([]) - 1; }
  1860. function edge(from, to, term) {
  1861. let edge = { term, to };
  1862. nfa[from].push(edge);
  1863. return edge;
  1864. }
  1865. function connect(edges, to) {
  1866. edges.forEach(edge => edge.to = to);
  1867. }
  1868. function compile(expr, from) {
  1869. if (expr.type == "choice") {
  1870. return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);
  1871. }
  1872. else if (expr.type == "seq") {
  1873. for (let i = 0;; i++) {
  1874. let next = compile(expr.exprs[i], from);
  1875. if (i == expr.exprs.length - 1)
  1876. return next;
  1877. connect(next, from = node());
  1878. }
  1879. }
  1880. else if (expr.type == "star") {
  1881. let loop = node();
  1882. edge(from, loop);
  1883. connect(compile(expr.expr, loop), loop);
  1884. return [edge(loop)];
  1885. }
  1886. else if (expr.type == "plus") {
  1887. let loop = node();
  1888. connect(compile(expr.expr, from), loop);
  1889. connect(compile(expr.expr, loop), loop);
  1890. return [edge(loop)];
  1891. }
  1892. else if (expr.type == "opt") {
  1893. return [edge(from)].concat(compile(expr.expr, from));
  1894. }
  1895. else if (expr.type == "range") {
  1896. let cur = from;
  1897. for (let i = 0; i < expr.min; i++) {
  1898. let next = node();
  1899. connect(compile(expr.expr, cur), next);
  1900. cur = next;
  1901. }
  1902. if (expr.max == -1) {
  1903. connect(compile(expr.expr, cur), cur);
  1904. }
  1905. else {
  1906. for (let i = expr.min; i < expr.max; i++) {
  1907. let next = node();
  1908. edge(cur, next);
  1909. connect(compile(expr.expr, cur), next);
  1910. cur = next;
  1911. }
  1912. }
  1913. return [edge(cur)];
  1914. }
  1915. else if (expr.type == "name") {
  1916. return [edge(from, undefined, expr.value)];
  1917. }
  1918. else {
  1919. throw new Error("Unknown expr type");
  1920. }
  1921. }
  1922. }
  1923. function cmp(a, b) { return b - a; }
  1924. // Get the set of nodes reachable by null edges from `node`. Omit
  1925. // nodes with only a single null-out-edge, since they may lead to
  1926. // needless duplicated nodes.
  1927. function nullFrom(nfa, node) {
  1928. let result = [];
  1929. scan(node);
  1930. return result.sort(cmp);
  1931. function scan(node) {
  1932. let edges = nfa[node];
  1933. if (edges.length == 1 && !edges[0].term)
  1934. return scan(edges[0].to);
  1935. result.push(node);
  1936. for (let i = 0; i < edges.length; i++) {
  1937. let { term, to } = edges[i];
  1938. if (!term && result.indexOf(to) == -1)
  1939. scan(to);
  1940. }
  1941. }
  1942. }
  1943. // Compiles an NFA as produced by `nfa` into a DFA, modeled as a set
  1944. // of state objects (`ContentMatch` instances) with transitions
  1945. // between them.
  1946. function dfa(nfa) {
  1947. let labeled = Object.create(null);
  1948. return explore(nullFrom(nfa, 0));
  1949. function explore(states) {
  1950. let out = [];
  1951. states.forEach(node => {
  1952. nfa[node].forEach(({ term, to }) => {
  1953. if (!term)
  1954. return;
  1955. let set;
  1956. for (let i = 0; i < out.length; i++)
  1957. if (out[i][0] == term)
  1958. set = out[i][1];
  1959. nullFrom(nfa, to).forEach(node => {
  1960. if (!set)
  1961. out.push([term, set = []]);
  1962. if (set.indexOf(node) == -1)
  1963. set.push(node);
  1964. });
  1965. });
  1966. });
  1967. let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);
  1968. for (let i = 0; i < out.length; i++) {
  1969. let states = out[i][1].sort(cmp);
  1970. state.next.push({ type: out[i][0], next: labeled[states.join(",")] || explore(states) });
  1971. }
  1972. return state;
  1973. }
  1974. }
  1975. function checkForDeadEnds(match, stream) {
  1976. for (let i = 0, work = [match]; i < work.length; i++) {
  1977. let state = work[i], dead = !state.validEnd, nodes = [];
  1978. for (let j = 0; j < state.next.length; j++) {
  1979. let { type, next } = state.next[j];
  1980. nodes.push(type.name);
  1981. if (dead && !(type.isText || type.hasRequiredAttrs()))
  1982. dead = false;
  1983. if (work.indexOf(next) == -1)
  1984. work.push(next);
  1985. }
  1986. if (dead)
  1987. stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
  1988. }
  1989. }
  1990. // For node types where all attrs have a default value (or which don't
  1991. // have any attributes), build up a single reusable default attribute
  1992. // object, and use it for all nodes that don't specify specific
  1993. // attributes.
  1994. function defaultAttrs(attrs) {
  1995. let defaults = Object.create(null);
  1996. for (let attrName in attrs) {
  1997. let attr = attrs[attrName];
  1998. if (!attr.hasDefault)
  1999. return null;
  2000. defaults[attrName] = attr.default;
  2001. }
  2002. return defaults;
  2003. }
  2004. function computeAttrs(attrs, value) {
  2005. let built = Object.create(null);
  2006. for (let name in attrs) {
  2007. let given = value && value[name];
  2008. if (given === undefined) {
  2009. let attr = attrs[name];
  2010. if (attr.hasDefault)
  2011. given = attr.default;
  2012. else
  2013. throw new RangeError("No value supplied for attribute " + name);
  2014. }
  2015. built[name] = given;
  2016. }
  2017. return built;
  2018. }
  2019. function initAttrs(attrs) {
  2020. let result = Object.create(null);
  2021. if (attrs)
  2022. for (let name in attrs)
  2023. result[name] = new Attribute(attrs[name]);
  2024. return result;
  2025. }
  2026. /**
  2027. Node types are objects allocated once per `Schema` and used to
  2028. [tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information
  2029. about the node type, such as its name and what kind of node it
  2030. represents.
  2031. */
  2032. class NodeType {
  2033. /**
  2034. @internal
  2035. */
  2036. constructor(
  2037. /**
  2038. The name the node type has in this schema.
  2039. */
  2040. name,
  2041. /**
  2042. A link back to the `Schema` the node type belongs to.
  2043. */
  2044. schema,
  2045. /**
  2046. The spec that this type is based on
  2047. */
  2048. spec) {
  2049. this.name = name;
  2050. this.schema = schema;
  2051. this.spec = spec;
  2052. /**
  2053. The set of marks allowed in this node. `null` means all marks
  2054. are allowed.
  2055. */
  2056. this.markSet = null;
  2057. this.groups = spec.group ? spec.group.split(" ") : [];
  2058. this.attrs = initAttrs(spec.attrs);
  2059. this.defaultAttrs = defaultAttrs(this.attrs);
  2060. this.contentMatch = null;
  2061. this.inlineContent = null;
  2062. this.isBlock = !(spec.inline || name == "text");
  2063. this.isText = name == "text";
  2064. }
  2065. /**
  2066. True if this is an inline type.
  2067. */
  2068. get isInline() { return !this.isBlock; }
  2069. /**
  2070. True if this is a textblock type, a block that contains inline
  2071. content.
  2072. */
  2073. get isTextblock() { return this.isBlock && this.inlineContent; }
  2074. /**
  2075. True for node types that allow no content.
  2076. */
  2077. get isLeaf() { return this.contentMatch == ContentMatch.empty; }
  2078. /**
  2079. True when this node is an atom, i.e. when it does not have
  2080. directly editable content.
  2081. */
  2082. get isAtom() { return this.isLeaf || !!this.spec.atom; }
  2083. /**
  2084. The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
  2085. */
  2086. get whitespace() {
  2087. return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
  2088. }
  2089. /**
  2090. Tells you whether this node type has any required attributes.
  2091. */
  2092. hasRequiredAttrs() {
  2093. for (let n in this.attrs)
  2094. if (this.attrs[n].isRequired)
  2095. return true;
  2096. return false;
  2097. }
  2098. /**
  2099. Indicates whether this node allows some of the same content as
  2100. the given node type.
  2101. */
  2102. compatibleContent(other) {
  2103. return this == other || this.contentMatch.compatible(other.contentMatch);
  2104. }
  2105. /**
  2106. @internal
  2107. */
  2108. computeAttrs(attrs) {
  2109. if (!attrs && this.defaultAttrs)
  2110. return this.defaultAttrs;
  2111. else
  2112. return computeAttrs(this.attrs, attrs);
  2113. }
  2114. /**
  2115. Create a `Node` of this type. The given attributes are
  2116. checked and defaulted (you can pass `null` to use the type's
  2117. defaults entirely, if no required attributes exist). `content`
  2118. may be a `Fragment`, a node, an array of nodes, or
  2119. `null`. Similarly `marks` may be `null` to default to the empty
  2120. set of marks.
  2121. */
  2122. create(attrs = null, content, marks) {
  2123. if (this.isText)
  2124. throw new Error("NodeType.create can't construct text nodes");
  2125. return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));
  2126. }
  2127. /**
  2128. Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
  2129. against the node type's content restrictions, and throw an error
  2130. if it doesn't match.
  2131. */
  2132. createChecked(attrs = null, content, marks) {
  2133. content = Fragment.from(content);
  2134. this.checkContent(content);
  2135. return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));
  2136. }
  2137. /**
  2138. Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
  2139. necessary to add nodes to the start or end of the given fragment
  2140. to make it fit the node. If no fitting wrapping can be found,
  2141. return null. Note that, due to the fact that required nodes can
  2142. always be created, this will always succeed if you pass null or
  2143. `Fragment.empty` as content.
  2144. */
  2145. createAndFill(attrs = null, content, marks) {
  2146. attrs = this.computeAttrs(attrs);
  2147. content = Fragment.from(content);
  2148. if (content.size) {
  2149. let before = this.contentMatch.fillBefore(content);
  2150. if (!before)
  2151. return null;
  2152. content = before.append(content);
  2153. }
  2154. let matched = this.contentMatch.matchFragment(content);
  2155. let after = matched && matched.fillBefore(Fragment.empty, true);
  2156. if (!after)
  2157. return null;
  2158. return new Node(this, attrs, content.append(after), Mark.setFrom(marks));
  2159. }
  2160. /**
  2161. Returns true if the given fragment is valid content for this node
  2162. type with the given attributes.
  2163. */
  2164. validContent(content) {
  2165. let result = this.contentMatch.matchFragment(content);
  2166. if (!result || !result.validEnd)
  2167. return false;
  2168. for (let i = 0; i < content.childCount; i++)
  2169. if (!this.allowsMarks(content.child(i).marks))
  2170. return false;
  2171. return true;
  2172. }
  2173. /**
  2174. Throws a RangeError if the given fragment is not valid content for this
  2175. node type.
  2176. @internal
  2177. */
  2178. checkContent(content) {
  2179. if (!this.validContent(content))
  2180. throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
  2181. }
  2182. /**
  2183. Check whether the given mark type is allowed in this node.
  2184. */
  2185. allowsMarkType(markType) {
  2186. return this.markSet == null || this.markSet.indexOf(markType) > -1;
  2187. }
  2188. /**
  2189. Test whether the given set of marks are allowed in this node.
  2190. */
  2191. allowsMarks(marks) {
  2192. if (this.markSet == null)
  2193. return true;
  2194. for (let i = 0; i < marks.length; i++)
  2195. if (!this.allowsMarkType(marks[i].type))
  2196. return false;
  2197. return true;
  2198. }
  2199. /**
  2200. Removes the marks that are not allowed in this node from the given set.
  2201. */
  2202. allowedMarks(marks) {
  2203. if (this.markSet == null)
  2204. return marks;
  2205. let copy;
  2206. for (let i = 0; i < marks.length; i++) {
  2207. if (!this.allowsMarkType(marks[i].type)) {
  2208. if (!copy)
  2209. copy = marks.slice(0, i);
  2210. }
  2211. else if (copy) {
  2212. copy.push(marks[i]);
  2213. }
  2214. }
  2215. return !copy ? marks : copy.length ? copy : Mark.none;
  2216. }
  2217. /**
  2218. @internal
  2219. */
  2220. static compile(nodes, schema) {
  2221. let result = Object.create(null);
  2222. nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));
  2223. let topType = schema.spec.topNode || "doc";
  2224. if (!result[topType])
  2225. throw new RangeError("Schema is missing its top node type ('" + topType + "')");
  2226. if (!result.text)
  2227. throw new RangeError("Every schema needs a 'text' type");
  2228. for (let _ in result.text.attrs)
  2229. throw new RangeError("The text node type should not have attributes");
  2230. return result;
  2231. }
  2232. }
  2233. // Attribute descriptors
  2234. class Attribute {
  2235. constructor(options) {
  2236. this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
  2237. this.default = options.default;
  2238. }
  2239. get isRequired() {
  2240. return !this.hasDefault;
  2241. }
  2242. }
  2243. // Marks
  2244. /**
  2245. Like nodes, marks (which are associated with nodes to signify
  2246. things like emphasis or being part of a link) are
  2247. [tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are
  2248. instantiated once per `Schema`.
  2249. */
  2250. class MarkType {
  2251. /**
  2252. @internal
  2253. */
  2254. constructor(
  2255. /**
  2256. The name of the mark type.
  2257. */
  2258. name,
  2259. /**
  2260. @internal
  2261. */
  2262. rank,
  2263. /**
  2264. The schema that this mark type instance is part of.
  2265. */
  2266. schema,
  2267. /**
  2268. The spec on which the type is based.
  2269. */
  2270. spec) {
  2271. this.name = name;
  2272. this.rank = rank;
  2273. this.schema = schema;
  2274. this.spec = spec;
  2275. this.attrs = initAttrs(spec.attrs);
  2276. this.excluded = null;
  2277. let defaults = defaultAttrs(this.attrs);
  2278. this.instance = defaults ? new Mark(this, defaults) : null;
  2279. }
  2280. /**
  2281. Create a mark of this type. `attrs` may be `null` or an object
  2282. containing only some of the mark's attributes. The others, if
  2283. they have defaults, will be added.
  2284. */
  2285. create(attrs = null) {
  2286. if (!attrs && this.instance)
  2287. return this.instance;
  2288. return new Mark(this, computeAttrs(this.attrs, attrs));
  2289. }
  2290. /**
  2291. @internal
  2292. */
  2293. static compile(marks, schema) {
  2294. let result = Object.create(null), rank = 0;
  2295. marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));
  2296. return result;
  2297. }
  2298. /**
  2299. When there is a mark of this type in the given set, a new set
  2300. without it is returned. Otherwise, the input set is returned.
  2301. */
  2302. removeFromSet(set) {
  2303. for (var i = 0; i < set.length; i++)
  2304. if (set[i].type == this) {
  2305. set = set.slice(0, i).concat(set.slice(i + 1));
  2306. i--;
  2307. }
  2308. return set;
  2309. }
  2310. /**
  2311. Tests whether there is a mark of this type in the given set.
  2312. */
  2313. isInSet(set) {
  2314. for (let i = 0; i < set.length; i++)
  2315. if (set[i].type == this)
  2316. return set[i];
  2317. }
  2318. /**
  2319. Queries whether a given mark type is
  2320. [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
  2321. */
  2322. excludes(other) {
  2323. return this.excluded.indexOf(other) > -1;
  2324. }
  2325. }
  2326. /**
  2327. A document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark
  2328. type](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may
  2329. occur in conforming documents, and provides functionality for
  2330. creating and deserializing such documents.
  2331. When given, the type parameters provide the names of the nodes and
  2332. marks in this schema.
  2333. */
  2334. class Schema {
  2335. /**
  2336. Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
  2337. */
  2338. constructor(spec) {
  2339. /**
  2340. An object for storing whatever values modules may want to
  2341. compute and cache per schema. (If you want to store something
  2342. in it, try to use property names unlikely to clash.)
  2343. */
  2344. this.cached = Object.create(null);
  2345. let instanceSpec = this.spec = {};
  2346. for (let prop in spec)
  2347. instanceSpec[prop] = spec[prop];
  2348. instanceSpec.nodes = OrderedMap.from(spec.nodes),
  2349. instanceSpec.marks = OrderedMap.from(spec.marks || {}),
  2350. this.nodes = NodeType.compile(this.spec.nodes, this);
  2351. this.marks = MarkType.compile(this.spec.marks, this);
  2352. let contentExprCache = Object.create(null);
  2353. for (let prop in this.nodes) {
  2354. if (prop in this.marks)
  2355. throw new RangeError(prop + " can not be both a node and a mark");
  2356. let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
  2357. type.contentMatch = contentExprCache[contentExpr] ||
  2358. (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
  2359. type.inlineContent = type.contentMatch.inlineContent;
  2360. type.markSet = markExpr == "_" ? null :
  2361. markExpr ? gatherMarks(this, markExpr.split(" ")) :
  2362. markExpr == "" || !type.inlineContent ? [] : null;
  2363. }
  2364. for (let prop in this.marks) {
  2365. let type = this.marks[prop], excl = type.spec.excludes;
  2366. type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
  2367. }
  2368. this.nodeFromJSON = this.nodeFromJSON.bind(this);
  2369. this.markFromJSON = this.markFromJSON.bind(this);
  2370. this.topNodeType = this.nodes[this.spec.topNode || "doc"];
  2371. this.cached.wrappings = Object.create(null);
  2372. }
  2373. /**
  2374. Create a node in this schema. The `type` may be a string or a
  2375. `NodeType` instance. Attributes will be extended with defaults,
  2376. `content` may be a `Fragment`, `null`, a `Node`, or an array of
  2377. nodes.
  2378. */
  2379. node(type, attrs = null, content, marks) {
  2380. if (typeof type == "string")
  2381. type = this.nodeType(type);
  2382. else if (!(type instanceof NodeType))
  2383. throw new RangeError("Invalid node type: " + type);
  2384. else if (type.schema != this)
  2385. throw new RangeError("Node type from different schema used (" + type.name + ")");
  2386. return type.createChecked(attrs, content, marks);
  2387. }
  2388. /**
  2389. Create a text node in the schema. Empty text nodes are not
  2390. allowed.
  2391. */
  2392. text(text, marks) {
  2393. let type = this.nodes.text;
  2394. return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));
  2395. }
  2396. /**
  2397. Create a mark with the given type and attributes.
  2398. */
  2399. mark(type, attrs) {
  2400. if (typeof type == "string")
  2401. type = this.marks[type];
  2402. return type.create(attrs);
  2403. }
  2404. /**
  2405. Deserialize a node from its JSON representation. This method is
  2406. bound.
  2407. */
  2408. nodeFromJSON(json) {
  2409. return Node.fromJSON(this, json);
  2410. }
  2411. /**
  2412. Deserialize a mark from its JSON representation. This method is
  2413. bound.
  2414. */
  2415. markFromJSON(json) {
  2416. return Mark.fromJSON(this, json);
  2417. }
  2418. /**
  2419. @internal
  2420. */
  2421. nodeType(name) {
  2422. let found = this.nodes[name];
  2423. if (!found)
  2424. throw new RangeError("Unknown node type: " + name);
  2425. return found;
  2426. }
  2427. }
  2428. function gatherMarks(schema, marks) {
  2429. let found = [];
  2430. for (let i = 0; i < marks.length; i++) {
  2431. let name = marks[i], mark = schema.marks[name], ok = mark;
  2432. if (mark) {
  2433. found.push(mark);
  2434. }
  2435. else {
  2436. for (let prop in schema.marks) {
  2437. let mark = schema.marks[prop];
  2438. if (name == "_" || (mark.spec.group && mark.spec.group.split(" ").indexOf(name) > -1))
  2439. found.push(ok = mark);
  2440. }
  2441. }
  2442. if (!ok)
  2443. throw new SyntaxError("Unknown mark type: '" + marks[i] + "'");
  2444. }
  2445. return found;
  2446. }
  2447. /**
  2448. A DOM parser represents a strategy for parsing DOM content into a
  2449. ProseMirror document conforming to a given schema. Its behavior is
  2450. defined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).
  2451. */
  2452. class DOMParser {
  2453. /**
  2454. Create a parser that targets the given schema, using the given
  2455. parsing rules.
  2456. */
  2457. constructor(
  2458. /**
  2459. The schema into which the parser parses.
  2460. */
  2461. schema,
  2462. /**
  2463. The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser
  2464. uses, in order of precedence.
  2465. */
  2466. rules) {
  2467. this.schema = schema;
  2468. this.rules = rules;
  2469. /**
  2470. @internal
  2471. */
  2472. this.tags = [];
  2473. /**
  2474. @internal
  2475. */
  2476. this.styles = [];
  2477. rules.forEach(rule => {
  2478. if (rule.tag)
  2479. this.tags.push(rule);
  2480. else if (rule.style)
  2481. this.styles.push(rule);
  2482. });
  2483. // Only normalize list elements when lists in the schema can't directly contain themselves
  2484. this.normalizeLists = !this.tags.some(r => {
  2485. if (!/^(ul|ol)\b/.test(r.tag) || !r.node)
  2486. return false;
  2487. let node = schema.nodes[r.node];
  2488. return node.contentMatch.matchType(node);
  2489. });
  2490. }
  2491. /**
  2492. Parse a document from the content of a DOM node.
  2493. */
  2494. parse(dom, options = {}) {
  2495. let context = new ParseContext(this, options, false);
  2496. context.addAll(dom, options.from, options.to);
  2497. return context.finish();
  2498. }
  2499. /**
  2500. Parses the content of the given DOM node, like
  2501. [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of
  2502. options. But unlike that method, which produces a whole node,
  2503. this one returns a slice that is open at the sides, meaning that
  2504. the schema constraints aren't applied to the start of nodes to
  2505. the left of the input and the end of nodes at the end.
  2506. */
  2507. parseSlice(dom, options = {}) {
  2508. let context = new ParseContext(this, options, true);
  2509. context.addAll(dom, options.from, options.to);
  2510. return Slice.maxOpen(context.finish());
  2511. }
  2512. /**
  2513. @internal
  2514. */
  2515. matchTag(dom, context, after) {
  2516. for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {
  2517. let rule = this.tags[i];
  2518. if (matches(dom, rule.tag) &&
  2519. (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&
  2520. (!rule.context || context.matchesContext(rule.context))) {
  2521. if (rule.getAttrs) {
  2522. let result = rule.getAttrs(dom);
  2523. if (result === false)
  2524. continue;
  2525. rule.attrs = result || undefined;
  2526. }
  2527. return rule;
  2528. }
  2529. }
  2530. }
  2531. /**
  2532. @internal
  2533. */
  2534. matchStyle(prop, value, context, after) {
  2535. for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {
  2536. let rule = this.styles[i], style = rule.style;
  2537. if (style.indexOf(prop) != 0 ||
  2538. rule.context && !context.matchesContext(rule.context) ||
  2539. // Test that the style string either precisely matches the prop,
  2540. // or has an '=' sign after the prop, followed by the given
  2541. // value.
  2542. style.length > prop.length &&
  2543. (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))
  2544. continue;
  2545. if (rule.getAttrs) {
  2546. let result = rule.getAttrs(value);
  2547. if (result === false)
  2548. continue;
  2549. rule.attrs = result || undefined;
  2550. }
  2551. return rule;
  2552. }
  2553. }
  2554. /**
  2555. @internal
  2556. */
  2557. static schemaRules(schema) {
  2558. let result = [];
  2559. function insert(rule) {
  2560. let priority = rule.priority == null ? 50 : rule.priority, i = 0;
  2561. for (; i < result.length; i++) {
  2562. let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;
  2563. if (nextPriority < priority)
  2564. break;
  2565. }
  2566. result.splice(i, 0, rule);
  2567. }
  2568. for (let name in schema.marks) {
  2569. let rules = schema.marks[name].spec.parseDOM;
  2570. if (rules)
  2571. rules.forEach(rule => {
  2572. insert(rule = copy(rule));
  2573. if (!(rule.mark || rule.ignore || rule.clearMark))
  2574. rule.mark = name;
  2575. });
  2576. }
  2577. for (let name in schema.nodes) {
  2578. let rules = schema.nodes[name].spec.parseDOM;
  2579. if (rules)
  2580. rules.forEach(rule => {
  2581. insert(rule = copy(rule));
  2582. if (!(rule.node || rule.ignore || rule.mark))
  2583. rule.node = name;
  2584. });
  2585. }
  2586. return result;
  2587. }
  2588. /**
  2589. Construct a DOM parser using the parsing rules listed in a
  2590. schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by
  2591. [priority](https://prosemirror.net/docs/ref/#model.ParseRule.priority).
  2592. */
  2593. static fromSchema(schema) {
  2594. return schema.cached.domParser ||
  2595. (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));
  2596. }
  2597. }
  2598. const blockTags = {
  2599. address: true, article: true, aside: true, blockquote: true, canvas: true,
  2600. dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,
  2601. footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,
  2602. h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,
  2603. output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true
  2604. };
  2605. const ignoreTags = {
  2606. head: true, noscript: true, object: true, script: true, style: true, title: true
  2607. };
  2608. const listTags = { ol: true, ul: true };
  2609. // Using a bitfield for node context options
  2610. const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;
  2611. function wsOptionsFor(type, preserveWhitespace, base) {
  2612. if (preserveWhitespace != null)
  2613. return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |
  2614. (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
  2615. return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;
  2616. }
  2617. class NodeContext {
  2618. constructor(type, attrs,
  2619. // Marks applied to this node itself
  2620. marks,
  2621. // Marks that can't apply here, but will be used in children if possible
  2622. pendingMarks, solid, match, options) {
  2623. this.type = type;
  2624. this.attrs = attrs;
  2625. this.marks = marks;
  2626. this.pendingMarks = pendingMarks;
  2627. this.solid = solid;
  2628. this.options = options;
  2629. this.content = [];
  2630. // Marks applied to the node's children
  2631. this.activeMarks = Mark.none;
  2632. // Nested Marks with same type
  2633. this.stashMarks = [];
  2634. this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);
  2635. }
  2636. findWrapping(node) {
  2637. if (!this.match) {
  2638. if (!this.type)
  2639. return [];
  2640. let fill = this.type.contentMatch.fillBefore(Fragment.from(node));
  2641. if (fill) {
  2642. this.match = this.type.contentMatch.matchFragment(fill);
  2643. }
  2644. else {
  2645. let start = this.type.contentMatch, wrap;
  2646. if (wrap = start.findWrapping(node.type)) {
  2647. this.match = start;
  2648. return wrap;
  2649. }
  2650. else {
  2651. return null;
  2652. }
  2653. }
  2654. }
  2655. return this.match.findWrapping(node.type);
  2656. }
  2657. finish(openEnd) {
  2658. if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace
  2659. let last = this.content[this.content.length - 1], m;
  2660. if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) {
  2661. let text = last;
  2662. if (last.text.length == m[0].length)
  2663. this.content.pop();
  2664. else
  2665. this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));
  2666. }
  2667. }
  2668. let content = Fragment.from(this.content);
  2669. if (!openEnd && this.match)
  2670. content = content.append(this.match.fillBefore(Fragment.empty, true));
  2671. return this.type ? this.type.create(this.attrs, content, this.marks) : content;
  2672. }
  2673. popFromStashMark(mark) {
  2674. for (let i = this.stashMarks.length - 1; i >= 0; i--)
  2675. if (mark.eq(this.stashMarks[i]))
  2676. return this.stashMarks.splice(i, 1)[0];
  2677. }
  2678. applyPending(nextType) {
  2679. for (let i = 0, pending = this.pendingMarks; i < pending.length; i++) {
  2680. let mark = pending[i];
  2681. if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) &&
  2682. !mark.isInSet(this.activeMarks)) {
  2683. this.activeMarks = mark.addToSet(this.activeMarks);
  2684. this.pendingMarks = mark.removeFromSet(this.pendingMarks);
  2685. }
  2686. }
  2687. }
  2688. inlineContext(node) {
  2689. if (this.type)
  2690. return this.type.inlineContent;
  2691. if (this.content.length)
  2692. return this.content[0].isInline;
  2693. return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());
  2694. }
  2695. }
  2696. class ParseContext {
  2697. constructor(
  2698. // The parser we are using.
  2699. parser,
  2700. // The options passed to this parse.
  2701. options, isOpen) {
  2702. this.parser = parser;
  2703. this.options = options;
  2704. this.isOpen = isOpen;
  2705. this.open = 0;
  2706. let topNode = options.topNode, topContext;
  2707. let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
  2708. if (topNode)
  2709. topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);
  2710. else if (isOpen)
  2711. topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions);
  2712. else
  2713. topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions);
  2714. this.nodes = [topContext];
  2715. this.find = options.findPositions;
  2716. this.needsBlock = false;
  2717. }
  2718. get top() {
  2719. return this.nodes[this.open];
  2720. }
  2721. // Add a DOM node to the content. Text is inserted as text node,
  2722. // otherwise, the node is passed to `addElement` or, if it has a
  2723. // `style` attribute, `addElementWithStyles`.
  2724. addDOM(dom) {
  2725. if (dom.nodeType == 3)
  2726. this.addTextNode(dom);
  2727. else if (dom.nodeType == 1)
  2728. this.addElement(dom);
  2729. }
  2730. withStyleRules(dom, f) {
  2731. let style = dom.getAttribute("style");
  2732. if (!style)
  2733. return f();
  2734. let marks = this.readStyles(parseStyles(style));
  2735. if (!marks)
  2736. return; // A style with ignore: true
  2737. let [addMarks, removeMarks] = marks, top = this.top;
  2738. for (let i = 0; i < removeMarks.length; i++)
  2739. this.removePendingMark(removeMarks[i], top);
  2740. for (let i = 0; i < addMarks.length; i++)
  2741. this.addPendingMark(addMarks[i]);
  2742. f();
  2743. for (let i = 0; i < addMarks.length; i++)
  2744. this.removePendingMark(addMarks[i], top);
  2745. for (let i = 0; i < removeMarks.length; i++)
  2746. this.addPendingMark(removeMarks[i]);
  2747. }
  2748. addTextNode(dom) {
  2749. let value = dom.nodeValue;
  2750. let top = this.top;
  2751. if (top.options & OPT_PRESERVE_WS_FULL ||
  2752. top.inlineContext(dom) ||
  2753. /[^ \t\r\n\u000c]/.test(value)) {
  2754. if (!(top.options & OPT_PRESERVE_WS)) {
  2755. value = value.replace(/[ \t\r\n\u000c]+/g, " ");
  2756. // If this starts with whitespace, and there is no node before it, or
  2757. // a hard break, or a text node that ends with whitespace, strip the
  2758. // leading space.
  2759. if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
  2760. let nodeBefore = top.content[top.content.length - 1];
  2761. let domNodeBefore = dom.previousSibling;
  2762. if (!nodeBefore ||
  2763. (domNodeBefore && domNodeBefore.nodeName == 'BR') ||
  2764. (nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)))
  2765. value = value.slice(1);
  2766. }
  2767. }
  2768. else if (!(top.options & OPT_PRESERVE_WS_FULL)) {
  2769. value = value.replace(/\r?\n|\r/g, " ");
  2770. }
  2771. else {
  2772. value = value.replace(/\r\n?/g, "\n");
  2773. }
  2774. if (value)
  2775. this.insertNode(this.parser.schema.text(value));
  2776. this.findInText(dom);
  2777. }
  2778. else {
  2779. this.findInside(dom);
  2780. }
  2781. }
  2782. // Try to find a handler for the given tag and use that to parse. If
  2783. // none is found, the element's content nodes are added directly.
  2784. addElement(dom, matchAfter) {
  2785. let name = dom.nodeName.toLowerCase(), ruleID;
  2786. if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)
  2787. normalizeList(dom);
  2788. let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||
  2789. (ruleID = this.parser.matchTag(dom, this, matchAfter));
  2790. if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {
  2791. this.findInside(dom);
  2792. this.ignoreFallback(dom);
  2793. }
  2794. else if (!rule || rule.skip || rule.closeParent) {
  2795. if (rule && rule.closeParent)
  2796. this.open = Math.max(0, this.open - 1);
  2797. else if (rule && rule.skip.nodeType)
  2798. dom = rule.skip;
  2799. let sync, top = this.top, oldNeedsBlock = this.needsBlock;
  2800. if (blockTags.hasOwnProperty(name)) {
  2801. if (top.content.length && top.content[0].isInline && this.open) {
  2802. this.open--;
  2803. top = this.top;
  2804. }
  2805. sync = true;
  2806. if (!top.type)
  2807. this.needsBlock = true;
  2808. }
  2809. else if (!dom.firstChild) {
  2810. this.leafFallback(dom);
  2811. return;
  2812. }
  2813. if (rule && rule.skip)
  2814. this.addAll(dom);
  2815. else
  2816. this.withStyleRules(dom, () => this.addAll(dom));
  2817. if (sync)
  2818. this.sync(top);
  2819. this.needsBlock = oldNeedsBlock;
  2820. }
  2821. else {
  2822. this.withStyleRules(dom, () => {
  2823. this.addElementByRule(dom, rule, rule.consuming === false ? ruleID : undefined);
  2824. });
  2825. }
  2826. }
  2827. // Called for leaf DOM nodes that would otherwise be ignored
  2828. leafFallback(dom) {
  2829. if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
  2830. this.addTextNode(dom.ownerDocument.createTextNode("\n"));
  2831. }
  2832. // Called for ignored nodes
  2833. ignoreFallback(dom) {
  2834. // Ignored BR nodes should at least create an inline context
  2835. if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
  2836. this.findPlace(this.parser.schema.text("-"));
  2837. }
  2838. // Run any style parser associated with the node's styles. Either
  2839. // return an array of marks, or null to indicate some of the styles
  2840. // had a rule with `ignore` set.
  2841. readStyles(styles) {
  2842. let add = Mark.none, remove = Mark.none;
  2843. for (let i = 0; i < styles.length; i += 2) {
  2844. for (let after = undefined;;) {
  2845. let rule = this.parser.matchStyle(styles[i], styles[i + 1], this, after);
  2846. if (!rule)
  2847. break;
  2848. if (rule.ignore)
  2849. return null;
  2850. if (rule.clearMark) {
  2851. this.top.pendingMarks.concat(this.top.activeMarks).forEach(m => {
  2852. if (rule.clearMark(m))
  2853. remove = m.addToSet(remove);
  2854. });
  2855. }
  2856. else {
  2857. add = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(add);
  2858. }
  2859. if (rule.consuming === false)
  2860. after = rule;
  2861. else
  2862. break;
  2863. }
  2864. }
  2865. return [add, remove];
  2866. }
  2867. // Look up a handler for the given node. If none are found, return
  2868. // false. Otherwise, apply it, use its return value to drive the way
  2869. // the node's content is wrapped, and return true.
  2870. addElementByRule(dom, rule, continueAfter) {
  2871. let sync, nodeType, mark;
  2872. if (rule.node) {
  2873. nodeType = this.parser.schema.nodes[rule.node];
  2874. if (!nodeType.isLeaf) {
  2875. sync = this.enter(nodeType, rule.attrs || null, rule.preserveWhitespace);
  2876. }
  2877. else if (!this.insertNode(nodeType.create(rule.attrs))) {
  2878. this.leafFallback(dom);
  2879. }
  2880. }
  2881. else {
  2882. let markType = this.parser.schema.marks[rule.mark];
  2883. mark = markType.create(rule.attrs);
  2884. this.addPendingMark(mark);
  2885. }
  2886. let startIn = this.top;
  2887. if (nodeType && nodeType.isLeaf) {
  2888. this.findInside(dom);
  2889. }
  2890. else if (continueAfter) {
  2891. this.addElement(dom, continueAfter);
  2892. }
  2893. else if (rule.getContent) {
  2894. this.findInside(dom);
  2895. rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node));
  2896. }
  2897. else {
  2898. let contentDOM = dom;
  2899. if (typeof rule.contentElement == "string")
  2900. contentDOM = dom.querySelector(rule.contentElement);
  2901. else if (typeof rule.contentElement == "function")
  2902. contentDOM = rule.contentElement(dom);
  2903. else if (rule.contentElement)
  2904. contentDOM = rule.contentElement;
  2905. this.findAround(dom, contentDOM, true);
  2906. this.addAll(contentDOM);
  2907. }
  2908. if (sync && this.sync(startIn))
  2909. this.open--;
  2910. if (mark)
  2911. this.removePendingMark(mark, startIn);
  2912. }
  2913. // Add all child nodes between `startIndex` and `endIndex` (or the
  2914. // whole node, if not given). If `sync` is passed, use it to
  2915. // synchronize after every block element.
  2916. addAll(parent, startIndex, endIndex) {
  2917. let index = startIndex || 0;
  2918. for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {
  2919. this.findAtPoint(parent, index);
  2920. this.addDOM(dom);
  2921. }
  2922. this.findAtPoint(parent, index);
  2923. }
  2924. // Try to find a way to fit the given node type into the current
  2925. // context. May add intermediate wrappers and/or leave non-solid
  2926. // nodes that we're in.
  2927. findPlace(node) {
  2928. let route, sync;
  2929. for (let depth = this.open; depth >= 0; depth--) {
  2930. let cx = this.nodes[depth];
  2931. let found = cx.findWrapping(node);
  2932. if (found && (!route || route.length > found.length)) {
  2933. route = found;
  2934. sync = cx;
  2935. if (!found.length)
  2936. break;
  2937. }
  2938. if (cx.solid)
  2939. break;
  2940. }
  2941. if (!route)
  2942. return false;
  2943. this.sync(sync);
  2944. for (let i = 0; i < route.length; i++)
  2945. this.enterInner(route[i], null, false);
  2946. return true;
  2947. }
  2948. // Try to insert the given node, adjusting the context when needed.
  2949. insertNode(node) {
  2950. if (node.isInline && this.needsBlock && !this.top.type) {
  2951. let block = this.textblockFromContext();
  2952. if (block)
  2953. this.enterInner(block);
  2954. }
  2955. if (this.findPlace(node)) {
  2956. this.closeExtra();
  2957. let top = this.top;
  2958. top.applyPending(node.type);
  2959. if (top.match)
  2960. top.match = top.match.matchType(node.type);
  2961. let marks = top.activeMarks;
  2962. for (let i = 0; i < node.marks.length; i++)
  2963. if (!top.type || top.type.allowsMarkType(node.marks[i].type))
  2964. marks = node.marks[i].addToSet(marks);
  2965. top.content.push(node.mark(marks));
  2966. return true;
  2967. }
  2968. return false;
  2969. }
  2970. // Try to start a node of the given type, adjusting the context when
  2971. // necessary.
  2972. enter(type, attrs, preserveWS) {
  2973. let ok = this.findPlace(type.create(attrs));
  2974. if (ok)
  2975. this.enterInner(type, attrs, true, preserveWS);
  2976. return ok;
  2977. }
  2978. // Open a node of the given type
  2979. enterInner(type, attrs = null, solid = false, preserveWS) {
  2980. this.closeExtra();
  2981. let top = this.top;
  2982. top.applyPending(type);
  2983. top.match = top.match && top.match.matchType(type);
  2984. let options = wsOptionsFor(type, preserveWS, top.options);
  2985. if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)
  2986. options |= OPT_OPEN_LEFT;
  2987. this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options));
  2988. this.open++;
  2989. }
  2990. // Make sure all nodes above this.open are finished and added to
  2991. // their parents
  2992. closeExtra(openEnd = false) {
  2993. let i = this.nodes.length - 1;
  2994. if (i > this.open) {
  2995. for (; i > this.open; i--)
  2996. this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));
  2997. this.nodes.length = this.open + 1;
  2998. }
  2999. }
  3000. finish() {
  3001. this.open = 0;
  3002. this.closeExtra(this.isOpen);
  3003. return this.nodes[0].finish(this.isOpen || this.options.topOpen);
  3004. }
  3005. sync(to) {
  3006. for (let i = this.open; i >= 0; i--)
  3007. if (this.nodes[i] == to) {
  3008. this.open = i;
  3009. return true;
  3010. }
  3011. return false;
  3012. }
  3013. get currentPos() {
  3014. this.closeExtra();
  3015. let pos = 0;
  3016. for (let i = this.open; i >= 0; i--) {
  3017. let content = this.nodes[i].content;
  3018. for (let j = content.length - 1; j >= 0; j--)
  3019. pos += content[j].nodeSize;
  3020. if (i)
  3021. pos++;
  3022. }
  3023. return pos;
  3024. }
  3025. findAtPoint(parent, offset) {
  3026. if (this.find)
  3027. for (let i = 0; i < this.find.length; i++) {
  3028. if (this.find[i].node == parent && this.find[i].offset == offset)
  3029. this.find[i].pos = this.currentPos;
  3030. }
  3031. }
  3032. findInside(parent) {
  3033. if (this.find)
  3034. for (let i = 0; i < this.find.length; i++) {
  3035. if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))
  3036. this.find[i].pos = this.currentPos;
  3037. }
  3038. }
  3039. findAround(parent, content, before) {
  3040. if (parent != content && this.find)
  3041. for (let i = 0; i < this.find.length; i++) {
  3042. if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {
  3043. let pos = content.compareDocumentPosition(this.find[i].node);
  3044. if (pos & (before ? 2 : 4))
  3045. this.find[i].pos = this.currentPos;
  3046. }
  3047. }
  3048. }
  3049. findInText(textNode) {
  3050. if (this.find)
  3051. for (let i = 0; i < this.find.length; i++) {
  3052. if (this.find[i].node == textNode)
  3053. this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);
  3054. }
  3055. }
  3056. // Determines whether the given context string matches this context.
  3057. matchesContext(context) {
  3058. if (context.indexOf("|") > -1)
  3059. return context.split(/\s*\|\s*/).some(this.matchesContext, this);
  3060. let parts = context.split("/");
  3061. let option = this.options.context;
  3062. let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
  3063. let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);
  3064. let match = (i, depth) => {
  3065. for (; i >= 0; i--) {
  3066. let part = parts[i];
  3067. if (part == "") {
  3068. if (i == parts.length - 1 || i == 0)
  3069. continue;
  3070. for (; depth >= minDepth; depth--)
  3071. if (match(i - 1, depth))
  3072. return true;
  3073. return false;
  3074. }
  3075. else {
  3076. let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type
  3077. : option && depth >= minDepth ? option.node(depth - minDepth).type
  3078. : null;
  3079. if (!next || (next.name != part && next.groups.indexOf(part) == -1))
  3080. return false;
  3081. depth--;
  3082. }
  3083. }
  3084. return true;
  3085. };
  3086. return match(parts.length - 1, this.open);
  3087. }
  3088. textblockFromContext() {
  3089. let $context = this.options.context;
  3090. if ($context)
  3091. for (let d = $context.depth; d >= 0; d--) {
  3092. let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;
  3093. if (deflt && deflt.isTextblock && deflt.defaultAttrs)
  3094. return deflt;
  3095. }
  3096. for (let name in this.parser.schema.nodes) {
  3097. let type = this.parser.schema.nodes[name];
  3098. if (type.isTextblock && type.defaultAttrs)
  3099. return type;
  3100. }
  3101. }
  3102. addPendingMark(mark) {
  3103. let found = findSameMarkInSet(mark, this.top.pendingMarks);
  3104. if (found)
  3105. this.top.stashMarks.push(found);
  3106. this.top.pendingMarks = mark.addToSet(this.top.pendingMarks);
  3107. }
  3108. removePendingMark(mark, upto) {
  3109. for (let depth = this.open; depth >= 0; depth--) {
  3110. let level = this.nodes[depth];
  3111. let found = level.pendingMarks.lastIndexOf(mark);
  3112. if (found > -1) {
  3113. level.pendingMarks = mark.removeFromSet(level.pendingMarks);
  3114. }
  3115. else {
  3116. level.activeMarks = mark.removeFromSet(level.activeMarks);
  3117. let stashMark = level.popFromStashMark(mark);
  3118. if (stashMark && level.type && level.type.allowsMarkType(stashMark.type))
  3119. level.activeMarks = stashMark.addToSet(level.activeMarks);
  3120. }
  3121. if (level == upto)
  3122. break;
  3123. }
  3124. }
  3125. }
  3126. // Kludge to work around directly nested list nodes produced by some
  3127. // tools and allowed by browsers to mean that the nested list is
  3128. // actually part of the list item above it.
  3129. function normalizeList(dom) {
  3130. for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
  3131. let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;
  3132. if (name && listTags.hasOwnProperty(name) && prevItem) {
  3133. prevItem.appendChild(child);
  3134. child = prevItem;
  3135. }
  3136. else if (name == "li") {
  3137. prevItem = child;
  3138. }
  3139. else if (name) {
  3140. prevItem = null;
  3141. }
  3142. }
  3143. }
  3144. // Apply a CSS selector.
  3145. function matches(dom, selector) {
  3146. return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
  3147. }
  3148. // Tokenize a style attribute into property/value pairs.
  3149. function parseStyles(style) {
  3150. let re = /\s*([\w-]+)\s*:\s*([^;]+)/g, m, result = [];
  3151. while (m = re.exec(style))
  3152. result.push(m[1], m[2].trim());
  3153. return result;
  3154. }
  3155. function copy(obj) {
  3156. let copy = {};
  3157. for (let prop in obj)
  3158. copy[prop] = obj[prop];
  3159. return copy;
  3160. }
  3161. // Used when finding a mark at the top level of a fragment parse.
  3162. // Checks whether it would be reasonable to apply a given mark type to
  3163. // a given node, by looking at the way the mark occurs in the schema.
  3164. function markMayApply(markType, nodeType) {
  3165. let nodes = nodeType.schema.nodes;
  3166. for (let name in nodes) {
  3167. let parent = nodes[name];
  3168. if (!parent.allowsMarkType(markType))
  3169. continue;
  3170. let seen = [], scan = (match) => {
  3171. seen.push(match);
  3172. for (let i = 0; i < match.edgeCount; i++) {
  3173. let { type, next } = match.edge(i);
  3174. if (type == nodeType)
  3175. return true;
  3176. if (seen.indexOf(next) < 0 && scan(next))
  3177. return true;
  3178. }
  3179. };
  3180. if (scan(parent.contentMatch))
  3181. return true;
  3182. }
  3183. }
  3184. function findSameMarkInSet(mark, set) {
  3185. for (let i = 0; i < set.length; i++) {
  3186. if (mark.eq(set[i]))
  3187. return set[i];
  3188. }
  3189. }
  3190. /**
  3191. A DOM serializer knows how to convert ProseMirror nodes and
  3192. marks of various types to DOM nodes.
  3193. */
  3194. class DOMSerializer {
  3195. /**
  3196. Create a serializer. `nodes` should map node names to functions
  3197. that take a node and return a description of the corresponding
  3198. DOM. `marks` does the same for mark names, but also gets an
  3199. argument that tells it whether the mark's content is block or
  3200. inline content (for typical use, it'll always be inline). A mark
  3201. serializer may be `null` to indicate that marks of that type
  3202. should not be serialized.
  3203. */
  3204. constructor(
  3205. /**
  3206. The node serialization functions.
  3207. */
  3208. nodes,
  3209. /**
  3210. The mark serialization functions.
  3211. */
  3212. marks) {
  3213. this.nodes = nodes;
  3214. this.marks = marks;
  3215. }
  3216. /**
  3217. Serialize the content of this fragment to a DOM fragment. When
  3218. not in the browser, the `document` option, containing a DOM
  3219. document, should be passed so that the serializer can create
  3220. nodes.
  3221. */
  3222. serializeFragment(fragment, options = {}, target) {
  3223. if (!target)
  3224. target = doc(options).createDocumentFragment();
  3225. let top = target, active = [];
  3226. fragment.forEach(node => {
  3227. if (active.length || node.marks.length) {
  3228. let keep = 0, rendered = 0;
  3229. while (keep < active.length && rendered < node.marks.length) {
  3230. let next = node.marks[rendered];
  3231. if (!this.marks[next.type.name]) {
  3232. rendered++;
  3233. continue;
  3234. }
  3235. if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)
  3236. break;
  3237. keep++;
  3238. rendered++;
  3239. }
  3240. while (keep < active.length)
  3241. top = active.pop()[1];
  3242. while (rendered < node.marks.length) {
  3243. let add = node.marks[rendered++];
  3244. let markDOM = this.serializeMark(add, node.isInline, options);
  3245. if (markDOM) {
  3246. active.push([add, top]);
  3247. top.appendChild(markDOM.dom);
  3248. top = markDOM.contentDOM || markDOM.dom;
  3249. }
  3250. }
  3251. }
  3252. top.appendChild(this.serializeNodeInner(node, options));
  3253. });
  3254. return target;
  3255. }
  3256. /**
  3257. @internal
  3258. */
  3259. serializeNodeInner(node, options) {
  3260. let { dom, contentDOM } = DOMSerializer.renderSpec(doc(options), this.nodes[node.type.name](node));
  3261. if (contentDOM) {
  3262. if (node.isLeaf)
  3263. throw new RangeError("Content hole not allowed in a leaf node spec");
  3264. this.serializeFragment(node.content, options, contentDOM);
  3265. }
  3266. return dom;
  3267. }
  3268. /**
  3269. Serialize this node to a DOM node. This can be useful when you
  3270. need to serialize a part of a document, as opposed to the whole
  3271. document. To serialize a whole document, use
  3272. [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
  3273. its [content](https://prosemirror.net/docs/ref/#model.Node.content).
  3274. */
  3275. serializeNode(node, options = {}) {
  3276. let dom = this.serializeNodeInner(node, options);
  3277. for (let i = node.marks.length - 1; i >= 0; i--) {
  3278. let wrap = this.serializeMark(node.marks[i], node.isInline, options);
  3279. if (wrap) {
  3280. (wrap.contentDOM || wrap.dom).appendChild(dom);
  3281. dom = wrap.dom;
  3282. }
  3283. }
  3284. return dom;
  3285. }
  3286. /**
  3287. @internal
  3288. */
  3289. serializeMark(mark, inline, options = {}) {
  3290. let toDOM = this.marks[mark.type.name];
  3291. return toDOM && DOMSerializer.renderSpec(doc(options), toDOM(mark, inline));
  3292. }
  3293. /**
  3294. Render an [output spec](https://prosemirror.net/docs/ref/#model.DOMOutputSpec) to a DOM node. If
  3295. the spec has a hole (zero) in it, `contentDOM` will point at the
  3296. node with the hole.
  3297. */
  3298. static renderSpec(doc, structure, xmlNS = null) {
  3299. if (typeof structure == "string")
  3300. return { dom: doc.createTextNode(structure) };
  3301. if (structure.nodeType != null)
  3302. return { dom: structure };
  3303. if (structure.dom && structure.dom.nodeType != null)
  3304. return structure;
  3305. let tagName = structure[0], space = tagName.indexOf(" ");
  3306. if (space > 0) {
  3307. xmlNS = tagName.slice(0, space);
  3308. tagName = tagName.slice(space + 1);
  3309. }
  3310. let contentDOM;
  3311. let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));
  3312. let attrs = structure[1], start = 1;
  3313. if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) {
  3314. start = 2;
  3315. for (let name in attrs)
  3316. if (attrs[name] != null) {
  3317. let space = name.indexOf(" ");
  3318. if (space > 0)
  3319. dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);
  3320. else
  3321. dom.setAttribute(name, attrs[name]);
  3322. }
  3323. }
  3324. for (let i = start; i < structure.length; i++) {
  3325. let child = structure[i];
  3326. if (child === 0) {
  3327. if (i < structure.length - 1 || i > start)
  3328. throw new RangeError("Content hole must be the only child of its parent node");
  3329. return { dom, contentDOM: dom };
  3330. }
  3331. else {
  3332. let { dom: inner, contentDOM: innerContent } = DOMSerializer.renderSpec(doc, child, xmlNS);
  3333. dom.appendChild(inner);
  3334. if (innerContent) {
  3335. if (contentDOM)
  3336. throw new RangeError("Multiple content holes");
  3337. contentDOM = innerContent;
  3338. }
  3339. }
  3340. }
  3341. return { dom, contentDOM };
  3342. }
  3343. /**
  3344. Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
  3345. properties in a schema's node and mark specs.
  3346. */
  3347. static fromSchema(schema) {
  3348. return schema.cached.domSerializer ||
  3349. (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));
  3350. }
  3351. /**
  3352. Gather the serializers in a schema's node specs into an object.
  3353. This can be useful as a base to build a custom serializer from.
  3354. */
  3355. static nodesFromSchema(schema) {
  3356. let result = gatherToDOM(schema.nodes);
  3357. if (!result.text)
  3358. result.text = node => node.text;
  3359. return result;
  3360. }
  3361. /**
  3362. Gather the serializers in a schema's mark specs into an object.
  3363. */
  3364. static marksFromSchema(schema) {
  3365. return gatherToDOM(schema.marks);
  3366. }
  3367. }
  3368. function gatherToDOM(obj) {
  3369. let result = {};
  3370. for (let name in obj) {
  3371. let toDOM = obj[name].spec.toDOM;
  3372. if (toDOM)
  3373. result[name] = toDOM;
  3374. }
  3375. return result;
  3376. }
  3377. function doc(options) {
  3378. return options.document || window.document;
  3379. }
  3380. export { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };