8
0

writer.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import Position from './position.js';
  6. import ContainerElement from './containerelement.js';
  7. import AttributeElement from './attributeelement.js';
  8. import Text from './text.js';
  9. import Range from './range.js';
  10. import CKEditorError from '../../utils/ckeditorerror.js';
  11. import DocumentFragment from './documentfragment.js';
  12. import isIterable from '../../utils/isiterable.js';
  13. /**
  14. * Contains functions used for composing view tree.
  15. *
  16. * @namespace engine.view.writer
  17. */
  18. export default {
  19. breakAttributes,
  20. breakContainer,
  21. mergeAttributes,
  22. mergeContainers,
  23. insert,
  24. remove,
  25. move,
  26. wrap,
  27. wrapPosition,
  28. unwrap,
  29. rename
  30. };
  31. /**
  32. * Breaks attribute nodes at provided position or at boundaries of provided range. It breaks attribute elements inside
  33. * up to a container element.
  34. *
  35. * In following examples `<p>` is a container, `<b>` and `<u>` are attribute nodes:
  36. *
  37. * <p>foo<b><u>bar{}</u></b></p> -> <p>foo<b><u>bar</u></b>[]</p>
  38. * <p>foo<b><u>{}bar</u></b></p> -> <p>foo{}<b><u>bar</u></b></p>
  39. * <p>foo<b><u>b{}ar</u></b></p> -> <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  40. * <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>
  41. *
  42. * **Note:** {@link engine.view.DocumentFragment DocumentFragment} is treated like a container.
  43. *
  44. * **Note:** Difference between {@link engine.view.writer.breakAttributes breakAttributes} and
  45. * {@link engine.view.writer.breakContainer breakContainer} is that `breakAttributes` breaks all
  46. * {@link engine.view.AttributeElement attribute elements} that are ancestors of given `position`, up to the first
  47. * encountered {@link engine.view.ContainerElement container element}. `breakContainer` assumes that given `position`
  48. * is directly in container element and breaks that container element.
  49. *
  50. * Throws {@link utils.CKEditorError CKEditorError} `view-writer-invalid-range-container` when {@link engine.view.Range#start start}
  51. * and {@link engine.view.Range#end end} positions of a passed range are not placed inside same parent container.
  52. *
  53. * @see engine.view.AttributeElement
  54. * @see engine.view.ContainerElement
  55. * @see engine.view.writer.breakContainer
  56. * @function engine.view.writer.breakAttributes
  57. * @param {engine.view.Position|engine.view.Range} positionOrRange Position where to break attribute elements.
  58. * @returns {engine.view.Position|engine.view.Range} New position or range, after breaking the attribute elements.
  59. */
  60. export function breakAttributes( positionOrRange ) {
  61. if ( positionOrRange instanceof Position ) {
  62. return _breakAttributes( positionOrRange );
  63. } else {
  64. return _breakAttributesRange( positionOrRange );
  65. }
  66. }
  67. /**
  68. * Breaks {@link engine.view.ContainerElement container view element} into two, at the given position. Position
  69. * has to be directly inside container element and cannot be in root. Does not break if position is at the beginning
  70. * or at the end of it's parent element.
  71. *
  72. * <p>foo^bar</p> -> <p>foo</p><p>bar</p>
  73. * <div><p>foo</p>^<p>bar</p></div> -> <div><p>foo</p></div><div><p>bar</p></div>
  74. * <p>^foobar</p> -> ^<p>foobar</p>
  75. * <p>foobar^</p> -> <p>foobar</p>^
  76. *
  77. * **Note:** Difference between {@link engine.view.writer.breakAttributes breakAttributes} and
  78. * {@link engine.view.writer.breakContainer breakContainer} is that `breakAttributes` breaks all
  79. * {@link engine.view.AttributeElement attribute elements} that are ancestors of given `position`, up to the first
  80. * encountered {@link engine.view.ContainerElement container element}. `breakContainer` assumes that given `position`
  81. * is directly in container element and breaks that container element.
  82. *
  83. * @see engine.view.AttributeElement
  84. * @see engine.view.ContainerElement
  85. * @see engine.view.writer.breakAttributes
  86. * @function engine.view.writer.breakContainer
  87. * @param {engine.view.Position} position Position where to break element.
  88. * @returns {engine.view.Position} Position between broken elements. If element has not been broken, the returned position
  89. * is placed either before it or after it.
  90. */
  91. export function breakContainer( position ) {
  92. const element = position.parent;
  93. if ( !( element instanceof ContainerElement ) ) {
  94. /**
  95. * Trying to break an element which is not a container element.
  96. *
  97. * @error view-writer-break-non-container-element
  98. */
  99. throw new CKEditorError( 'view-writer-break-non-container-element: Trying to break an element which is not a container element.' );
  100. }
  101. if ( !element.parent ) {
  102. /**
  103. * Trying to break root element.
  104. *
  105. * @error view-writer-break-root
  106. */
  107. throw new CKEditorError( 'view-writer-break-root: Trying to break root element.' );
  108. }
  109. if ( position.isAtStart ) {
  110. return Position.createBefore( element );
  111. } else if ( !position.isAtEnd ) {
  112. const newElement = element.clone( false );
  113. insert( Position.createAfter( element ), newElement );
  114. const sourceRange = new Range( position, Position.createAt( element, 'end' ) );
  115. const targetPosition = new Position( newElement, 0 );
  116. move( sourceRange, targetPosition );
  117. }
  118. return Position.createAfter( element );
  119. }
  120. /**
  121. * Merges {@link engine.view.AttributeElement attribute elements}. It also merges text nodes if needed.
  122. * Only {@link engine.view.AttributeElement#isSimilar similar} attribute elements can be merged.
  123. *
  124. * In following examples `<p>` is a container and `<b>` is an attribute element:
  125. *
  126. * <p>foo[]bar</p> -> <p>foo{}bar</p>
  127. * <p><b>foo</b>[]<b>bar</b> -> <p><b>foo{}bar</b></b>
  128. * <p><b foo="bar">a</b>[]<b foo="baz">b</b> -> <p><b foo="bar">a</b>[]<b foo="baz">b</b>
  129. *
  130. * It will also take care about empty attributes when merging:
  131. *
  132. * <p><b>[]</b></p> -> <p>[]</p>
  133. * <p><b>foo</b><i>[]</i><b>bar</b></p> -> <p><b>foo{}bar</b></p>
  134. *
  135. * **Note:** Difference between {@link engine.view.writer.mergeAttributes mergeAttributes} and
  136. * {@link engine.view.writer.mergeContainers mergeContainers} is that `mergeAttributes` merges two
  137. * {@link engine.view.AttributeElement attribute elements} or {@link engine.view.Text text nodes}
  138. * while `mergeContainer` merges two {@link engine.view.ContainerElement container elements}.
  139. *
  140. * @see engine.view.AttributeElement
  141. * @see engine.view.ContainerElement
  142. * @see engine.view.writer.mergeContainers
  143. * @function engine.view.writer.mergeAttributes
  144. * @param {engine.view.Position} position Merge position.
  145. * @returns {engine.view.Position} Position after merge.
  146. */
  147. export function mergeAttributes( position ) {
  148. const positionOffset = position.offset;
  149. const positionParent = position.parent;
  150. // When inside text node - nothing to merge.
  151. if ( positionParent instanceof Text ) {
  152. return position;
  153. }
  154. // When inside empty attribute - remove it.
  155. if ( positionParent instanceof AttributeElement && positionParent.childCount === 0 ) {
  156. const parent = positionParent.parent;
  157. const offset = positionParent.index;
  158. positionParent.remove();
  159. return mergeAttributes( new Position( parent, offset ) );
  160. }
  161. const nodeBefore = positionParent.getChild( positionOffset - 1 );
  162. const nodeAfter = positionParent.getChild( positionOffset );
  163. // Position should be placed between two nodes.
  164. if ( !nodeBefore || !nodeAfter ) {
  165. return position;
  166. }
  167. // When one or both nodes are containers - no attributes to merge.
  168. if ( ( nodeBefore instanceof ContainerElement ) || ( nodeAfter instanceof ContainerElement ) ) {
  169. return position;
  170. }
  171. // When position is between two text nodes.
  172. if ( nodeBefore instanceof Text && nodeAfter instanceof Text ) {
  173. return mergeTextNodes( nodeBefore, nodeAfter );
  174. }
  175. // When selection is between same nodes.
  176. else if ( nodeBefore.isSimilar( nodeAfter ) ) {
  177. // Move all children nodes from node placed after selection and remove that node.
  178. const count = nodeBefore.childCount;
  179. nodeBefore.appendChildren( nodeAfter.getChildren() );
  180. nodeAfter.remove();
  181. // New position is located inside the first node, before new nodes.
  182. // Call this method recursively to merge again if needed.
  183. return mergeAttributes( new Position( nodeBefore, count ) );
  184. }
  185. return position;
  186. }
  187. /**
  188. * Merges two {@link engine.view.ContainerElement container elements} that are before and after given position.
  189. * Precisely, the element after the position is removed and it's contents are moved to element before the position.
  190. *
  191. * <p>foo</p>^<p>bar</p> -> <p>foo^bar</p>
  192. * <div>foo</div>^<p>bar</p> -> <div>foo^bar</div>
  193. *
  194. * **Note:** Difference between {@link engine.view.writer.mergeAttributes mergeAttributes} and
  195. * {@link engine.view.writer.mergeContainers mergeContainers} is that `mergeAttributes` merges two
  196. * {@link engine.view.AttributeElement attribute elements} or {@link engine.view.Text text nodes}
  197. * while `mergeContainer` merges two {@link engine.view.ContainerElement container elements}.
  198. *
  199. * @see engine.view.AttributeElement
  200. * @see engine.view.ContainerElement
  201. * @see engine.view.writer.mergeAttributes
  202. * @function engine.view.writer.mergeContainers
  203. * @param {engine.view.Position} position Merge position.
  204. * @returns {engine.view.Position} Position after merge.
  205. */
  206. export function mergeContainers( position ) {
  207. const prev = position.nodeBefore;
  208. const next = position.nodeAfter;
  209. if ( !prev || !next || !( prev instanceof ContainerElement ) || !( next instanceof ContainerElement ) ) {
  210. /**
  211. * Element before and after given position cannot be merged.
  212. *
  213. * @error view-writer-merge-containers-invalid-position
  214. */
  215. throw new CKEditorError( 'view-writer-merge-containers-invalid-position: ' +
  216. 'Element before and after given position cannot be merged.' );
  217. }
  218. const lastChild = prev.getChild( prev.childCount - 1 );
  219. const newPosition = lastChild instanceof Text ? Position.createAt( lastChild, 'end' ) : Position.createAt( prev, 'end' );
  220. move( Range.createIn( next ), Position.createAt( prev, 'end' ) );
  221. remove( Range.createOn( next ) );
  222. return newPosition;
  223. }
  224. /**
  225. * Insert node or nodes at specified position. Takes care about breaking attributes before insertion
  226. * and merging them afterwards.
  227. *
  228. * Throws {@link utils.CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  229. * contains instances that are not {@link engine.view.Text Texts},
  230. * {@link engine.view.AttributeElement AttributeElements} or
  231. * {@link engine.view.ContainerElement ContainerElements}.
  232. *
  233. * @function engine.view.writer.insert
  234. * @param {engine.view.Position} position Insertion position.
  235. * @param {engine.view.Text|engine.view.AttributeElement|engine.view.ContainerElement
  236. * |Iterable.<engine.view.Text|engine.view.AttributeElement|engine.view.ContainerElement>} nodes Node or
  237. * nodes to insert.
  238. * @returns {engine.view.Range} Range around inserted nodes.
  239. */
  240. export function insert( position, nodes ) {
  241. nodes = isIterable( nodes ) ? [ ...nodes ] : [ nodes ];
  242. // Check if nodes to insert are instances of AttributeElements, ContainerElements or Text.
  243. validateNodesToInsert( nodes );
  244. const container = getParentContainer( position );
  245. if ( !container ) {
  246. /**
  247. * Position's parent container cannot be found.
  248. *
  249. * @error view-writer-invalid-position-container
  250. */
  251. throw new CKEditorError( 'view-writer-invalid-position-container' );
  252. }
  253. const insertionPosition = _breakAttributes( position, true );
  254. const length = container.insertChildren( insertionPosition.offset, nodes );
  255. const endPosition = insertionPosition.getShiftedBy( length );
  256. const start = mergeAttributes( insertionPosition );
  257. // When no nodes were inserted - return collapsed range.
  258. if ( length === 0 ) {
  259. return new Range( start, start );
  260. } else {
  261. // If start position was merged - move end position.
  262. if ( !start.isEqual( insertionPosition ) ) {
  263. endPosition.offset--;
  264. }
  265. const end = mergeAttributes( endPosition );
  266. return new Range( start, end );
  267. }
  268. }
  269. /**
  270. * Removes provided range from the container.
  271. *
  272. * Throws {@link utils.CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  273. * {@link engine.view.Range#start start} and {@link engine.view.Range#end end} positions are not placed inside
  274. * same parent container.
  275. *
  276. * @function engine.view.writer.remove
  277. * @param {engine.view.Range} range Range to remove from container. After removing, it will be updated
  278. * to a collapsed range showing the new position.
  279. * @returns {engine.view.DocumentFragment} Document fragment containing removed nodes.
  280. */
  281. export function remove( range ) {
  282. validateRangeContainer( range );
  283. // If range is collapsed - nothing to remove.
  284. if ( range.isCollapsed ) {
  285. return new DocumentFragment();
  286. }
  287. // Break attributes at range start and end.
  288. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  289. const parentContainer = breakStart.parent;
  290. const count = breakEnd.offset - breakStart.offset;
  291. // Remove nodes in range.
  292. const removed = parentContainer.removeChildren( breakStart.offset, count );
  293. // Merge after removing.
  294. const mergePosition = mergeAttributes( breakStart );
  295. range.start = mergePosition;
  296. range.end = Position.createFromPosition( mergePosition );
  297. // Return removed nodes.
  298. return new DocumentFragment( removed );
  299. }
  300. /**
  301. * Moves nodes from provided range to target position.
  302. *
  303. * Throws {@link utils.CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  304. * {@link engine.view.Range#start start} and {@link engine.view.Range#end end} positions are not placed inside
  305. * same parent container.
  306. *
  307. * @function engine.view.writer.move
  308. * @param {engine.view.Range} sourceRange Range containing nodes to move.
  309. * @param {engine.view.Position} targetPosition Position to insert.
  310. * @returns {engine.view.Range} Range in target container. Inserted nodes are placed between
  311. * {@link engine.view.Range#start start} and {@link engine.view.Range#end end} positions.
  312. */
  313. export function move( sourceRange, targetPosition ) {
  314. if ( sourceRange.start.parent == targetPosition.parent ) {
  315. targetPosition.offset -= sourceRange.end.offset - sourceRange.start.offset;
  316. }
  317. const nodes = remove( sourceRange );
  318. return insert( targetPosition, nodes );
  319. }
  320. /**
  321. * Wraps elements within range with provided {@link engine.view.AttributeElement AttributeElement}.
  322. *
  323. * Throws {@link utils.CKEditorError} `view-writer-invalid-range-container` when {@link engine.view.Range#start}
  324. * and {@link engine.view.Range#end} positions are not placed inside same parent container.
  325. * Throws {@link utils.CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  326. * an instance of {engine.view.AttributeElement AttributeElement}.
  327. *
  328. * @function engine.view.writer.wrap
  329. * @param {engine.view.Range} range Range to wrap.
  330. * @param {engine.view.AttributeElement} attribute Attribute element to use as wrapper.
  331. */
  332. export function wrap( range, attribute ) {
  333. if ( !( attribute instanceof AttributeElement ) ) {
  334. /**
  335. * Attribute element need to be instance of attribute element.
  336. *
  337. * @error view-writer-wrap-invalid-attribute
  338. */
  339. throw new CKEditorError( 'view-writer-wrap-invalid-attribute' );
  340. }
  341. validateRangeContainer( range );
  342. // If range is collapsed - nothing to wrap.
  343. if ( range.isCollapsed ) {
  344. return range;
  345. }
  346. // Range around one element.
  347. if ( range.end.isEqual( range.start.getShiftedBy( 1 ) ) ) {
  348. const node = range.start.nodeAfter;
  349. if ( node instanceof AttributeElement && wrapAttributeElement( attribute, node ) ) {
  350. return range;
  351. }
  352. }
  353. // Range is inside single attribute and spans on all children.
  354. if ( rangeSpansOnAllChildren( range ) && wrapAttributeElement( attribute, range.start.parent ) ) {
  355. const parent = range.start.parent.parent;
  356. const index = range.start.parent.index;
  357. return Range.createFromParentsAndOffsets( parent, index, parent, index + 1 ) ;
  358. }
  359. // Break attributes at range start and end.
  360. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  361. const parentContainer = breakStart.parent;
  362. // Unwrap children located between break points.
  363. const unwrappedRange = unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  364. // Wrap all children with attribute.
  365. const newRange = wrapChildren( parentContainer, unwrappedRange.start.offset, unwrappedRange.end.offset, attribute );
  366. // Merge attributes at the both ends and return a new range.
  367. const start = mergeAttributes( newRange.start );
  368. // If start position was merged - move end position back.
  369. if ( !start.isEqual( newRange.start ) ) {
  370. newRange.end.offset--;
  371. }
  372. const end = mergeAttributes( newRange.end );
  373. return new Range( start, end );
  374. }
  375. /**
  376. * Wraps position with provided attribute. Returns new position after wrapping. This method will also merge newly
  377. * added attribute with its siblings whenever possible.
  378. *
  379. * Throws {@link utils.CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  380. * an instance of {engine.view.AttributeElement AttributeElement}.
  381. *
  382. * @function engine.view.writer.wrapPosition
  383. * @param {engine.view.Position} position
  384. * @param {engine.view.AttributeElement} attribute
  385. * @returns {Position} New position after wrapping.
  386. */
  387. export function wrapPosition( position, attribute ) {
  388. if ( !( attribute instanceof AttributeElement ) ) {
  389. /**
  390. * Attribute element need to be instance of attribute element.
  391. *
  392. * @error view-writer-wrap-invalid-attribute
  393. */
  394. throw new CKEditorError( 'view-writer-wrap-invalid-attribute' );
  395. }
  396. // Return same position when trying to wrap with attribute similar to position parent.
  397. if ( attribute.isSimilar( position.parent ) ) {
  398. return movePositionToTextNode( Position.createFromPosition( position ) );
  399. }
  400. // When position is inside text node - break it and place new position between two text nodes.
  401. if ( position.parent instanceof Text ) {
  402. position = breakTextNode( position );
  403. }
  404. // Create fake element that will represent position, and will not be merged with other attributes.
  405. const fakePosition = new AttributeElement();
  406. fakePosition.priority = Number.POSITIVE_INFINITY;
  407. fakePosition.isSimilar = () => false;
  408. // Insert fake element in position location.
  409. position.parent.insertChildren( position.offset, fakePosition );
  410. // Range around inserted fake attribute element.
  411. const wrapRange = new Range( position, position.getShiftedBy( 1 ) );
  412. // Wrap fake element with attribute (it will also merge if possible).
  413. wrap( wrapRange, attribute );
  414. // Remove fake element and place new position there.
  415. const newPosition = new Position( fakePosition.parent, fakePosition.index );
  416. fakePosition.remove();
  417. // If position is placed between text nodes - merge them and return position inside.
  418. const nodeBefore = newPosition.nodeBefore;
  419. const nodeAfter = newPosition.nodeAfter;
  420. if ( nodeBefore instanceof Text && nodeAfter instanceof Text ) {
  421. return mergeTextNodes( nodeBefore, nodeAfter );
  422. }
  423. // If position is next to text node - move position inside.
  424. return movePositionToTextNode( newPosition );
  425. }
  426. /**
  427. * Unwraps nodes within provided range from attribute element.
  428. *
  429. * Throws {@link utils.CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  430. * {@link engine.view.Range#start start} and {@link engine.view.Range#end end} positions are not placed inside
  431. * same parent container.
  432. *
  433. * @function engine.view.writer.unwrap
  434. * @param {engine.view.Range} range
  435. * @param {engine.view.AttributeElement} element
  436. */
  437. export function unwrap( range, attribute ) {
  438. if ( !( attribute instanceof AttributeElement ) ) {
  439. /**
  440. * Attribute element need to be instance of attribute element.
  441. *
  442. * @error view-writer-unwrap-invalid-attribute
  443. */
  444. throw new CKEditorError( 'view-writer-unwrap-invalid-attribute' );
  445. }
  446. validateRangeContainer( range );
  447. // If range is collapsed - nothing to unwrap.
  448. if ( range.isCollapsed ) {
  449. return range;
  450. }
  451. // Range around one element - check if AttributeElement can be unwrapped partially when it's not similar.
  452. // For example:
  453. // <b class="foo bar" title="baz"></b> unwrap with: <b class="foo"></p> result: <b class"bar" title="baz"></b>
  454. if ( range.end.isEqual( range.start.getShiftedBy( 1 ) ) ) {
  455. const node = range.start.nodeAfter;
  456. // Unwrap single attribute element.
  457. if ( !attribute.isSimilar( node ) && node instanceof AttributeElement && unwrapAttributeElement( attribute, node ) ) {
  458. return range;
  459. }
  460. }
  461. // Break attributes at range start and end.
  462. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  463. const parentContainer = breakStart.parent;
  464. // Unwrap children located between break points.
  465. const newRange = unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  466. // Merge attributes at the both ends and return a new range.
  467. const start = mergeAttributes( newRange.start );
  468. // If start position was merged - move end position back.
  469. if ( !start.isEqual( newRange.start ) ) {
  470. newRange.end.offset--;
  471. }
  472. const end = mergeAttributes( newRange.end );
  473. return new Range( start, end );
  474. }
  475. /**
  476. * Renames element by creating a copy of renamed element but with changed name and then moving contents of the
  477. * old element to the new one. Keep in mind that this will invalidate all {@link engine.view.Position positions} which
  478. * has renamed element as {@link engine.view.Position#parent a parent}.
  479. *
  480. * New element has to be created because `Element#tagName` property in DOM is readonly.
  481. *
  482. * Since this function creates a new element and removes the given one, the new element is returned to keep reference.
  483. *
  484. * @param {engine.view.ContainerElement} viewElement Element to be renamed.
  485. * @param {String} newName New name for element.
  486. */
  487. export function rename( viewElement, newName ) {
  488. const newElement = new ContainerElement( newName, viewElement.getAttributes() );
  489. insert( Position.createAfter( viewElement ), newElement );
  490. move( Range.createIn( viewElement ), Position.createAt( newElement ) );
  491. remove( Range.createOn( viewElement ) );
  492. return newElement;
  493. }
  494. // Returns first parent container of specified {@link engine.view.Position Position}.
  495. // Position's parent node is checked as first, then next parents are checked.
  496. // Note that {@link engine.view.DocumentFragment DocumentFragment} is treated like a container.
  497. //
  498. // @param {engine.view.Position} position Position used as a start point to locate parent container.
  499. // @returns {engine.view.ContainerElement|engine.view.DocumentFragment|undefined} Parent container element or
  500. // `undefined` if container is not found.
  501. function getParentContainer( position ) {
  502. let parent = position.parent;
  503. while ( !isContainerOrFragment( parent ) ) {
  504. if ( !parent ) {
  505. return undefined;
  506. }
  507. parent = parent.parent;
  508. }
  509. return parent;
  510. }
  511. // Function used by both public breakAttributes (without splitting text nodes) and by other methods (with
  512. // splitting text nodes).
  513. //
  514. // @param {engine.view.Range} range Range which `start` and `end` positions will be used to break attributes.
  515. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  516. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  517. // which then fixes view state. Defaults to `false`.
  518. // @returns {engine.view.Range} New range with located at break positions.
  519. function _breakAttributesRange( range, forceSplitText = false ) {
  520. const rangeStart = range.start;
  521. const rangeEnd = range.end;
  522. validateRangeContainer( range );
  523. // Break at the collapsed position. Return new collapsed range.
  524. if ( range.isCollapsed ) {
  525. const position = _breakAttributes( range.start, forceSplitText );
  526. return new Range( position, position );
  527. }
  528. const breakEnd = _breakAttributes( rangeEnd, forceSplitText );
  529. const count = breakEnd.parent.childCount;
  530. const breakStart = _breakAttributes( rangeStart, forceSplitText );
  531. // Calculate new break end offset.
  532. breakEnd.offset += breakEnd.parent.childCount - count;
  533. return new Range( breakStart, breakEnd );
  534. }
  535. // Function used by public breakAttributes (without splitting text nodes) and by other methods (with
  536. // splitting text nodes).
  537. //
  538. // @param {engine.view.Position} position Position where to break attributes.
  539. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  540. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  541. // which then fixes view state. Defaults to `false`.
  542. // @returns {engine.view.Position} New position after breaking the attributes.
  543. function _breakAttributes( position, forceSplitText = false ) {
  544. const positionOffset = position.offset;
  545. const positionParent = position.parent;
  546. // There are no attributes to break and text nodes breaking is not forced.
  547. if ( !forceSplitText && positionParent instanceof Text && isContainerOrFragment( positionParent.parent ) ) {
  548. return Position.createFromPosition( position );
  549. }
  550. // Position's parent is container, so no attributes to break.
  551. if ( isContainerOrFragment( positionParent ) ) {
  552. return Position.createFromPosition( position );
  553. }
  554. // Break text and start again in new position.
  555. if ( positionParent instanceof Text ) {
  556. return _breakAttributes( breakTextNode( position ), forceSplitText );
  557. }
  558. const length = positionParent.childCount;
  559. // <p>foo<b><u>bar{}</u></b></p>
  560. // <p>foo<b><u>bar</u>[]</b></p>
  561. // <p>foo<b><u>bar</u></b>[]</p>
  562. if ( positionOffset == length ) {
  563. const newPosition = new Position( positionParent.parent, positionParent.index + 1 );
  564. return _breakAttributes( newPosition, forceSplitText );
  565. } else
  566. // <p>foo<b><u>{}bar</u></b></p>
  567. // <p>foo<b>[]<u>bar</u></b></p>
  568. // <p>foo{}<b><u>bar</u></b></p>
  569. if ( positionOffset === 0 ) {
  570. const newPosition = new Position( positionParent.parent, positionParent.index );
  571. return _breakAttributes( newPosition, forceSplitText );
  572. }
  573. // <p>foo<b><u>b{}ar</u></b></p>
  574. // <p>foo<b><u>b[]ar</u></b></p>
  575. // <p>foo<b><u>b</u>[]<u>ar</u></b></p>
  576. // <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  577. else {
  578. const offsetAfter = positionParent.index + 1;
  579. // Break element.
  580. const clonedNode = positionParent.clone();
  581. // Insert cloned node to position's parent node.
  582. positionParent.parent.insertChildren( offsetAfter, clonedNode );
  583. // Get nodes to move.
  584. const count = positionParent.childCount - positionOffset;
  585. const nodesToMove = positionParent.removeChildren( positionOffset, count );
  586. // Move nodes to cloned node.
  587. clonedNode.appendChildren( nodesToMove );
  588. // Create new position to work on.
  589. const newPosition = new Position( positionParent.parent, offsetAfter );
  590. return _breakAttributes( newPosition, forceSplitText );
  591. }
  592. }
  593. // Unwraps children from provided `attribute`. Only children contained in `parent` element between
  594. // `startOffset` and `endOffset` will be unwrapped.
  595. //
  596. // @param {engine.view.Element} parent
  597. // @param {Number} startOffset
  598. // @param {Number} endOffset
  599. // @param {engine.view.Element} attribute
  600. function unwrapChildren( parent, startOffset, endOffset, attribute ) {
  601. let i = startOffset;
  602. const unwrapPositions = [];
  603. // Iterate over each element between provided offsets inside parent.
  604. while ( i < endOffset ) {
  605. const child = parent.getChild( i );
  606. // If attributes are the similar, then unwrap.
  607. if ( child.isSimilar( attribute ) ) {
  608. const unwrapped = child.getChildren();
  609. const count = child.childCount;
  610. // Replace wrapper element with its children
  611. child.remove();
  612. parent.insertChildren( i, unwrapped );
  613. // Save start and end position of moved items.
  614. unwrapPositions.push(
  615. new Position( parent, i ),
  616. new Position( parent, i + count )
  617. );
  618. // Skip elements that were unwrapped. Assuming that there won't be another element to unwrap in child
  619. // elements.
  620. i += count;
  621. endOffset += count - 1;
  622. } else {
  623. // If other nested attribute is found start unwrapping there.
  624. if ( child instanceof AttributeElement ) {
  625. unwrapChildren( child, 0, child.childCount, attribute );
  626. }
  627. i++;
  628. }
  629. }
  630. // Merge at each unwrap.
  631. let offsetChange = 0;
  632. for ( let position of unwrapPositions ) {
  633. position.offset -= offsetChange;
  634. // Do not merge with elements outside selected children.
  635. if ( position.offset == startOffset || position.offset == endOffset ) {
  636. continue;
  637. }
  638. const newPosition = mergeAttributes( position );
  639. // If nodes were merged - other merge offsets will change.
  640. if ( !newPosition.isEqual( position ) ) {
  641. offsetChange++;
  642. endOffset--;
  643. }
  644. }
  645. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  646. }
  647. // Wraps children with provided `attribute`. Only children contained in `parent` element between
  648. // `startOffset` and `endOffset` will be wrapped.
  649. //
  650. // @param {engine.view.Element} parent
  651. // @param {Number} startOffset
  652. // @param {Number} endOffset
  653. // @param {engine.view.Element} attribute
  654. function wrapChildren( parent, startOffset, endOffset, attribute ) {
  655. let i = startOffset;
  656. const wrapPositions = [];
  657. while ( i < endOffset ) {
  658. const child = parent.getChild( i );
  659. const isText = child instanceof Text;
  660. const isAttribute = child instanceof AttributeElement;
  661. // Wrap text or attributes with higher or equal priority.
  662. if ( isText || ( isAttribute && attribute.priority <= child.priority ) ) {
  663. // Clone attribute.
  664. const newAttribute = attribute.clone();
  665. // Wrap current node with new attribute;
  666. child.remove();
  667. newAttribute.appendChildren( child );
  668. parent.insertChildren( i, newAttribute );
  669. wrapPositions.push( new Position( parent, i ) );
  670. } else {
  671. // If other nested attribute is found start wrapping there.
  672. if ( child instanceof AttributeElement ) {
  673. wrapChildren( child, 0, child.childCount, attribute );
  674. }
  675. }
  676. i++;
  677. }
  678. // Merge at each wrap.
  679. let offsetChange = 0;
  680. for ( let position of wrapPositions ) {
  681. // Do not merge with elements outside selected children.
  682. if ( position.offset == startOffset ) {
  683. continue;
  684. }
  685. const newPosition = mergeAttributes( position );
  686. // If nodes were merged - other merge offsets will change.
  687. if ( !newPosition.isEqual( position ) ) {
  688. offsetChange++;
  689. endOffset--;
  690. }
  691. }
  692. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  693. }
  694. // Returns new position that is moved to near text node. Returns same position if there is no text node before of after
  695. // specified position.
  696. //
  697. // <p>foo[]</p> -> <p>foo{}</p>
  698. // <p>[]foo</p> -> <p>{}foo</p>
  699. //
  700. // @param {engine.view.Position} position
  701. // @returns {engine.view.Position} Position located inside text node or same position if there is no text nodes
  702. // before or after position location.
  703. function movePositionToTextNode( position ) {
  704. const nodeBefore = position.nodeBefore;
  705. if ( nodeBefore && nodeBefore instanceof Text ) {
  706. return new Position( nodeBefore, nodeBefore.data.length );
  707. }
  708. const nodeAfter = position.nodeAfter;
  709. if ( nodeAfter && nodeAfter instanceof Text ) {
  710. return new Position( nodeAfter, 0 );
  711. }
  712. return position;
  713. }
  714. // Breaks text node into two text nodes when possible.
  715. //
  716. // <p>foo{}bar</p> -> <p>foo[]bar</p>
  717. // <p>{}foobar</p> -> <p>[]foobar</p>
  718. // <p>foobar{}</p> -> <p>foobar[]</p>
  719. //
  720. // @param {engine.view.Position} position Position that need to be placed inside text node.
  721. // @returns {engine.view.Position} New position after breaking text node.
  722. function breakTextNode( position ) {
  723. if ( position.offset == position.parent.data.length ) {
  724. return new Position( position.parent.parent, position.parent.index + 1 );
  725. }
  726. if ( position.offset === 0 ) {
  727. return new Position( position.parent.parent, position.parent.index );
  728. }
  729. // Get part of the text that need to be moved.
  730. const textToMove = position.parent.data.slice( position.offset );
  731. // Leave rest of the text in position's parent.
  732. position.parent.data = position.parent.data.slice( 0, position.offset );
  733. // Insert new text node after position's parent text node.
  734. position.parent.parent.insertChildren( position.parent.index + 1, new Text( textToMove ) );
  735. // Return new position between two newly created text nodes.
  736. return new Position( position.parent.parent, position.parent.index + 1 );
  737. }
  738. // Merges two text nodes into first node. Removes second node and returns merge position.
  739. //
  740. // @param {engine.view.Text} t1 First text node to merge. Data from second text node will be moved at the end of
  741. // this text node.
  742. // @param {engine.view.Text} t2 Second text node to merge. This node will be removed after merging.
  743. // @returns {engine.view.Position} Position after merging text nodes.
  744. function mergeTextNodes( t1, t2 ) {
  745. // Merge text data into first text node and remove second one.
  746. const nodeBeforeLength = t1.data.length;
  747. t1.data += t2.data;
  748. t2.remove();
  749. return new Position( t1, nodeBeforeLength );
  750. }
  751. // Wraps one {@link engine.view.AttributeElement AttributeElement} into another by merging them if possible.
  752. // Two AttributeElements can be merged when there is no attribute or style conflicts between them.
  753. // When merging is possible - all attributes, styles and classes are moved from wrapper element to element being
  754. // wrapped.
  755. //
  756. // @param {engine.view.AttributeElement} wrapper Wrapper AttributeElement.
  757. // @param {engine.view.AttributeElement} toWrap AttributeElement to wrap using wrapper element.
  758. // @returns {Boolean} Returns `true` if elements are merged.
  759. function wrapAttributeElement( wrapper, toWrap ) {
  760. // Can't merge if name or priority differs.
  761. if ( wrapper.name !== toWrap.name || wrapper.priority !== toWrap.priority ) {
  762. return false;
  763. }
  764. // Check if attributes can be merged.
  765. for ( let key of wrapper.getAttributeKeys() ) {
  766. // Classes and styles should be checked separately.
  767. if ( key === 'class' || key === 'style' ) {
  768. continue;
  769. }
  770. // If some attributes are different we cannot wrap.
  771. if ( toWrap.hasAttribute( key ) && toWrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  772. return false;
  773. }
  774. }
  775. // Check if styles can be merged.
  776. for ( let key of wrapper.getStyleNames() ) {
  777. if ( toWrap.hasStyle( key ) && toWrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  778. return false;
  779. }
  780. }
  781. // Move all attributes/classes/styles from wrapper to wrapped AttributeElement.
  782. for ( let key of wrapper.getAttributeKeys() ) {
  783. // Classes and styles should be checked separately.
  784. if ( key === 'class' || key === 'style' ) {
  785. continue;
  786. }
  787. // Move only these attributes that are not present - other are similar.
  788. if ( !toWrap.hasAttribute( key ) ) {
  789. toWrap.setAttribute( key, wrapper.getAttribute( key ) );
  790. }
  791. }
  792. for ( let key of wrapper.getStyleNames() ) {
  793. if ( !toWrap.hasStyle( key ) ) {
  794. toWrap.setStyle( key, wrapper.getStyle( key ) );
  795. }
  796. }
  797. for ( let key of wrapper.getClassNames() ) {
  798. if ( !toWrap.hasClass( key ) ) {
  799. toWrap.addClass( key );
  800. }
  801. }
  802. return true;
  803. }
  804. // Unwraps {@link engine.view.AttributeElement AttributeElement} from another by removing corresponding attributes,
  805. // classes and styles. All attributes, classes and styles from wrapper should be present inside element being unwrapped.
  806. //
  807. // @param {engine.view.AttributeElement} wrapper Wrapper AttributeElement.
  808. // @param {engine.view.AttributeElement} toUnwrap AttributeElement to unwrap using wrapper element.
  809. // @returns {Boolean} Returns `true` if elements are unwrapped.
  810. function unwrapAttributeElement( wrapper, toUnwrap ) {
  811. // Can't unwrap if name or priority differs.
  812. if ( wrapper.name !== toUnwrap.name || wrapper.priority !== toUnwrap.priority ) {
  813. return false;
  814. }
  815. // Check if AttributeElement has all wrapper attributes.
  816. for ( let key of wrapper.getAttributeKeys() ) {
  817. // Classes and styles should be checked separately.
  818. if ( key === 'class' || key === 'style' ) {
  819. continue;
  820. }
  821. // If some attributes are missing or different we cannot unwrap.
  822. if ( !toUnwrap.hasAttribute( key ) || toUnwrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  823. return false;
  824. }
  825. }
  826. // Check if AttributeElement has all wrapper classes.
  827. if ( !toUnwrap.hasClass( ...wrapper.getClassNames() ) ) {
  828. return false;
  829. }
  830. // Check if AttributeElement has all wrapper styles.
  831. for ( let key of wrapper.getStyleNames() ) {
  832. // If some styles are missing or different we cannot unwrap.
  833. if ( !toUnwrap.hasStyle( key ) || toUnwrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  834. return false;
  835. }
  836. }
  837. // Remove all wrapper's attributes from unwrapped element.
  838. for ( let key of wrapper.getAttributeKeys() ) {
  839. // Classes and styles should be checked separately.
  840. if ( key === 'class' || key === 'style' ) {
  841. continue;
  842. }
  843. toUnwrap.removeAttribute( key );
  844. }
  845. // Remove all wrapper's classes from unwrapped element.
  846. toUnwrap.removeClass( ...wrapper.getClassNames() );
  847. // Remove all wrapper's styles from unwrapped element.
  848. toUnwrap.removeStyle( ...wrapper.getStyleNames() );
  849. return true;
  850. }
  851. // Returns `true` if range is located in same {@link engine.view.AttributeElement AttributeElement}
  852. // (`start` and `end` positions are located inside same {@link engine.view.AttributeElement AttributeElement}),
  853. // starts on 0 offset and ends after last child node.
  854. //
  855. // @param {engine.view.Range} Range
  856. // @returns {Boolean}
  857. function rangeSpansOnAllChildren( range ) {
  858. return range.start.parent == range.end.parent && range.start.parent instanceof AttributeElement &&
  859. range.start.offset === 0 && range.end.offset === range.start.parent.childCount;
  860. }
  861. // Checks if provided nodes are valid to insert. Checks if each node is an instance of
  862. // {@link engine.view.Text Text} or {@link engine.view.AttributeElement AttributeElement} or
  863. // {@link engine.view.ContainerElement ContainerElement}.
  864. //
  865. // Throws {@link utils.CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  866. // contains instances that are not {@link engine.view.Text Texts},
  867. // {@link engine.view.AttributeElement AttributeElements} or
  868. // {@link engine.view.ContainerElement ContainerElements}.
  869. //
  870. // @param Iterable.<engine.view.Text|engine.view.AttributeElement|engine.view.ContainerElement> nodes
  871. function validateNodesToInsert( nodes ) {
  872. for ( let node of nodes ) {
  873. if ( !( node instanceof Text || node instanceof AttributeElement || node instanceof ContainerElement ) ) {
  874. /**
  875. * Inserted nodes should be instance of {@link engine.view.AttributeElement AttributeElement},
  876. * {@link engine.view.ContainerElement ContainerElement} or {@link engine.view.Text Text}.
  877. *
  878. * @error view-writer-insert-invalid-node
  879. */
  880. throw new CKEditorError( 'view-writer-insert-invalid-node' );
  881. }
  882. if ( !( node instanceof Text ) ) {
  883. validateNodesToInsert( node.getChildren() );
  884. }
  885. }
  886. }
  887. // Checks if node is ContainerElement or DocumentFragment, because in most cases they should be treated the same way.
  888. //
  889. // @param {engine.view.Node} node
  890. // @returns {Boolean} Returns `true` if node is instance of ContainerElement or DocumentFragment.
  891. function isContainerOrFragment( node ) {
  892. return node instanceof ContainerElement || node instanceof DocumentFragment;
  893. }
  894. // Checks if {@link engine.view.Range#start range start} and {@link engine.view.Range#end range end} are placed
  895. // inside same {@link engine.view.ContainerElement container}.
  896. // Throws {@link utils.CKEditorError CKEditorError} `view-writer-invalid-range-container` when validation fails.
  897. //
  898. // @param {engine.view.Range} range
  899. function validateRangeContainer( range ) {
  900. const startContainer = getParentContainer( range.start );
  901. const endContainer = getParentContainer( range.end );
  902. if ( !startContainer || !endContainer || startContainer !== endContainer ) {
  903. /**
  904. * Range container is invalid. This can happen if {@link engine.view.Range#start range start} and
  905. * {@link engine.view.Range#end range end} positions are not placed inside same container or
  906. * parent container for these positions cannot be found.
  907. *
  908. * @error view-writer-invalid-range-container
  909. */
  910. throw new CKEditorError( 'view-writer-invalid-range-container' );
  911. }
  912. }