8
0

writer.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module module:engine/view/writer
  7. */
  8. import Position from './position';
  9. import ContainerElement from './containerelement';
  10. import AttributeElement from './attributeelement';
  11. import EmptyElement from './emptyelement';
  12. import UIElement from './uielement';
  13. import Range from './range';
  14. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  15. import DocumentFragment from './documentfragment';
  16. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  17. import Text from './text';
  18. import EditableElement from './editableelement';
  19. /**
  20. * View writer class. Provides set of methods used to properly manipulate nodes attached to
  21. * {@link module:engine/view/document~Document view document}. It is not recommended to use it directly. To get an instance
  22. * of view writer associated with the document use {@link module:engine/view/view~View#change view.change()) method.
  23. */
  24. export default class Writer {
  25. constructor( document ) {
  26. this.document = document;
  27. }
  28. /**
  29. * Sets {@link module:engine/view/selection~Selection selection's} ranges and direction to the specified location based on the given
  30. * {@link module:engine/view/selection~Selection selection}, {@link module:engine/view/position~Position position},
  31. * {@link module:engine/view/item~Item item}, {@link module:engine/view/range~Range range},
  32. * an iterable of {@link module:engine/view/range~Range ranges} or null.
  33. *
  34. * // Sets ranges from the given range.
  35. * const range = new Range( start, end );
  36. * writer.setSelection( range, isBackwardSelection );
  37. *
  38. * // Sets ranges from the iterable of ranges.
  39. * const ranges = [ new Range( start1, end2 ), new Range( star2, end2 ) ];
  40. * writer.setSelection( range, isBackwardSelection );
  41. *
  42. * // Sets ranges from the other selection.
  43. * const otherSelection = new Selection();
  44. * writer.setSelection( otherSelection );
  45. *
  46. * // Sets collapsed range at the given position.
  47. * const position = new Position( root, path );
  48. * writer.setSelection( position );
  49. *
  50. * // Sets collapsed range on the given item.
  51. * const paragraph = writer.createElement( 'paragraph' );
  52. * writer.setSelection( paragraph, offset );
  53. *
  54. * // Removes all ranges.
  55. * writer.setSelection( null );
  56. *
  57. * @param {module:engine/view/selection~Selection|module:engine/view/position~Position|
  58. * Iterable.<module:engine/view/range~Range>|module:engine/view/range~Range|module:engine/view/item~Item|null} selectable
  59. * @param {Boolean|Number|'before'|'end'|'after'} [backwardSelectionOrOffset]
  60. */
  61. setSelection( selectable, backwardSelectionOrOffset ) {
  62. this.document.selection._setTo( selectable, backwardSelectionOrOffset );
  63. }
  64. /**
  65. * Moves {@link module:engine/view/selection~Selection#focus selection's focus} to the specified location.
  66. *
  67. * The location can be specified in the same form as {@link module:engine/view/position~Position.createAt} parameters.
  68. *
  69. * @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
  70. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  71. * first parameter is a {@link module:engine/view/item~Item view item}.
  72. */
  73. setSelectionFocus( itemOrPosition, offset ) {
  74. this.document.selection._setFocus( itemOrPosition, offset );
  75. }
  76. /**
  77. * Sets {@link module:engine/view/selection~Selection selection's} to be marked as `fake`. A fake selection does
  78. * not render as browser native selection over selected elements and is hidden to the user.
  79. * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
  80. * represented in other way, for example by applying proper CSS class.
  81. *
  82. * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM (and be
  83. * properly handled by screen readers).
  84. *
  85. * @param {Boolean} [value=true] If set to true selection will be marked as `fake`.
  86. * @param {Object} [options] Additional options.
  87. * @param {String} [options.label=''] Fake selection label.
  88. */
  89. setFakeSelection( value, options ) {
  90. this.document.selection._setFake( value, options );
  91. }
  92. /**
  93. * Creates a new {@link module:engine/view/text~Text text node}.
  94. *
  95. * writer.createText( 'foo' );
  96. *
  97. * @param {String} data Text data.
  98. * @returns {module:engine/view/text~Text} Created text node.
  99. */
  100. createText( data ) {
  101. return new Text( data );
  102. }
  103. /**
  104. * Creates new {@link module:engine/view/attributeelement~AttributeElement}.
  105. *
  106. * writer.createAttributeElement( 'paragraph' );
  107. * writer.createAttributeElement( 'paragraph', { 'alignment': 'center' } );
  108. *
  109. * @param {String} name Name of the element.
  110. * @param {Object} [attributes] Elements attributes.
  111. * @returns {module:engine/view/attributeelement~AttributeElement} Created element.
  112. */
  113. createAttributeElement( name, attributes ) {
  114. return new AttributeElement( name, attributes );
  115. }
  116. /**
  117. * Creates new {@link module:engine/view/containerelement~ContainerElement}.
  118. *
  119. * writer.createContainerElement( 'paragraph' );
  120. * writer.createContainerElement( 'paragraph', { 'alignment': 'center' } );
  121. *
  122. * @param {String} name Name of the element.
  123. * @param {Object} [attributes] Elements attributes.
  124. * @returns {module:engine/view/containerelement~ContainerElement} Created element.
  125. */
  126. createContainerElement( name, attributes ) {
  127. return new ContainerElement( name, attributes );
  128. }
  129. /**
  130. * Creates new {@link module:engine/view/editableelement~EditableElement}.
  131. *
  132. * writer.createEditableElement( document, 'paragraph' );
  133. * writer.createEditableElement( document, 'paragraph', { 'alignment': 'center' } );
  134. *
  135. * @param {module:engine/view/document~Document} document View document.
  136. * @param {String} name Name of the element.
  137. * @param {Object} [attributes] Elements attributes.
  138. * @returns {module:engine/view/editableelement~EditableElement} Created element.
  139. */
  140. createEditableElement( name, attributes ) {
  141. const editableElement = new EditableElement( name, attributes );
  142. editableElement.document = this.document;
  143. return editableElement;
  144. }
  145. /**
  146. * Creates new {@link module:engine/view/emptyelement~EmptyElement}.
  147. *
  148. * writer.createEmptyElement( 'paragraph' );
  149. * writer.createEmptyElement( 'paragraph', { 'alignment': 'center' } );
  150. *
  151. * @param {String} name Name of the element.
  152. * @param {Object} [attributes] Elements attributes.
  153. * @returns {module:engine/view/emptyelement~EmptyElement} Created element.
  154. */
  155. createEmptyElement( name, attributes ) {
  156. return new EmptyElement( name, attributes );
  157. }
  158. /**
  159. * Creates new {@link module:engine/view/uielement~UIElement}.
  160. *
  161. * writer.createUIElement( 'paragraph' );
  162. * writer.createUIElement( 'paragraph', { 'alignment': 'center' } );
  163. *
  164. * @param {String} name Name of the element.
  165. * @param {Object} [attributes] Elements attributes.
  166. * @returns {module:engine/view/uielement~UIElement} Created element.
  167. */
  168. createUIElement( name, attributes ) {
  169. return new UIElement( name, attributes );
  170. }
  171. /**
  172. * Breaks attribute nodes at provided position or at boundaries of provided range. It breaks attribute elements inside
  173. * up to a container element.
  174. *
  175. * In following examples `<p>` is a container, `<b>` and `<u>` are attribute nodes:
  176. *
  177. * <p>foo<b><u>bar{}</u></b></p> -> <p>foo<b><u>bar</u></b>[]</p>
  178. * <p>foo<b><u>{}bar</u></b></p> -> <p>foo{}<b><u>bar</u></b></p>
  179. * <p>foo<b><u>b{}ar</u></b></p> -> <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  180. * <p><b>fo{o</b><u>ba}r</u></p> -> <p><b>fo</b><b>o</b><u>ba</u><u>r</u></b></p>
  181. *
  182. * **Note:** {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
  183. *
  184. * **Note:** Difference between {@link module:engine/view/writer~Writer#breakAttributes breakAttributes} and
  185. * {@link module:engine/view/writer~Writer#breakContainer breakContainer} is that `breakAttributes` breaks all
  186. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of given `position`,
  187. * up to the first encountered {@link module:engine/view/containerelement~ContainerElement container element}.
  188. * `breakContainer` assumes that given `position` is directly in container element and breaks that container element.
  189. *
  190. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container`
  191. * when {@link module:engine/view/range~Range#start start}
  192. * and {@link module:engine/view/range~Range#end end} positions of a passed range are not placed inside same parent container.
  193. *
  194. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element`
  195. * when trying to break attributes
  196. * inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
  197. *
  198. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element`
  199. * when trying to break attributes
  200. * inside {@link module:engine/view/uielement~UIElement UIElement}.
  201. *
  202. * @see module:engine/view/attributeelement~AttributeElement
  203. * @see module:engine/view/containerelement~ContainerElement
  204. * @see module:engine/view/writer~Writer#breakContainer
  205. * @param {module:engine/view/position~Position|module:engine/view/range~Range} positionOrRange Position where
  206. * to break attribute elements.
  207. * @returns {module:engine/view/position~Position|module:engine/view/range~Range} New position or range, after breaking the attribute
  208. * elements.
  209. */
  210. breakAttributes( positionOrRange ) {
  211. if ( positionOrRange instanceof Position ) {
  212. return _breakAttributes( positionOrRange );
  213. } else {
  214. return _breakAttributesRange( positionOrRange );
  215. }
  216. }
  217. /**
  218. * Breaks {@link module:engine/view/containerelement~ContainerElement container view element} into two, at the given position. Position
  219. * has to be directly inside container element and cannot be in root. Does not break if position is at the beginning
  220. * or at the end of it's parent element.
  221. *
  222. * <p>foo^bar</p> -> <p>foo</p><p>bar</p>
  223. * <div><p>foo</p>^<p>bar</p></div> -> <div><p>foo</p></div><div><p>bar</p></div>
  224. * <p>^foobar</p> -> ^<p>foobar</p>
  225. * <p>foobar^</p> -> <p>foobar</p>^
  226. *
  227. * **Note:** Difference between {@link module:engine/view/writer~Writer#breakAttributes breakAttributes} and
  228. * {@link module:engine/view/writer~Writer#breakContainer breakContainer} is that `breakAttributes` breaks all
  229. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of given `position`,
  230. * up to the first encountered {@link module:engine/view/containerelement~ContainerElement container element}.
  231. * `breakContainer` assumes that given `position` is directly in container element and breaks that container element.
  232. *
  233. * @see module:engine/view/attributeelement~AttributeElement
  234. * @see module:engine/view/containerelement~ContainerElement
  235. * @see module:engine/view/writer~Writer#breakAttributes
  236. * @param {module:engine/view/position~Position} position Position where to break element.
  237. * @returns {module:engine/view/position~Position} Position between broken elements. If element has not been broken,
  238. * the returned position is placed either before it or after it.
  239. */
  240. breakContainer( position ) {
  241. const element = position.parent;
  242. if ( !( element.is( 'containerElement' ) ) ) {
  243. /**
  244. * Trying to break an element which is not a container element.
  245. *
  246. * @error view-writer-break-non-container-element
  247. */
  248. throw new CKEditorError(
  249. 'view-writer-break-non-container-element: Trying to break an element which is not a container element.'
  250. );
  251. }
  252. if ( !element.parent ) {
  253. /**
  254. * Trying to break root element.
  255. *
  256. * @error view-writer-break-root
  257. */
  258. throw new CKEditorError( 'view-writer-break-root: Trying to break root element.' );
  259. }
  260. if ( position.isAtStart ) {
  261. return Position.createBefore( element );
  262. } else if ( !position.isAtEnd ) {
  263. const newElement = element.clone( false );
  264. this.insert( Position.createAfter( element ), newElement );
  265. const sourceRange = new Range( position, Position.createAt( element, 'end' ) );
  266. const targetPosition = new Position( newElement, 0 );
  267. this.move( sourceRange, targetPosition );
  268. }
  269. return Position.createAfter( element );
  270. }
  271. /**
  272. * Merges {@link module:engine/view/attributeelement~AttributeElement attribute elements}. It also merges text nodes if needed.
  273. * Only {@link module:engine/view/attributeelement~AttributeElement#isSimilar similar} attribute elements can be merged.
  274. *
  275. * In following examples `<p>` is a container and `<b>` is an attribute element:
  276. *
  277. * <p>foo[]bar</p> -> <p>foo{}bar</p>
  278. * <p><b>foo</b>[]<b>bar</b></p> -> <p><b>foo{}bar</b></p>
  279. * <p><b foo="bar">a</b>[]<b foo="baz">b</b></p> -> <p><b foo="bar">a</b>[]<b foo="baz">b</b></p>
  280. *
  281. * It will also take care about empty attributes when merging:
  282. *
  283. * <p><b>[]</b></p> -> <p>[]</p>
  284. * <p><b>foo</b><i>[]</i><b>bar</b></p> -> <p><b>foo{}bar</b></p>
  285. *
  286. * **Note:** Difference between {@link module:engine/view/writer~Writer#mergeAttributes mergeAttributes} and
  287. * {@link module:engine/view/writer~Writer#mergeContainers mergeContainers} is that `mergeAttributes` merges two
  288. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
  289. * while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
  290. *
  291. * @see module:engine/view/attributeelement~AttributeElement
  292. * @see module:engine/view/containerelement~ContainerElement
  293. * @see module:engine/view/writer~Writer#mergeContainers
  294. * @param {module:engine/view/position~Position} position Merge position.
  295. * @returns {module:engine/view/position~Position} Position after merge.
  296. */
  297. mergeAttributes( position ) {
  298. const positionOffset = position.offset;
  299. const positionParent = position.parent;
  300. // When inside text node - nothing to merge.
  301. if ( positionParent.is( 'text' ) ) {
  302. return position;
  303. }
  304. // When inside empty attribute - remove it.
  305. if ( positionParent.is( 'attributeElement' ) && positionParent.childCount === 0 ) {
  306. const parent = positionParent.parent;
  307. const offset = positionParent.index;
  308. positionParent.remove();
  309. return this.mergeAttributes( new Position( parent, offset ) );
  310. }
  311. const nodeBefore = positionParent.getChild( positionOffset - 1 );
  312. const nodeAfter = positionParent.getChild( positionOffset );
  313. // Position should be placed between two nodes.
  314. if ( !nodeBefore || !nodeAfter ) {
  315. return position;
  316. }
  317. // When position is between two text nodes.
  318. if ( nodeBefore.is( 'text' ) && nodeAfter.is( 'text' ) ) {
  319. return mergeTextNodes( nodeBefore, nodeAfter );
  320. }
  321. // When selection is between two same attribute elements.
  322. else if ( nodeBefore.is( 'attributeElement' ) && nodeAfter.is( 'attributeElement' ) && nodeBefore.isSimilar( nodeAfter ) ) {
  323. // Move all children nodes from node placed after selection and remove that node.
  324. const count = nodeBefore.childCount;
  325. nodeBefore.appendChildren( nodeAfter.getChildren() );
  326. nodeAfter.remove();
  327. // New position is located inside the first node, before new nodes.
  328. // Call this method recursively to merge again if needed.
  329. return this.mergeAttributes( new Position( nodeBefore, count ) );
  330. }
  331. return position;
  332. }
  333. /**
  334. * Merges two {@link module:engine/view/containerelement~ContainerElement container elements} that are before and after given position.
  335. * Precisely, the element after the position is removed and it's contents are moved to element before the position.
  336. *
  337. * <p>foo</p>^<p>bar</p> -> <p>foo^bar</p>
  338. * <div>foo</div>^<p>bar</p> -> <div>foo^bar</div>
  339. *
  340. * **Note:** Difference between {@link module:engine/view/writer~Writer#mergeAttributes mergeAttributes} and
  341. * {@link module:engine/view/writer~Writer#mergeContainers mergeContainers} is that `mergeAttributes` merges two
  342. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
  343. * while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
  344. *
  345. * @see module:engine/view/attributeelement~AttributeElement
  346. * @see module:engine/view/containerelement~ContainerElement
  347. * @see module:engine/view/writer~Writer#mergeAttributes
  348. * @param {module:engine/view/position~Position} position Merge position.
  349. * @returns {module:engine/view/position~Position} Position after merge.
  350. */
  351. mergeContainers( position ) {
  352. const prev = position.nodeBefore;
  353. const next = position.nodeAfter;
  354. if ( !prev || !next || !prev.is( 'containerElement' ) || !next.is( 'containerElement' ) ) {
  355. /**
  356. * Element before and after given position cannot be merged.
  357. *
  358. * @error view-writer-merge-containers-invalid-position
  359. */
  360. throw new CKEditorError( 'view-writer-merge-containers-invalid-position: ' +
  361. 'Element before and after given position cannot be merged.' );
  362. }
  363. const lastChild = prev.getChild( prev.childCount - 1 );
  364. const newPosition = lastChild instanceof Text ? Position.createAt( lastChild, 'end' ) : Position.createAt( prev, 'end' );
  365. this.move( Range.createIn( next ), Position.createAt( prev, 'end' ) );
  366. this.remove( Range.createOn( next ) );
  367. return newPosition;
  368. }
  369. /**
  370. * Insert node or nodes at specified position. Takes care about breaking attributes before insertion
  371. * and merging them afterwards.
  372. *
  373. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  374. * contains instances that are not {@link module:engine/view/text~Text Texts},
  375. * {@link module:engine/view/attributeelement~AttributeElement AttributeElements},
  376. * {@link module:engine/view/containerelement~ContainerElement ContainerElements},
  377. * {@link module:engine/view/emptyelement~EmptyElement EmptyElements} or
  378. * {@link module:engine/view/uielement~UIElement UIElements}.
  379. *
  380. * @param {module:engine/view/position~Position} position Insertion position.
  381. * @param {module:engine/view/text~Text|module:engine/view/attributeelement~AttributeElement|
  382. * module:engine/view/containerelement~ContainerElement|module:engine/view/emptyelement~EmptyElement|
  383. * module:engine/view/uielement~UIElement|Iterable.<module:engine/view/text~Text|
  384. * module:engine/view/attributeelement~AttributeElement|module:engine/view/containerelement~ContainerElement|
  385. * module:engine/view/emptyelement~EmptyElement|module:engine/view/uielement~UIElement>} nodes Node or nodes to insert.
  386. * @returns {module:engine/view/range~Range} Range around inserted nodes.
  387. */
  388. insert( position, nodes ) {
  389. nodes = isIterable( nodes ) ? [ ...nodes ] : [ nodes ];
  390. // Check if nodes to insert are instances of AttributeElements, ContainerElements, EmptyElements, UIElements or Text.
  391. validateNodesToInsert( nodes );
  392. const container = getParentContainer( position );
  393. if ( !container ) {
  394. /**
  395. * Position's parent container cannot be found.
  396. *
  397. * @error view-writer-invalid-position-container
  398. */
  399. throw new CKEditorError( 'view-writer-invalid-position-container' );
  400. }
  401. const insertionPosition = _breakAttributes( position, true );
  402. const length = container.insertChildren( insertionPosition.offset, nodes );
  403. const endPosition = insertionPosition.getShiftedBy( length );
  404. const start = this.mergeAttributes( insertionPosition );
  405. // When no nodes were inserted - return collapsed range.
  406. if ( length === 0 ) {
  407. return new Range( start, start );
  408. } else {
  409. // If start position was merged - move end position.
  410. if ( !start.isEqual( insertionPosition ) ) {
  411. endPosition.offset--;
  412. }
  413. const end = this.mergeAttributes( endPosition );
  414. return new Range( start, end );
  415. }
  416. }
  417. /**
  418. * Removes provided range from the container.
  419. *
  420. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  421. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  422. * same parent container.
  423. *
  424. * @param {module:engine/view/range~Range} range Range to remove from container. After removing, it will be updated
  425. * to a collapsed range showing the new position.
  426. * @returns {module:engine/view/documentfragment~DocumentFragment} Document fragment containing removed nodes.
  427. */
  428. remove( range ) {
  429. validateRangeContainer( range );
  430. // If range is collapsed - nothing to remove.
  431. if ( range.isCollapsed ) {
  432. return new DocumentFragment();
  433. }
  434. // Break attributes at range start and end.
  435. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  436. const parentContainer = breakStart.parent;
  437. const count = breakEnd.offset - breakStart.offset;
  438. // Remove nodes in range.
  439. const removed = parentContainer.removeChildren( breakStart.offset, count );
  440. // Merge after removing.
  441. const mergePosition = this.mergeAttributes( breakStart );
  442. range.start = mergePosition;
  443. range.end = Position.createFromPosition( mergePosition );
  444. // Return removed nodes.
  445. return new DocumentFragment( removed );
  446. }
  447. /**
  448. * Removes matching elements from given range.
  449. *
  450. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  451. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  452. * same parent container.
  453. *
  454. * @param {module:engine/view/range~Range} range Range to clear.
  455. * @param {module:engine/view/element~Element} element Element to remove.
  456. */
  457. clear( range, element ) {
  458. validateRangeContainer( range );
  459. // Create walker on given range.
  460. // We walk backward because when we remove element during walk it modifies range end position.
  461. const walker = range.getWalker( {
  462. direction: 'backward',
  463. ignoreElementEnd: true
  464. } );
  465. // Let's walk.
  466. for ( const current of walker ) {
  467. const item = current.item;
  468. let rangeToRemove;
  469. // When current item matches to the given element.
  470. if ( item.is( 'element' ) && element.isSimilar( item ) ) {
  471. // Create range on this element.
  472. rangeToRemove = Range.createOn( item );
  473. // When range starts inside Text or TextProxy element.
  474. } else if ( !current.nextPosition.isAfter( range.start ) && item.is( 'textProxy' ) ) {
  475. // We need to check if parent of this text matches to given element.
  476. const parentElement = item.getAncestors().find( ancestor => {
  477. return ancestor.is( 'element' ) && element.isSimilar( ancestor );
  478. } );
  479. // If it is then create range inside this element.
  480. if ( parentElement ) {
  481. rangeToRemove = Range.createIn( parentElement );
  482. }
  483. }
  484. // If we have found element to remove.
  485. if ( rangeToRemove ) {
  486. // We need to check if element range stick out of the given range and truncate if it is.
  487. if ( rangeToRemove.end.isAfter( range.end ) ) {
  488. rangeToRemove.end = range.end;
  489. }
  490. if ( rangeToRemove.start.isBefore( range.start ) ) {
  491. rangeToRemove.start = range.start;
  492. }
  493. // At the end we remove range with found element.
  494. this.remove( rangeToRemove );
  495. }
  496. }
  497. }
  498. /**
  499. * Moves nodes from provided range to target position.
  500. *
  501. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  502. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  503. * same parent container.
  504. *
  505. * @param {module:engine/view/range~Range} sourceRange Range containing nodes to move.
  506. * @param {module:engine/view/position~Position} targetPosition Position to insert.
  507. * @returns {module:engine/view/range~Range} Range in target container. Inserted nodes are placed between
  508. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions.
  509. */
  510. move( sourceRange, targetPosition ) {
  511. let nodes;
  512. if ( targetPosition.isAfter( sourceRange.end ) ) {
  513. targetPosition = _breakAttributes( targetPosition, true );
  514. const parent = targetPosition.parent;
  515. const countBefore = parent.childCount;
  516. sourceRange = _breakAttributesRange( sourceRange, true );
  517. nodes = this.remove( sourceRange );
  518. targetPosition.offset += ( parent.childCount - countBefore );
  519. } else {
  520. nodes = this.remove( sourceRange );
  521. }
  522. return this.insert( targetPosition, nodes );
  523. }
  524. /**
  525. * Wraps elements within range with provided {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
  526. * If a collapsed range is provided, it will be wrapped only if it is equal to view selection.
  527. *
  528. * If a collapsed range was passed and is same as selection, the selection
  529. * will be moved to the inside of the wrapped attribute element.
  530. *
  531. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-invalid-range-container`
  532. * when {@link module:engine/view/range~Range#start}
  533. * and {@link module:engine/view/range~Range#end} positions are not placed inside same parent container.
  534. *
  535. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  536. * an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  537. *
  538. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-nonselection-collapsed-range` when passed range
  539. * is collapsed and different than view selection.
  540. *
  541. * @param {module:engine/view/range~Range} range Range to wrap.
  542. * @param {module:engine/view/attributeelement~AttributeElement} attribute Attribute element to use as wrapper.
  543. * @returns {module:engine/view/range~Range} range Range after wrapping, spanning over wrapping attribute element.
  544. */
  545. wrap( range, attribute ) {
  546. if ( !( attribute instanceof AttributeElement ) ) {
  547. throw new CKEditorError( 'view-writer-wrap-invalid-attribute' );
  548. }
  549. validateRangeContainer( range );
  550. if ( !range.isCollapsed ) {
  551. // Non-collapsed range. Wrap it with the attribute element.
  552. return this._wrapRange( range, attribute );
  553. } else {
  554. // Collapsed range. Wrap position.
  555. let position = range.start;
  556. if ( position.parent.is( 'element' ) && !_hasNonUiChildren( position.parent ) ) {
  557. position = position.getLastMatchingPosition( value => value.item.is( 'uiElement' ) );
  558. }
  559. position = this._wrapPosition( position, attribute );
  560. const viewSelection = this.document.selection;
  561. // If wrapping position is equal to view selection, move view selection inside wrapping attribute element.
  562. if ( viewSelection.isCollapsed && viewSelection.getFirstPosition().isEqual( range.start ) ) {
  563. this.setSelection( position );
  564. }
  565. return new Range( position );
  566. }
  567. }
  568. /**
  569. * Unwraps nodes within provided range from attribute element.
  570. *
  571. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  572. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  573. * same parent container.
  574. *
  575. * @param {module:engine/view/range~Range} range
  576. * @param {module:engine/view/attributeelement~AttributeElement} attribute
  577. */
  578. unwrap( range, attribute ) {
  579. if ( !( attribute instanceof AttributeElement ) ) {
  580. /**
  581. * Attribute element need to be instance of attribute element.
  582. *
  583. * @error view-writer-unwrap-invalid-attribute
  584. */
  585. throw new CKEditorError( 'view-writer-unwrap-invalid-attribute' );
  586. }
  587. validateRangeContainer( range );
  588. // If range is collapsed - nothing to unwrap.
  589. if ( range.isCollapsed ) {
  590. return range;
  591. }
  592. // Break attributes at range start and end.
  593. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  594. // Range around one element - check if AttributeElement can be unwrapped partially when it's not similar.
  595. // For example:
  596. // <b class="foo bar" title="baz"></b> unwrap with: <b class="foo"></p> result: <b class"bar" title="baz"></b>
  597. if ( breakEnd.isEqual( breakStart.getShiftedBy( 1 ) ) ) {
  598. const node = breakStart.nodeAfter;
  599. // Unwrap single attribute element.
  600. if ( !attribute.isSimilar( node ) && node instanceof AttributeElement && unwrapAttributeElement( attribute, node ) ) {
  601. const start = this.mergeAttributes( breakStart );
  602. if ( !start.isEqual( breakStart ) ) {
  603. breakEnd.offset--;
  604. }
  605. const end = this.mergeAttributes( breakEnd );
  606. return new Range( start, end );
  607. }
  608. }
  609. const parentContainer = breakStart.parent;
  610. // Unwrap children located between break points.
  611. const newRange = this._unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  612. // Merge attributes at the both ends and return a new range.
  613. const start = this.mergeAttributes( newRange.start );
  614. // If start position was merged - move end position back.
  615. if ( !start.isEqual( newRange.start ) ) {
  616. newRange.end.offset--;
  617. }
  618. const end = this.mergeAttributes( newRange.end );
  619. return new Range( start, end );
  620. }
  621. /**
  622. * Renames element by creating a copy of renamed element but with changed name and then moving contents of the
  623. * old element to the new one. Keep in mind that this will invalidate all {@link module:engine/view/position~Position positions} which
  624. * has renamed element as {@link module:engine/view/position~Position#parent a parent}.
  625. *
  626. * New element has to be created because `Element#tagName` property in DOM is readonly.
  627. *
  628. * Since this function creates a new element and removes the given one, the new element is returned to keep reference.
  629. *
  630. * @param {module:engine/view/containerelement~ContainerElement} viewElement Element to be renamed.
  631. * @param {String} newName New name for element.
  632. */
  633. rename( viewElement, newName ) {
  634. const newElement = new ContainerElement( newName, viewElement.getAttributes() );
  635. this.insert( Position.createAfter( viewElement ), newElement );
  636. this.move( Range.createIn( viewElement ), Position.createAt( newElement ) );
  637. this.remove( Range.createOn( viewElement ) );
  638. return newElement;
  639. }
  640. /**
  641. * Wraps children with provided `attribute`. Only children contained in `parent` element between
  642. * `startOffset` and `endOffset` will be wrapped.
  643. *
  644. * @private
  645. * @param {module:engine/view/element~Element} parent
  646. * @param {Number} startOffset
  647. * @param {Number} endOffset
  648. * @param {module:engine/view/element~Element} attribute
  649. */
  650. _wrapChildren( parent, startOffset, endOffset, attribute ) {
  651. let i = startOffset;
  652. const wrapPositions = [];
  653. while ( i < endOffset ) {
  654. const child = parent.getChild( i );
  655. const isText = child.is( 'text' );
  656. const isAttribute = child.is( 'attributeElement' );
  657. const isEmpty = child.is( 'emptyElement' );
  658. const isUI = child.is( 'uiElement' );
  659. // Wrap text, empty elements, ui elements or attributes with higher or equal priority.
  660. if ( isText || isEmpty || isUI || ( isAttribute && shouldABeOutsideB( attribute, child ) ) ) {
  661. // Clone attribute.
  662. const newAttribute = attribute.clone();
  663. // Wrap current node with new attribute;
  664. child.remove();
  665. newAttribute.appendChildren( child );
  666. parent.insertChildren( i, newAttribute );
  667. wrapPositions.push( new Position( parent, i ) );
  668. }
  669. // If other nested attribute is found start wrapping there.
  670. else if ( isAttribute ) {
  671. this._wrapChildren( child, 0, child.childCount, attribute );
  672. }
  673. i++;
  674. }
  675. // Merge at each wrap.
  676. let offsetChange = 0;
  677. for ( const position of wrapPositions ) {
  678. position.offset -= offsetChange;
  679. // Do not merge with elements outside selected children.
  680. if ( position.offset == startOffset ) {
  681. continue;
  682. }
  683. const newPosition = this.mergeAttributes( position );
  684. // If nodes were merged - other merge offsets will change.
  685. if ( !newPosition.isEqual( position ) ) {
  686. offsetChange++;
  687. endOffset--;
  688. }
  689. }
  690. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  691. }
  692. /**
  693. * Unwraps children from provided `attribute`. Only children contained in `parent` element between
  694. * `startOffset` and `endOffset` will be unwrapped.
  695. *
  696. * @private
  697. * @param {module:engine/view/element~Element} parent
  698. * @param {Number} startOffset
  699. * @param {Number} endOffset
  700. * @param {module:engine/view/element~Element} attribute
  701. */
  702. _unwrapChildren( parent, startOffset, endOffset, attribute ) {
  703. let i = startOffset;
  704. const unwrapPositions = [];
  705. // Iterate over each element between provided offsets inside parent.
  706. while ( i < endOffset ) {
  707. const child = parent.getChild( i );
  708. // If attributes are the similar, then unwrap.
  709. if ( child.isSimilar( attribute ) ) {
  710. const unwrapped = child.getChildren();
  711. const count = child.childCount;
  712. // Replace wrapper element with its children
  713. child.remove();
  714. parent.insertChildren( i, unwrapped );
  715. // Save start and end position of moved items.
  716. unwrapPositions.push(
  717. new Position( parent, i ),
  718. new Position( parent, i + count )
  719. );
  720. // Skip elements that were unwrapped. Assuming that there won't be another element to unwrap in child
  721. // elements.
  722. i += count;
  723. endOffset += count - 1;
  724. } else {
  725. // If other nested attribute is found start unwrapping there.
  726. if ( child.is( 'attributeElement' ) ) {
  727. this._unwrapChildren( child, 0, child.childCount, attribute );
  728. }
  729. i++;
  730. }
  731. }
  732. // Merge at each unwrap.
  733. let offsetChange = 0;
  734. for ( const position of unwrapPositions ) {
  735. position.offset -= offsetChange;
  736. // Do not merge with elements outside selected children.
  737. if ( position.offset == startOffset || position.offset == endOffset ) {
  738. continue;
  739. }
  740. const newPosition = this.mergeAttributes( position );
  741. // If nodes were merged - other merge offsets will change.
  742. if ( !newPosition.isEqual( position ) ) {
  743. offsetChange++;
  744. endOffset--;
  745. }
  746. }
  747. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  748. }
  749. /**
  750. * Helper function for `view.writer.wrap`. Wraps range with provided attribute element.
  751. * This method will also merge newly added attribute element with its siblings whenever possible.
  752. *
  753. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  754. * an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  755. *
  756. * @private
  757. * @param {module:engine/view/range~Range} range
  758. * @param {module:engine/view/attributeelement~AttributeElement} attribute
  759. * @returns {module:engine/view/range~Range} New range after wrapping, spanning over wrapping attribute element.
  760. */
  761. _wrapRange( range, attribute ) {
  762. // Range is inside single attribute and spans on all children.
  763. if ( rangeSpansOnAllChildren( range ) && wrapAttributeElement( attribute, range.start.parent ) ) {
  764. const parent = range.start.parent;
  765. const end = this.mergeAttributes( Position.createAfter( parent ) );
  766. const start = this.mergeAttributes( Position.createBefore( parent ) );
  767. return new Range( start, end );
  768. }
  769. // Break attributes at range start and end.
  770. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  771. // Range around one element.
  772. if ( breakEnd.isEqual( breakStart.getShiftedBy( 1 ) ) ) {
  773. const node = breakStart.nodeAfter;
  774. if ( node instanceof AttributeElement && wrapAttributeElement( attribute, node ) ) {
  775. const start = this.mergeAttributes( breakStart );
  776. if ( !start.isEqual( breakStart ) ) {
  777. breakEnd.offset--;
  778. }
  779. const end = this.mergeAttributes( breakEnd );
  780. return new Range( start, end );
  781. }
  782. }
  783. const parentContainer = breakStart.parent;
  784. // Unwrap children located between break points.
  785. const unwrappedRange = this._unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  786. // Wrap all children with attribute.
  787. const newRange = this._wrapChildren( parentContainer, unwrappedRange.start.offset, unwrappedRange.end.offset, attribute );
  788. // Merge attributes at the both ends and return a new range.
  789. const start = this.mergeAttributes( newRange.start );
  790. // If start position was merged - move end position back.
  791. if ( !start.isEqual( newRange.start ) ) {
  792. newRange.end.offset--;
  793. }
  794. const end = this.mergeAttributes( newRange.end );
  795. return new Range( start, end );
  796. }
  797. /**
  798. * Helper function for {@link #wrap}. Wraps position with provided attribute element.
  799. * This method will also merge newly added attribute element with its siblings whenever possible.
  800. *
  801. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  802. * an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  803. *
  804. * @private
  805. * @param {module:engine/view/position~Position} position
  806. * @param {module:engine/view/attributeelement~AttributeElement} attribute
  807. * @returns {module:engine/view/position~Position} New position after wrapping.
  808. */
  809. _wrapPosition( position, attribute ) {
  810. // Return same position when trying to wrap with attribute similar to position parent.
  811. if ( attribute.isSimilar( position.parent ) ) {
  812. return movePositionToTextNode( Position.createFromPosition( position ) );
  813. }
  814. // When position is inside text node - break it and place new position between two text nodes.
  815. if ( position.parent.is( 'text' ) ) {
  816. position = breakTextNode( position );
  817. }
  818. // Create fake element that will represent position, and will not be merged with other attributes.
  819. const fakePosition = new AttributeElement();
  820. fakePosition.priority = Number.POSITIVE_INFINITY;
  821. fakePosition.isSimilar = () => false;
  822. // Insert fake element in position location.
  823. position.parent.insertChildren( position.offset, fakePosition );
  824. // Range around inserted fake attribute element.
  825. const wrapRange = new Range( position, position.getShiftedBy( 1 ) );
  826. // Wrap fake element with attribute (it will also merge if possible).
  827. this.wrap( wrapRange, attribute );
  828. // Remove fake element and place new position there.
  829. const newPosition = new Position( fakePosition.parent, fakePosition.index );
  830. fakePosition.remove();
  831. // If position is placed between text nodes - merge them and return position inside.
  832. const nodeBefore = newPosition.nodeBefore;
  833. const nodeAfter = newPosition.nodeAfter;
  834. if ( nodeBefore instanceof Text && nodeAfter instanceof Text ) {
  835. return mergeTextNodes( nodeBefore, nodeAfter );
  836. }
  837. // If position is next to text node - move position inside.
  838. return movePositionToTextNode( newPosition );
  839. }
  840. }
  841. // Helper function for `view.writer.wrap`. Checks if given element has any children that are not ui elements.
  842. function _hasNonUiChildren( parent ) {
  843. return Array.from( parent.getChildren() ).some( child => !child.is( 'uiElement' ) );
  844. }
  845. /**
  846. * Attribute element need to be instance of attribute element.
  847. *
  848. * @error view-writer-wrap-invalid-attribute
  849. */
  850. // Returns first parent container of specified {@link module:engine/view/position~Position Position}.
  851. // Position's parent node is checked as first, then next parents are checked.
  852. // Note that {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
  853. //
  854. // @param {module:engine/view/position~Position} position Position used as a start point to locate parent container.
  855. // @returns {module:engine/view/containerelement~ContainerElement|module:engine/view/documentfragment~DocumentFragment|undefined}
  856. // Parent container element or `undefined` if container is not found.
  857. function getParentContainer( position ) {
  858. let parent = position.parent;
  859. while ( !isContainerOrFragment( parent ) ) {
  860. if ( !parent ) {
  861. return undefined;
  862. }
  863. parent = parent.parent;
  864. }
  865. return parent;
  866. }
  867. // Function used by both public breakAttributes (without splitting text nodes) and by other methods (with
  868. // splitting text nodes).
  869. //
  870. // @param {module:engine/view/range~Range} range Range which `start` and `end` positions will be used to break attributes.
  871. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  872. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  873. // which then fixes view state. Defaults to `false`.
  874. // @returns {module:engine/view/range~Range} New range with located at break positions.
  875. function _breakAttributesRange( range, forceSplitText = false ) {
  876. const rangeStart = range.start;
  877. const rangeEnd = range.end;
  878. validateRangeContainer( range );
  879. // Break at the collapsed position. Return new collapsed range.
  880. if ( range.isCollapsed ) {
  881. const position = _breakAttributes( range.start, forceSplitText );
  882. return new Range( position, position );
  883. }
  884. const breakEnd = _breakAttributes( rangeEnd, forceSplitText );
  885. const count = breakEnd.parent.childCount;
  886. const breakStart = _breakAttributes( rangeStart, forceSplitText );
  887. // Calculate new break end offset.
  888. breakEnd.offset += breakEnd.parent.childCount - count;
  889. return new Range( breakStart, breakEnd );
  890. }
  891. // Function used by public breakAttributes (without splitting text nodes) and by other methods (with
  892. // splitting text nodes).
  893. //
  894. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element` when break position
  895. // is placed inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
  896. //
  897. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element` when break position
  898. // is placed inside {@link module:engine/view/uielement~UIElement UIElement}.
  899. //
  900. // @param {module:engine/view/position~Position} position Position where to break attributes.
  901. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  902. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  903. // which then fixes view state. Defaults to `false`.
  904. // @returns {module:engine/view/position~Position} New position after breaking the attributes.
  905. function _breakAttributes( position, forceSplitText = false ) {
  906. const positionOffset = position.offset;
  907. const positionParent = position.parent;
  908. // If position is placed inside EmptyElement - throw an exception as we cannot break inside.
  909. if ( position.parent.is( 'emptyElement' ) ) {
  910. /**
  911. * Cannot break inside EmptyElement instance.
  912. *
  913. * @error view-writer-cannot-break-empty-element
  914. */
  915. throw new CKEditorError( 'view-writer-cannot-break-empty-element' );
  916. }
  917. // If position is placed inside UIElement - throw an exception as we cannot break inside.
  918. if ( position.parent.is( 'uiElement' ) ) {
  919. /**
  920. * Cannot break inside UIElement instance.
  921. *
  922. * @error view-writer-cannot-break-ui-element
  923. */
  924. throw new CKEditorError( 'view-writer-cannot-break-ui-element' );
  925. }
  926. // There are no attributes to break and text nodes breaking is not forced.
  927. if ( !forceSplitText && positionParent.is( 'text' ) && isContainerOrFragment( positionParent.parent ) ) {
  928. return Position.createFromPosition( position );
  929. }
  930. // Position's parent is container, so no attributes to break.
  931. if ( isContainerOrFragment( positionParent ) ) {
  932. return Position.createFromPosition( position );
  933. }
  934. // Break text and start again in new position.
  935. if ( positionParent.is( 'text' ) ) {
  936. return _breakAttributes( breakTextNode( position ), forceSplitText );
  937. }
  938. const length = positionParent.childCount;
  939. // <p>foo<b><u>bar{}</u></b></p>
  940. // <p>foo<b><u>bar</u>[]</b></p>
  941. // <p>foo<b><u>bar</u></b>[]</p>
  942. if ( positionOffset == length ) {
  943. const newPosition = new Position( positionParent.parent, positionParent.index + 1 );
  944. return _breakAttributes( newPosition, forceSplitText );
  945. } else
  946. // <p>foo<b><u>{}bar</u></b></p>
  947. // <p>foo<b>[]<u>bar</u></b></p>
  948. // <p>foo{}<b><u>bar</u></b></p>
  949. if ( positionOffset === 0 ) {
  950. const newPosition = new Position( positionParent.parent, positionParent.index );
  951. return _breakAttributes( newPosition, forceSplitText );
  952. }
  953. // <p>foo<b><u>b{}ar</u></b></p>
  954. // <p>foo<b><u>b[]ar</u></b></p>
  955. // <p>foo<b><u>b</u>[]<u>ar</u></b></p>
  956. // <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  957. else {
  958. const offsetAfter = positionParent.index + 1;
  959. // Break element.
  960. const clonedNode = positionParent.clone();
  961. // Insert cloned node to position's parent node.
  962. positionParent.parent.insertChildren( offsetAfter, clonedNode );
  963. // Get nodes to move.
  964. const count = positionParent.childCount - positionOffset;
  965. const nodesToMove = positionParent.removeChildren( positionOffset, count );
  966. // Move nodes to cloned node.
  967. clonedNode.appendChildren( nodesToMove );
  968. // Create new position to work on.
  969. const newPosition = new Position( positionParent.parent, offsetAfter );
  970. return _breakAttributes( newPosition, forceSplitText );
  971. }
  972. }
  973. // Checks if first {@link module:engine/view/attributeelement~AttributeElement AttributeElement} provided to the function
  974. // can be wrapped otuside second element. It is done by comparing elements'
  975. // {@link module:engine/view/attributeelement~AttributeElement#priority priorities}, if both have same priority
  976. // {@link module:engine/view/element~Element#getIdentity identities} are compared.
  977. //
  978. // @param {module:engine/view/attributeelement~AttributeElement} a
  979. // @param {module:engine/view/attributeelement~AttributeElement} b
  980. // @returns {Boolean}
  981. function shouldABeOutsideB( a, b ) {
  982. if ( a.priority < b.priority ) {
  983. return true;
  984. } else if ( a.priority > b.priority ) {
  985. return false;
  986. }
  987. // When priorities are equal and names are different - use identities.
  988. return a.getIdentity() < b.getIdentity();
  989. }
  990. // Returns new position that is moved to near text node. Returns same position if there is no text node before of after
  991. // specified position.
  992. //
  993. // <p>foo[]</p> -> <p>foo{}</p>
  994. // <p>[]foo</p> -> <p>{}foo</p>
  995. //
  996. // @param {module:engine/view/position~Position} position
  997. // @returns {module:engine/view/position~Position} Position located inside text node or same position if there is no text nodes
  998. // before or after position location.
  999. function movePositionToTextNode( position ) {
  1000. const nodeBefore = position.nodeBefore;
  1001. if ( nodeBefore && nodeBefore.is( 'text' ) ) {
  1002. return new Position( nodeBefore, nodeBefore.data.length );
  1003. }
  1004. const nodeAfter = position.nodeAfter;
  1005. if ( nodeAfter && nodeAfter.is( 'text' ) ) {
  1006. return new Position( nodeAfter, 0 );
  1007. }
  1008. return position;
  1009. }
  1010. // Breaks text node into two text nodes when possible.
  1011. //
  1012. // <p>foo{}bar</p> -> <p>foo[]bar</p>
  1013. // <p>{}foobar</p> -> <p>[]foobar</p>
  1014. // <p>foobar{}</p> -> <p>foobar[]</p>
  1015. //
  1016. // @param {module:engine/view/position~Position} position Position that need to be placed inside text node.
  1017. // @returns {module:engine/view/position~Position} New position after breaking text node.
  1018. function breakTextNode( position ) {
  1019. if ( position.offset == position.parent.data.length ) {
  1020. return new Position( position.parent.parent, position.parent.index + 1 );
  1021. }
  1022. if ( position.offset === 0 ) {
  1023. return new Position( position.parent.parent, position.parent.index );
  1024. }
  1025. // Get part of the text that need to be moved.
  1026. const textToMove = position.parent.data.slice( position.offset );
  1027. // Leave rest of the text in position's parent.
  1028. position.parent.data = position.parent.data.slice( 0, position.offset );
  1029. // Insert new text node after position's parent text node.
  1030. position.parent.parent.insertChildren( position.parent.index + 1, new Text( textToMove ) );
  1031. // Return new position between two newly created text nodes.
  1032. return new Position( position.parent.parent, position.parent.index + 1 );
  1033. }
  1034. // Merges two text nodes into first node. Removes second node and returns merge position.
  1035. //
  1036. // @param {module:engine/view/text~Text} t1 First text node to merge. Data from second text node will be moved at the end of
  1037. // this text node.
  1038. // @param {module:engine/view/text~Text} t2 Second text node to merge. This node will be removed after merging.
  1039. // @returns {module:engine/view/position~Position} Position after merging text nodes.
  1040. function mergeTextNodes( t1, t2 ) {
  1041. // Merge text data into first text node and remove second one.
  1042. const nodeBeforeLength = t1.data.length;
  1043. t1.data += t2.data;
  1044. t2.remove();
  1045. return new Position( t1, nodeBeforeLength );
  1046. }
  1047. // Wraps one {@link module:engine/view/attributeelement~AttributeElement AttributeElement} into another by merging them if possible.
  1048. // When merging is possible - all attributes, styles and classes are moved from wrapper element to element being
  1049. // wrapped.
  1050. //
  1051. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  1052. // @param {module:engine/view/attributeelement~AttributeElement} toWrap AttributeElement to wrap using wrapper element.
  1053. // @returns {Boolean} Returns `true` if elements are merged.
  1054. function wrapAttributeElement( wrapper, toWrap ) {
  1055. // Can't merge if name or priority differs.
  1056. if ( wrapper.name !== toWrap.name || wrapper.priority !== toWrap.priority ) {
  1057. return false;
  1058. }
  1059. // Check if attributes can be merged.
  1060. for ( const key of wrapper.getAttributeKeys() ) {
  1061. // Classes and styles should be checked separately.
  1062. if ( key === 'class' || key === 'style' ) {
  1063. continue;
  1064. }
  1065. // If some attributes are different we cannot wrap.
  1066. if ( toWrap.hasAttribute( key ) && toWrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  1067. return false;
  1068. }
  1069. }
  1070. // Check if styles can be merged.
  1071. for ( const key of wrapper.getStyleNames() ) {
  1072. if ( toWrap.hasStyle( key ) && toWrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  1073. return false;
  1074. }
  1075. }
  1076. // Move all attributes/classes/styles from wrapper to wrapped AttributeElement.
  1077. for ( const key of wrapper.getAttributeKeys() ) {
  1078. // Classes and styles should be checked separately.
  1079. if ( key === 'class' || key === 'style' ) {
  1080. continue;
  1081. }
  1082. // Move only these attributes that are not present - other are similar.
  1083. if ( !toWrap.hasAttribute( key ) ) {
  1084. toWrap.setAttribute( key, wrapper.getAttribute( key ) );
  1085. }
  1086. }
  1087. for ( const key of wrapper.getStyleNames() ) {
  1088. if ( !toWrap.hasStyle( key ) ) {
  1089. toWrap.setStyle( key, wrapper.getStyle( key ) );
  1090. }
  1091. }
  1092. for ( const key of wrapper.getClassNames() ) {
  1093. if ( !toWrap.hasClass( key ) ) {
  1094. toWrap.addClass( key );
  1095. }
  1096. }
  1097. return true;
  1098. }
  1099. // Unwraps {@link module:engine/view/attributeelement~AttributeElement AttributeElement} from another by removing corresponding attributes,
  1100. // classes and styles. All attributes, classes and styles from wrapper should be present inside element being unwrapped.
  1101. //
  1102. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  1103. // @param {module:engine/view/attributeelement~AttributeElement} toUnwrap AttributeElement to unwrap using wrapper element.
  1104. // @returns {Boolean} Returns `true` if elements are unwrapped.
  1105. function unwrapAttributeElement( wrapper, toUnwrap ) {
  1106. // Can't unwrap if name or priority differs.
  1107. if ( wrapper.name !== toUnwrap.name || wrapper.priority !== toUnwrap.priority ) {
  1108. return false;
  1109. }
  1110. // Check if AttributeElement has all wrapper attributes.
  1111. for ( const key of wrapper.getAttributeKeys() ) {
  1112. // Classes and styles should be checked separately.
  1113. if ( key === 'class' || key === 'style' ) {
  1114. continue;
  1115. }
  1116. // If some attributes are missing or different we cannot unwrap.
  1117. if ( !toUnwrap.hasAttribute( key ) || toUnwrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  1118. return false;
  1119. }
  1120. }
  1121. // Check if AttributeElement has all wrapper classes.
  1122. if ( !toUnwrap.hasClass( ...wrapper.getClassNames() ) ) {
  1123. return false;
  1124. }
  1125. // Check if AttributeElement has all wrapper styles.
  1126. for ( const key of wrapper.getStyleNames() ) {
  1127. // If some styles are missing or different we cannot unwrap.
  1128. if ( !toUnwrap.hasStyle( key ) || toUnwrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  1129. return false;
  1130. }
  1131. }
  1132. // Remove all wrapper's attributes from unwrapped element.
  1133. for ( const key of wrapper.getAttributeKeys() ) {
  1134. // Classes and styles should be checked separately.
  1135. if ( key === 'class' || key === 'style' ) {
  1136. continue;
  1137. }
  1138. toUnwrap.removeAttribute( key );
  1139. }
  1140. // Remove all wrapper's classes from unwrapped element.
  1141. toUnwrap.removeClass( ...wrapper.getClassNames() );
  1142. // Remove all wrapper's styles from unwrapped element.
  1143. toUnwrap.removeStyle( ...wrapper.getStyleNames() );
  1144. return true;
  1145. }
  1146. // Returns `true` if range is located in same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}
  1147. // (`start` and `end` positions are located inside same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}),
  1148. // starts on 0 offset and ends after last child node.
  1149. //
  1150. // @param {module:engine/view/range~Range} Range
  1151. // @returns {Boolean}
  1152. function rangeSpansOnAllChildren( range ) {
  1153. return range.start.parent == range.end.parent && range.start.parent.is( 'attributeElement' ) &&
  1154. range.start.offset === 0 && range.end.offset === range.start.parent.childCount;
  1155. }
  1156. // Checks if provided nodes are valid to insert. Checks if each node is an instance of
  1157. // {@link module:engine/view/text~Text Text} or {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  1158. // {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  1159. // {@link module:engine/view/emptyelement~EmptyElement EmptyElement} or
  1160. // {@link module:engine/view/uielement~UIElement UIElement}.
  1161. //
  1162. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  1163. // contains instances that are not {@link module:engine/view/text~Text Texts},
  1164. // {@link module:engine/view/emptyelement~EmptyElement EmptyElements},
  1165. // {@link module:engine/view/uielement~UIElement UIElements},
  1166. // {@link module:engine/view/attributeelement~AttributeElement AttributeElements} or
  1167. // {@link module:engine/view/containerelement~ContainerElement ContainerElements}.
  1168. //
  1169. // @param Iterable.<module:engine/view/text~Text|module:engine/view/attributeelement~AttributeElement
  1170. // |module:engine/view/containerelement~ContainerElement> nodes
  1171. function validateNodesToInsert( nodes ) {
  1172. for ( const node of nodes ) {
  1173. if ( !validNodesToInsert.some( ( validNode => node instanceof validNode ) ) ) { // eslint-disable-line no-use-before-define
  1174. /**
  1175. * Inserted nodes should be valid to insert. of {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  1176. * {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  1177. * {@link module:engine/view/emptyelement~EmptyElement EmptyElement},
  1178. * {@link module:engine/view/uielement~UIElement UIElement}, {@link module:engine/view/text~Text Text}.
  1179. *
  1180. * @error view-writer-insert-invalid-node
  1181. */
  1182. throw new CKEditorError( 'view-writer-insert-invalid-node' );
  1183. }
  1184. if ( !node.is( 'text' ) ) {
  1185. validateNodesToInsert( node.getChildren() );
  1186. }
  1187. }
  1188. }
  1189. const validNodesToInsert = [ Text, AttributeElement, ContainerElement, EmptyElement, UIElement ];
  1190. // Checks if node is ContainerElement or DocumentFragment, because in most cases they should be treated the same way.
  1191. //
  1192. // @param {module:engine/view/node~Node} node
  1193. // @returns {Boolean} Returns `true` if node is instance of ContainerElement or DocumentFragment.
  1194. function isContainerOrFragment( node ) {
  1195. return node && ( node.is( 'containerElement' ) || node.is( 'documentFragment' ) );
  1196. }
  1197. // Checks if {@link module:engine/view/range~Range#start range start} and {@link module:engine/view/range~Range#end range end} are placed
  1198. // inside same {@link module:engine/view/containerelement~ContainerElement container element}.
  1199. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when validation fails.
  1200. //
  1201. // @param {module:engine/view/range~Range} range
  1202. function validateRangeContainer( range ) {
  1203. const startContainer = getParentContainer( range.start );
  1204. const endContainer = getParentContainer( range.end );
  1205. if ( !startContainer || !endContainer || startContainer !== endContainer ) {
  1206. /**
  1207. * Range container is invalid. This can happen if {@link module:engine/view/range~Range#start range start} and
  1208. * {@link module:engine/view/range~Range#end range end} positions are not placed inside same container or
  1209. * parent container for these positions cannot be found.
  1210. *
  1211. * @error view-writer-invalid-range-container
  1212. */
  1213. throw new CKEditorError( 'view-writer-invalid-range-container' );
  1214. }
  1215. }