8
0

downcasthelpers.js 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * Contains downcast (model-to-view) converters for {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}.
  7. *
  8. * @module engine/conversion/downcasthelpers
  9. */
  10. import ModelRange from '../model/range';
  11. import ModelSelection from '../model/selection';
  12. import ModelElement from '../model/element';
  13. import ViewAttributeElement from '../view/attributeelement';
  14. import DocumentSelection from '../model/documentselection';
  15. import ConversionHelpers from './conversionhelpers';
  16. import { cloneDeep } from 'lodash-es';
  17. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  18. /**
  19. * Downcast conversion helper functions.
  20. *
  21. * @extends module:engine/conversion/conversionhelpers~ConversionHelpers
  22. */
  23. export default class DowncastHelpers extends ConversionHelpers {
  24. /**
  25. * Model element to view element conversion helper.
  26. *
  27. * This conversion results in creating a view element. For example, model `<paragraph>Foo</paragraph>` becomes `<p>Foo</p>` in the view.
  28. *
  29. * editor.conversion.for( 'downcast' ).elementToElement( {
  30. * model: 'paragraph',
  31. * view: 'p'
  32. * } );
  33. *
  34. * editor.conversion.for( 'downcast' ).elementToElement( {
  35. * model: 'paragraph',
  36. * view: 'div',
  37. * converterPriority: 'high'
  38. * } );
  39. *
  40. * editor.conversion.for( 'downcast' ).elementToElement( {
  41. * model: 'fancyParagraph',
  42. * view: {
  43. * name: 'p',
  44. * classes: 'fancy'
  45. * }
  46. * } );
  47. *
  48. * editor.conversion.for( 'downcast' ).elementToElement( {
  49. * model: 'heading',
  50. * view: ( modelElement, conversionApi ) => {
  51. * const { writer } = conversionApi;
  52. *
  53. * return writer.createContainerElement( 'h' + modelElement.getAttribute( 'level' ) );
  54. * }
  55. * } );
  56. *
  57. * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
  58. * to the conversion process.
  59. *
  60. * You can read more about element-to-element conversion in the
  61. * {@glink framework/guides/deep-dive/conversion/custom-element-conversion Custom element conversion} guide.
  62. *
  63. * @method #elementToElement
  64. * @param {Object} config Conversion configuration.
  65. * @param {String} config.model The name of the model element to convert.
  66. * @param {module:engine/view/elementdefinition~ElementDefinition|Function} config.view A view element definition or a function
  67. * that takes the model element and {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
  68. * as parameters and returns a view container element.
  69. * @returns {module:engine/conversion/downcasthelpers~DowncastHelpers}
  70. */
  71. elementToElement( config ) {
  72. return this.add( downcastElementToElement( config ) );
  73. }
  74. /**
  75. * Model attribute to view element conversion helper.
  76. *
  77. * This conversion results in wrapping view nodes with a view attribute element. For example, a model text node with
  78. * `"Foo"` as data and the `bold` attribute becomes `<strong>Foo</strong>` in the view.
  79. *
  80. * editor.conversion.for( 'downcast' ).attributeToElement( {
  81. * model: 'bold',
  82. * view: 'strong'
  83. * } );
  84. *
  85. * editor.conversion.for( 'downcast' ).attributeToElement( {
  86. * model: 'bold',
  87. * view: 'b',
  88. * converterPriority: 'high'
  89. * } );
  90. *
  91. * editor.conversion.for( 'downcast' ).attributeToElement( {
  92. * model: 'invert',
  93. * view: {
  94. * name: 'span',
  95. * classes: [ 'font-light', 'bg-dark' ]
  96. * }
  97. * } );
  98. *
  99. * editor.conversion.for( 'downcast' ).attributeToElement( {
  100. * model: {
  101. * key: 'fontSize',
  102. * values: [ 'big', 'small' ]
  103. * },
  104. * view: {
  105. * big: {
  106. * name: 'span',
  107. * styles: {
  108. * 'font-size': '1.2em'
  109. * }
  110. * },
  111. * small: {
  112. * name: 'span',
  113. * styles: {
  114. * 'font-size': '0.8em'
  115. * }
  116. * }
  117. * }
  118. * } );
  119. *
  120. * editor.conversion.for( 'downcast' ).attributeToElement( {
  121. * model: 'bold',
  122. * view: ( modelAttributeValue, conversionApi ) => {
  123. * const { writer } = conversionApi;
  124. *
  125. * return writer.createAttributeElement( 'span', {
  126. * style: 'font-weight:' + modelAttributeValue
  127. * } );
  128. * }
  129. * } );
  130. *
  131. * editor.conversion.for( 'downcast' ).attributeToElement( {
  132. * model: {
  133. * key: 'color',
  134. * name: '$text'
  135. * },
  136. * view: ( modelAttributeValue, conversionApi ) => {
  137. * const { writer } = conversionApi;
  138. *
  139. * return writer.createAttributeElement( 'span', {
  140. * style: 'color:' + modelAttributeValue
  141. * } );
  142. * }
  143. * } );
  144. *
  145. * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
  146. * to the conversion process.
  147. *
  148. * @method #attributeToElement
  149. * @param {Object} config Conversion configuration.
  150. * @param {String|Object} config.model The key of the attribute to convert from or a `{ key, values }` object. `values` is an array
  151. * of `String`s with possible values if the model attribute is an enumerable.
  152. * @param {module:engine/view/elementdefinition~ElementDefinition|Function|Object} config.view A view element definition or a function
  153. * that takes the model attribute value and
  154. * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as parameters and returns a view
  155. * attribute element. If `config.model.values` is given, `config.view` should be an object assigning values from `config.model.values`
  156. * to view element definitions or functions.
  157. * @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  158. * @returns {module:engine/conversion/downcasthelpers~DowncastHelpers}
  159. */
  160. attributeToElement( config ) {
  161. return this.add( downcastAttributeToElement( config ) );
  162. }
  163. /**
  164. * Model attribute to view attribute conversion helper.
  165. *
  166. * This conversion results in adding an attribute to a view node, basing on an attribute from a model node. For example,
  167. * `<image src='foo.jpg'></image>` is converted to `<img src='foo.jpg'></img>`.
  168. *
  169. * editor.conversion.for( 'downcast' ).attributeToAttribute( {
  170. * model: 'source',
  171. * view: 'src'
  172. * } );
  173. *
  174. * editor.conversion.for( 'downcast' ).attributeToAttribute( {
  175. * model: 'source',
  176. * view: 'href',
  177. * converterPriority: 'high'
  178. * } );
  179. *
  180. * editor.conversion.for( 'downcast' ).attributeToAttribute( {
  181. * model: {
  182. * name: 'image',
  183. * key: 'source'
  184. * },
  185. * view: 'src'
  186. * } );
  187. *
  188. * editor.conversion.for( 'downcast' ).attributeToAttribute( {
  189. * model: {
  190. * name: 'styled',
  191. * values: [ 'dark', 'light' ]
  192. * },
  193. * view: {
  194. * dark: {
  195. * key: 'class',
  196. * value: [ 'styled', 'styled-dark' ]
  197. * },
  198. * light: {
  199. * key: 'class',
  200. * value: [ 'styled', 'styled-light' ]
  201. * }
  202. * }
  203. * } );
  204. *
  205. * editor.conversion.for( 'downcast' ).attributeToAttribute( {
  206. * model: 'styled',
  207. * view: modelAttributeValue => ( {
  208. * key: 'class',
  209. * value: 'styled-' + modelAttributeValue
  210. * } )
  211. * } );
  212. *
  213. * **Note**: Downcasting to a style property requires providing `value` as an object:
  214. *
  215. * editor.conversion.for( 'downcast' ).attributeToAttribute( {
  216. * model: 'lineHeight',
  217. * view: modelAttributeValue => ( {
  218. * key: 'style',
  219. * value: {
  220. * 'line-height': modelAttributeValue,
  221. * 'border-bottom': '1px dotted #ba2'
  222. * }
  223. * } )
  224. * } );
  225. *
  226. * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
  227. * to the conversion process.
  228. *
  229. * @method #attributeToAttribute
  230. * @param {Object} config Conversion configuration.
  231. * @param {String|Object} config.model The key of the attribute to convert from or a `{ key, values, [ name ] }` object describing
  232. * the attribute key, possible values and, optionally, an element name to convert from.
  233. * @param {String|Object|Function} config.view A view attribute key, or a `{ key, value }` object or a function that takes
  234. * the model attribute value and {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
  235. * as parameters and returns a `{ key, value }` object. If `key` is `'class'`, `value` can be a `String` or an
  236. * array of `String`s. If `key` is `'style'`, `value` is an object with key-value pairs. In other cases, `value` is a `String`.
  237. * If `config.model.values` is set, `config.view` should be an object assigning values from `config.model.values` to
  238. * `{ key, value }` objects or a functions.
  239. * @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  240. * @returns {module:engine/conversion/downcasthelpers~DowncastHelpers}
  241. */
  242. attributeToAttribute( config ) {
  243. return this.add( downcastAttributeToAttribute( config ) );
  244. }
  245. /**
  246. * Model marker to view element conversion helper.
  247. *
  248. * **Note**: This method should be used only for editing downcast. For data downcast, use
  249. * {@link #markerToData `#markerToData()`} that produces valid HTML data.
  250. *
  251. * This conversion results in creating a view element on the boundaries of the converted marker. If the converted marker
  252. * is collapsed, only one element is created. For example, model marker set like this: `<paragraph>F[oo b]ar</paragraph>`
  253. * becomes `<p>F<span data-marker="search"></span>oo b<span data-marker="search"></span>ar</p>` in the view.
  254. *
  255. * editor.conversion.for( 'editingDowncast' ).markerToElement( {
  256. * model: 'search',
  257. * view: 'marker-search'
  258. * } );
  259. *
  260. * editor.conversion.for( 'editingDowncast' ).markerToElement( {
  261. * model: 'search',
  262. * view: 'search-result',
  263. * converterPriority: 'high'
  264. * } );
  265. *
  266. * editor.conversion.for( 'editingDowncast' ).markerToElement( {
  267. * model: 'search',
  268. * view: {
  269. * name: 'span',
  270. * attributes: {
  271. * 'data-marker': 'search'
  272. * }
  273. * }
  274. * } );
  275. *
  276. * editor.conversion.for( 'editingDowncast' ).markerToElement( {
  277. * model: 'search',
  278. * view: ( markerData, conversionApi ) => {
  279. * const { writer } = conversionApi;
  280. *
  281. * return writer.createUIElement( 'span', {
  282. * 'data-marker': 'search',
  283. * 'data-start': markerData.isOpening
  284. * } );
  285. * }
  286. * } );
  287. *
  288. * If a function is passed as the `config.view` parameter, it will be used to generate both boundary elements. The function
  289. * receives the `data` object and {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
  290. * as a parameters and should return an instance of the
  291. * {@link module:engine/view/uielement~UIElement view UI element}. The `data` object and
  292. * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi `conversionApi`} are passed from
  293. * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker}. Additionally,
  294. * the `data.isOpening` parameter is passed, which is set to `true` for the marker start boundary element, and `false` to
  295. * the marker end boundary element.
  296. *
  297. * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
  298. * to the conversion process.
  299. *
  300. * @method #markerToElement
  301. * @param {Object} config Conversion configuration.
  302. * @param {String} config.model The name of the model marker (or model marker group) to convert.
  303. * @param {module:engine/view/elementdefinition~ElementDefinition|Function} config.view A view element definition or a function that
  304. * takes the model marker data and {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
  305. * as a parameters and returns a view UI element.
  306. * @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  307. * @returns {module:engine/conversion/downcasthelpers~DowncastHelpers}
  308. */
  309. markerToElement( config ) {
  310. return this.add( downcastMarkerToElement( config ) );
  311. }
  312. /**
  313. * Model marker to highlight conversion helper.
  314. *
  315. * This conversion results in creating a highlight on view nodes. For this kind of conversion,
  316. * {@link module:engine/conversion/downcasthelpers~HighlightDescriptor} should be provided.
  317. *
  318. * For text nodes, a `<span>` {@link module:engine/view/attributeelement~AttributeElement} is created and it wraps all text nodes
  319. * in the converted marker range. For example, a model marker set like this: `<paragraph>F[oo b]ar</paragraph>` becomes
  320. * `<p>F<span class="comment">oo b</span>ar</p>` in the view.
  321. *
  322. * {@link module:engine/view/containerelement~ContainerElement} may provide a custom way of handling highlight. Most often,
  323. * the element itself is given classes and attributes described in the highlight descriptor (instead of being wrapped in `<span>`).
  324. * For example, a model marker set like this: `[<image src="foo.jpg"></image>]` becomes `<img src="foo.jpg" class="comment"></img>`
  325. * in the view.
  326. *
  327. * For container elements, the conversion is two-step. While the converter processes the highlight descriptor and passes it
  328. * to a container element, it is the container element instance itself that applies values from the highlight descriptor.
  329. * So, in a sense, the converter takes care of stating what should be applied on what, while the element decides how to apply that.
  330. *
  331. * editor.conversion.for( 'downcast' ).markerToHighlight( { model: 'comment', view: { classes: 'comment' } } );
  332. *
  333. * editor.conversion.for( 'downcast' ).markerToHighlight( {
  334. * model: 'comment',
  335. * view: { classes: 'new-comment' },
  336. * converterPriority: 'high'
  337. * } );
  338. *
  339. * editor.conversion.for( 'downcast' ).markerToHighlight( {
  340. * model: 'comment',
  341. * view: ( data, converstionApi ) => {
  342. * // Assuming that the marker name is in a form of comment:commentType.
  343. * const commentType = data.markerName.split( ':' )[ 1 ];
  344. *
  345. * return {
  346. * classes: [ 'comment', 'comment-' + commentType ]
  347. * };
  348. * }
  349. * } );
  350. *
  351. * If a function is passed as the `config.view` parameter, it will be used to generate the highlight descriptor. The function
  352. * receives the `data` object and {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API}
  353. * as a parameters and should return a
  354. * {@link module:engine/conversion/downcasthelpers~HighlightDescriptor highlight descriptor}.
  355. * The `data` object properties are passed from {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker}.
  356. *
  357. * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
  358. * to the conversion process.
  359. *
  360. * @method #markerToHighlight
  361. * @param {Object} config Conversion configuration.
  362. * @param {String} config.model The name of the model marker (or model marker group) to convert.
  363. * @param {module:engine/conversion/downcasthelpers~HighlightDescriptor|Function} config.view A highlight descriptor
  364. * that will be used for highlighting or a function that takes the model marker data and
  365. * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as a parameters
  366. * and returns a highlight descriptor.
  367. * @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  368. * @returns {module:engine/conversion/downcasthelpers~DowncastHelpers}
  369. */
  370. markerToHighlight( config ) {
  371. return this.add( downcastMarkerToHighlight( config ) );
  372. }
  373. /**
  374. * Model marker converter for data downcast.
  375. *
  376. * This conversion creates a representation for model marker boundaries in the view:
  377. *
  378. * * If the marker boundary is at a position where text nodes are allowed, then a view element with the specified tag name
  379. * and `name` attribute is added at this position.
  380. * * In other cases, a specified attribute is set on a view element that is before or after the marker boundary.
  381. *
  382. * Typically, marker names use the `group:uniqueId:otherData` convention. For example: `comment:e34zfk9k2n459df53sjl34:zx32c`.
  383. * The default configuration for this conversion is that the first part is the `group` part and the rest of
  384. * the marker name becomes the `name` part.
  385. *
  386. * Tag and attribute names and values are generated from the marker name:
  387. *
  388. * * Templates for attributes are `data-[group]-start-before="[name]"`, `data-[group]-start-after="[name]"`,
  389. * `data-[group]-end-before="[name]"` and `data-[group]-end-after="[name]"`.
  390. * * Templates for view elements are `<[group]-start name="[name]">` and `<[group]-end name="[name]">`.
  391. *
  392. * Attributes mark whether the given marker's start or end boundary is before or after the given element.
  393. * Attributes `data-[group]-start-before` and `data-[group]-end-after` are favored.
  394. * The other two are used when the former two cannot be used.
  395. *
  396. * The conversion configuration can take a function that will generate different group and name parts.
  397. * If such function is set as the `config.view` parameter, it is passed a marker name and it is expected to return an object with two
  398. * properties: `group` and `name`. If the function returns a falsy value, the conversion will not take place.
  399. *
  400. * Basic usage:
  401. *
  402. * // Using the default conversion.
  403. * // In this case, all markers whose name starts with 'comment:' will be converted.
  404. * // The `group` parameter will be set to `comment`.
  405. * // The `name` parameter will be the rest of the marker name (without `:`).
  406. * editor.conversion.for( 'dataDowncast' ).markerToData( {
  407. * model: 'comment'
  408. * } );
  409. *
  410. * An example of a view that may be generated by this conversion (assuming a marker with the name `comment:commentId:uid` marked
  411. * by `[]`):
  412. *
  413. * // Model:
  414. * <paragraph>Foo[bar</paragraph>
  415. * <image src="abc.jpg"></image>]
  416. *
  417. * // View:
  418. * <p>Foo<comment-start name="commentId:uid"></comment-start>bar</p>
  419. * <figure data-comment-end-after="commentId:uid" class="image"><img src="abc.jpg" /></figure>
  420. *
  421. * In the example above, the comment starts before "bar" and ends after the image.
  422. *
  423. * If the `name` part is empty, the following view may be generated:
  424. *
  425. * <p>Foo <myMarker-start></myMarker-start>bar</p>
  426. * <figure data-myMarker-end-after="" class="image"><img src="abc.jpg" /></figure>
  427. *
  428. * **Note:** A situation where some markers have the `name` part and some do not have it is incorrect and should be avoided.
  429. *
  430. * Examples where `data-group-start-after` and `data-group-end-before` are used:
  431. *
  432. * // Model:
  433. * <blockQuote>[]<paragraph>Foo</paragraph></blockQuote>
  434. *
  435. * // View:
  436. * <blockquote><p data-group-end-before="name" data-group-start-before="name">Foo</p></blockquote>
  437. *
  438. * Similarly, when a marker is collapsed after the last element:
  439. *
  440. * // Model:
  441. * <blockQuote><paragraph>Foo</paragraph>[]</blockQuote>
  442. *
  443. * // View:
  444. * <blockquote><p data-group-end-after="name" data-group-start-after="name">Foo</p></blockquote>
  445. *
  446. * When there are multiple markers from the same group stored in the same attribute of the same element, their
  447. * name parts are put together in the attribute value, for example: `data-group-start-before="name1,name2,name3"`.
  448. *
  449. * Other examples of usage:
  450. *
  451. * // Using a custom function which is the same as the default conversion:
  452. * editor.conversion.for( 'dataDowncast' ).markerToData( {
  453. * model: 'comment'
  454. * view: markerName => ( {
  455. * group: 'comment',
  456. * name: markerName.substr( 8 ) // Removes 'comment:' part.
  457. * } )
  458. * } );
  459. *
  460. * // Using the converter priority:
  461. * editor.conversion.for( 'dataDowncast' ).markerToData( {
  462. * model: 'comment'
  463. * view: markerName => ( {
  464. * group: 'comment',
  465. * name: markerName.substr( 8 ) // Removes 'comment:' part.
  466. * } ),
  467. * converterPriority: 'high'
  468. * } );
  469. *
  470. * This kind of conversion is useful for saving data into the database, so it should be used in the data conversion pipeline.
  471. *
  472. * See {@link module:engine/conversion/conversion~Conversion#for `conversion.for()`} to learn how to add a converter
  473. * to the conversion process.
  474. *
  475. * @method #markerToData
  476. * @param {Object} config Conversion configuration.
  477. * @param {String} config.model The name of the model marker (or model marker group) to convert.
  478. * @param {Function} [config.view] A function that takes the model marker name and
  479. * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi downcast conversion API} as a parameters
  480. * and returns an object with the `group` and `name` properties.
  481. * @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  482. * @returns {module:engine/conversion/downcasthelpers~DowncastHelpers}
  483. */
  484. markerToData( config ) {
  485. return this.add( downcastMarkerToData( config ) );
  486. }
  487. }
  488. /**
  489. * Function factory that creates a default downcast converter for text insertion changes.
  490. *
  491. * The converter automatically consumes the corresponding value from the consumables list and stops the event (see
  492. * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}).
  493. *
  494. * modelDispatcher.on( 'insert:$text', insertText() );
  495. *
  496. * @returns {Function} Insert text event converter.
  497. */
  498. export function insertText() {
  499. return ( evt, data, conversionApi ) => {
  500. if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
  501. return;
  502. }
  503. const viewWriter = conversionApi.writer;
  504. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  505. const viewText = viewWriter.createText( data.item.data );
  506. viewWriter.insert( viewPosition, viewText );
  507. };
  508. }
  509. /**
  510. * Function factory that creates a default downcast converter for node remove changes.
  511. *
  512. * modelDispatcher.on( 'remove', remove() );
  513. *
  514. * @returns {Function} Remove event converter.
  515. */
  516. export function remove() {
  517. return ( evt, data, conversionApi ) => {
  518. // Find view range start position by mapping model position at which the remove happened.
  519. const viewStart = conversionApi.mapper.toViewPosition( data.position );
  520. const modelEnd = data.position.getShiftedBy( data.length );
  521. const viewEnd = conversionApi.mapper.toViewPosition( modelEnd, { isPhantom: true } );
  522. const viewRange = conversionApi.writer.createRange( viewStart, viewEnd );
  523. // Trim the range to remove in case some UI elements are on the view range boundaries.
  524. const removed = conversionApi.writer.remove( viewRange.getTrimmed() );
  525. // After the range is removed, unbind all view elements from the model.
  526. // Range inside view document fragment is used to unbind deeply.
  527. for ( const child of conversionApi.writer.createRangeIn( removed ).getItems() ) {
  528. conversionApi.mapper.unbindViewElement( child );
  529. }
  530. };
  531. }
  532. /**
  533. * Creates a `<span>` {@link module:engine/view/attributeelement~AttributeElement view attribute element} from the information
  534. * provided by the {@link module:engine/conversion/downcasthelpers~HighlightDescriptor highlight descriptor} object. If a priority
  535. * is not provided in the descriptor, the default priority will be used.
  536. *
  537. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  538. * @param {module:engine/conversion/downcasthelpers~HighlightDescriptor} descriptor
  539. * @returns {module:engine/view/attributeelement~AttributeElement}
  540. */
  541. export function createViewElementFromHighlightDescriptor( writer, descriptor ) {
  542. const viewElement = writer.createAttributeElement( 'span', descriptor.attributes );
  543. if ( descriptor.classes ) {
  544. viewElement._addClass( descriptor.classes );
  545. }
  546. if ( descriptor.priority ) {
  547. viewElement._priority = descriptor.priority;
  548. }
  549. viewElement._id = descriptor.id;
  550. return viewElement;
  551. }
  552. /**
  553. * Function factory that creates a converter which converts a non-collapsed {@link module:engine/model/selection~Selection model selection}
  554. * to a {@link module:engine/view/documentselection~DocumentSelection view selection}. The converter consumes appropriate
  555. * value from the `consumable` object and maps model positions from the selection to view positions.
  556. *
  557. * modelDispatcher.on( 'selection', convertRangeSelection() );
  558. *
  559. * @returns {Function} Selection converter.
  560. */
  561. export function convertRangeSelection() {
  562. return ( evt, data, conversionApi ) => {
  563. const selection = data.selection;
  564. if ( selection.isCollapsed ) {
  565. return;
  566. }
  567. if ( !conversionApi.consumable.consume( selection, 'selection' ) ) {
  568. return;
  569. }
  570. const viewRanges = [];
  571. for ( const range of selection.getRanges() ) {
  572. const viewRange = conversionApi.mapper.toViewRange( range );
  573. viewRanges.push( viewRange );
  574. }
  575. conversionApi.writer.setSelection( viewRanges, { backward: selection.isBackward } );
  576. };
  577. }
  578. /**
  579. * Function factory that creates a converter which converts a collapsed {@link module:engine/model/selection~Selection model selection} to
  580. * a {@link module:engine/view/documentselection~DocumentSelection view selection}. The converter consumes appropriate
  581. * value from the `consumable` object, maps the model selection position to the view position and breaks
  582. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} at the selection position.
  583. *
  584. * modelDispatcher.on( 'selection', convertCollapsedSelection() );
  585. *
  586. * An example of the view state before and after converting the collapsed selection:
  587. *
  588. * <p><strong>f^oo<strong>bar</p>
  589. * -> <p><strong>f</strong>^<strong>oo</strong>bar</p>
  590. *
  591. * By breaking attribute elements like `<strong>`, the selection is in a correct element. Then, when the selection attribute is
  592. * converted, broken attributes might be merged again, or the position where the selection is may be wrapped
  593. * with different, appropriate attribute elements.
  594. *
  595. * See also {@link module:engine/conversion/downcasthelpers~clearAttributes} which does a clean-up
  596. * by merging attributes.
  597. *
  598. * @returns {Function} Selection converter.
  599. */
  600. export function convertCollapsedSelection() {
  601. return ( evt, data, conversionApi ) => {
  602. const selection = data.selection;
  603. if ( !selection.isCollapsed ) {
  604. return;
  605. }
  606. if ( !conversionApi.consumable.consume( selection, 'selection' ) ) {
  607. return;
  608. }
  609. const viewWriter = conversionApi.writer;
  610. const modelPosition = selection.getFirstPosition();
  611. const viewPosition = conversionApi.mapper.toViewPosition( modelPosition );
  612. const brokenPosition = viewWriter.breakAttributes( viewPosition );
  613. viewWriter.setSelection( brokenPosition );
  614. };
  615. }
  616. /**
  617. * Function factory that creates a converter which clears artifacts after the previous
  618. * {@link module:engine/model/selection~Selection model selection} conversion. It removes all empty
  619. * {@link module:engine/view/attributeelement~AttributeElement view attribute elements} and merges sibling attributes at all start and end
  620. * positions of all ranges.
  621. *
  622. * <p><strong>^</strong></p>
  623. * -> <p>^</p>
  624. *
  625. * <p><strong>foo</strong>^<strong>bar</strong>bar</p>
  626. * -> <p><strong>foo^bar<strong>bar</p>
  627. *
  628. * <p><strong>foo</strong><em>^</em><strong>bar</strong>bar</p>
  629. * -> <p><strong>foo^bar<strong>bar</p>
  630. *
  631. * This listener should be assigned before any converter for the new selection:
  632. *
  633. * modelDispatcher.on( 'selection', clearAttributes() );
  634. *
  635. * See {@link module:engine/conversion/downcasthelpers~convertCollapsedSelection}
  636. * which does the opposite by breaking attributes in the selection position.
  637. *
  638. * @returns {Function} Selection converter.
  639. */
  640. export function clearAttributes() {
  641. return ( evt, data, conversionApi ) => {
  642. const viewWriter = conversionApi.writer;
  643. const viewSelection = viewWriter.document.selection;
  644. for ( const range of viewSelection.getRanges() ) {
  645. // Not collapsed selection should not have artifacts.
  646. if ( range.isCollapsed ) {
  647. // Position might be in the node removed by the view writer.
  648. if ( range.end.parent.isAttached() ) {
  649. conversionApi.writer.mergeAttributes( range.start );
  650. }
  651. }
  652. }
  653. viewWriter.setSelection( null );
  654. };
  655. }
  656. /**
  657. * Function factory that creates a converter which converts set/change/remove attribute changes from the model to the view.
  658. * It can also be used to convert selection attributes. In that case, an empty attribute element will be created and the
  659. * selection will be put inside it.
  660. *
  661. * Attributes from the model are converted to a view element that will be wrapping these view nodes that are bound to
  662. * model elements having the given attribute. This is useful for attributes like `bold` that may be set on text nodes in the model
  663. * but are represented as an element in the view:
  664. *
  665. * [paragraph] MODEL ====> VIEW <p>
  666. * |- a {bold: true} |- <b>
  667. * |- b {bold: true} | |- ab
  668. * |- c |- c
  669. *
  670. * Passed `Function` will be provided with the attribute value and then all the parameters of the
  671. * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute` event}.
  672. * It is expected that the function returns an {@link module:engine/view/element~Element}.
  673. * The result of the function will be the wrapping element.
  674. * When the provided `Function` does not return any element, no conversion will take place.
  675. *
  676. * The converter automatically consumes the corresponding value from the consumables list and stops the event (see
  677. * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}).
  678. *
  679. * modelDispatcher.on( 'attribute:bold', wrap( ( modelAttributeValue, { writer } ) => {
  680. * return writer.createAttributeElement( 'strong' );
  681. * } );
  682. *
  683. * @protected
  684. * @param {Function} elementCreator Function returning a view element that will be used for wrapping.
  685. * @returns {Function} Set/change attribute converter.
  686. */
  687. export function wrap( elementCreator ) {
  688. return ( evt, data, conversionApi ) => {
  689. // Recreate current wrapping node. It will be used to unwrap view range if the attribute value has changed
  690. // or the attribute was removed.
  691. const oldViewElement = elementCreator( data.attributeOldValue, conversionApi );
  692. // Create node to wrap with.
  693. const newViewElement = elementCreator( data.attributeNewValue, conversionApi );
  694. if ( !oldViewElement && !newViewElement ) {
  695. return;
  696. }
  697. if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
  698. return;
  699. }
  700. const viewWriter = conversionApi.writer;
  701. const viewSelection = viewWriter.document.selection;
  702. if ( data.item instanceof ModelSelection || data.item instanceof DocumentSelection ) {
  703. // Selection attribute conversion.
  704. viewWriter.wrap( viewSelection.getFirstRange(), newViewElement );
  705. } else {
  706. // Node attribute conversion.
  707. let viewRange = conversionApi.mapper.toViewRange( data.range );
  708. // First, unwrap the range from current wrapper.
  709. if ( data.attributeOldValue !== null && oldViewElement ) {
  710. viewRange = viewWriter.unwrap( viewRange, oldViewElement );
  711. }
  712. if ( data.attributeNewValue !== null && newViewElement ) {
  713. viewWriter.wrap( viewRange, newViewElement );
  714. }
  715. }
  716. };
  717. }
  718. /**
  719. * Function factory that creates a converter which converts node insertion changes from the model to the view.
  720. * The function passed will be provided with all the parameters of the dispatcher's
  721. * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert` event}.
  722. * It is expected that the function returns an {@link module:engine/view/element~Element}.
  723. * The result of the function will be inserted into the view.
  724. *
  725. * The converter automatically consumes the corresponding value from the consumables list, stops the event (see
  726. * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}) and binds the model and view elements.
  727. *
  728. * downcastDispatcher.on(
  729. * 'insert:myElem',
  730. * insertElement( ( modelItem, { writer } ) => {
  731. * const text = writer.createText( 'myText' );
  732. * const myElem = writer.createElement( 'myElem', { myAttr: 'my-' + modelItem.getAttribute( 'myAttr' ) }, text );
  733. *
  734. * // Do something fancy with `myElem` using `modelItem` or other parameters.
  735. *
  736. * return myElem;
  737. * }
  738. * ) );
  739. *
  740. * @protected
  741. * @param {Function} elementCreator Function returning a view element, which will be inserted.
  742. * @returns {Function} Insert element event converter.
  743. */
  744. export function insertElement( elementCreator ) {
  745. return ( evt, data, conversionApi ) => {
  746. // Cache current view element of a converted element, might be undefined if first insert.
  747. const currentView = conversionApi.mapper.toViewElement( data.item );
  748. // Create view structure:
  749. const viewElement = elementCreator( data.item, conversionApi );
  750. if ( !viewElement ) {
  751. return;
  752. }
  753. if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
  754. return;
  755. }
  756. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  757. // A flag was the simplest way of changing default insertElement behavior.
  758. if ( data.isRefresh ) {
  759. // Because of lack of a better API...
  760. // Iterate over new view elements to find "interesting" points - those elements that are mapped to the model.
  761. for ( const { item } of conversionApi.writer.createRangeIn( viewElement ) ) {
  762. const modelItem = conversionApi.mapper.toModelElement( item );
  763. // At this stage we get the update view element, so any mapped model item might be a potential "slot".
  764. if ( modelItem ) {
  765. const currentViewItem = conversionApi.mapper._temporalModelToView.get( modelItem );
  766. // This of course needs better API, but for now it works.
  767. // Mapper.bindSlot() creates mappings as mapper.bindElements() but also binds view element from view to the model item.
  768. if ( currentViewItem ) {
  769. // This allows to have a map: updatedView - model - oldView and to retain previously rendered children
  770. // from the "slot" element. Those children can be moved to a newly created slot.
  771. conversionApi.writer.move(
  772. conversionApi.writer.createRangeIn( currentViewItem ),
  773. conversionApi.writer.createPositionAt( item, 0 )
  774. );
  775. }
  776. // @todo should be done by conversion API...
  777. // Again, no API for this, so we need to stop conversion beneath "slot" by simply consuming whole tree under it.
  778. for ( const inner of ModelRange._createOn( modelItem ) ) {
  779. conversionApi.consumable.consume( inner.item, 'insert' );
  780. }
  781. }
  782. }
  783. // At this stage old view can be safely removed.
  784. conversionApi.writer.remove( currentView );
  785. }
  786. // Rest of standard insertElement converter.
  787. conversionApi.mapper.bindElements( data.item, viewElement );
  788. conversionApi.writer.insert( viewPosition, viewElement );
  789. };
  790. }
  791. /**
  792. * Function factory that creates a converter which converts marker adding change to the
  793. * {@link module:engine/view/uielement~UIElement view UI element}.
  794. *
  795. * The view UI element that will be added to the view depends on the passed parameter. See {@link ~insertElement}.
  796. * In case of a non-collapsed range, the UI element will not wrap nodes but separate elements will be placed at the beginning
  797. * and at the end of the range.
  798. *
  799. * This converter binds created UI elements with the marker name using {@link module:engine/conversion/mapper~Mapper#bindElementToMarker}.
  800. *
  801. * @protected
  802. * @param {module:engine/view/uielement~UIElement|Function} elementCreator A view UI element or a function returning the view element
  803. * that will be inserted.
  804. * @returns {Function} Insert element event converter.
  805. */
  806. export function insertUIElement( elementCreator ) {
  807. return ( evt, data, conversionApi ) => {
  808. // Create two view elements. One will be inserted at the beginning of marker, one at the end.
  809. // If marker is collapsed, only "opening" element will be inserted.
  810. data.isOpening = true;
  811. const viewStartElement = elementCreator( data, conversionApi );
  812. data.isOpening = false;
  813. const viewEndElement = elementCreator( data, conversionApi );
  814. if ( !viewStartElement || !viewEndElement ) {
  815. return;
  816. }
  817. const markerRange = data.markerRange;
  818. // Marker that is collapsed has consumable build differently that non-collapsed one.
  819. // For more information see `addMarker` event description.
  820. // If marker's range is collapsed - check if it can be consumed.
  821. if ( markerRange.isCollapsed && !conversionApi.consumable.consume( markerRange, evt.name ) ) {
  822. return;
  823. }
  824. // If marker's range is not collapsed - consume all items inside.
  825. for ( const value of markerRange ) {
  826. if ( !conversionApi.consumable.consume( value.item, evt.name ) ) {
  827. return;
  828. }
  829. }
  830. const mapper = conversionApi.mapper;
  831. const viewWriter = conversionApi.writer;
  832. // Add "opening" element.
  833. viewWriter.insert( mapper.toViewPosition( markerRange.start ), viewStartElement );
  834. conversionApi.mapper.bindElementToMarker( viewStartElement, data.markerName );
  835. // Add "closing" element only if range is not collapsed.
  836. if ( !markerRange.isCollapsed ) {
  837. viewWriter.insert( mapper.toViewPosition( markerRange.end ), viewEndElement );
  838. conversionApi.mapper.bindElementToMarker( viewEndElement, data.markerName );
  839. }
  840. evt.stop();
  841. };
  842. }
  843. // Function factory that returns a default downcast converter for removing a {@link module:engine/view/uielement~UIElement UI element}
  844. // based on marker remove change.
  845. //
  846. // This converter unbinds elements from the marker name.
  847. //
  848. // @returns {Function} Removed UI element converter.
  849. function removeUIElement() {
  850. return ( evt, data, conversionApi ) => {
  851. const elements = conversionApi.mapper.markerNameToElements( data.markerName );
  852. if ( !elements ) {
  853. return;
  854. }
  855. for ( const element of elements ) {
  856. conversionApi.mapper.unbindElementFromMarkerName( element, data.markerName );
  857. conversionApi.writer.clear( conversionApi.writer.createRangeOn( element ), element );
  858. }
  859. conversionApi.writer.clearClonedElementsGroup( data.markerName );
  860. evt.stop();
  861. };
  862. }
  863. // Function factory that creates a default converter for model markers.
  864. //
  865. // See {@link DowncastHelpers#markerToData} for more information what type of view is generated.
  866. //
  867. // This converter binds created UI elements and affected view elements with the marker name
  868. // using {@link module:engine/conversion/mapper~Mapper#bindElementToMarker}.
  869. //
  870. // @returns {Function} Add marker converter.
  871. function insertMarkerData( viewCreator ) {
  872. return ( evt, data, conversionApi ) => {
  873. const viewMarkerData = viewCreator( data.markerName, conversionApi );
  874. if ( !viewMarkerData ) {
  875. return;
  876. }
  877. const markerRange = data.markerRange;
  878. if ( !conversionApi.consumable.consume( markerRange, evt.name ) ) {
  879. return;
  880. }
  881. // Adding closing data first to keep the proper order in the view.
  882. handleMarkerBoundary( markerRange, false, conversionApi, data, viewMarkerData );
  883. handleMarkerBoundary( markerRange, true, conversionApi, data, viewMarkerData );
  884. evt.stop();
  885. };
  886. }
  887. // Helper function for `insertMarkerData()` that marks a marker boundary at the beginning or end of given `range`.
  888. function handleMarkerBoundary( range, isStart, conversionApi, data, viewMarkerData ) {
  889. const modelPosition = isStart ? range.start : range.end;
  890. const canInsertElement = conversionApi.schema.checkChild( modelPosition, '$text' );
  891. if ( canInsertElement ) {
  892. const viewPosition = conversionApi.mapper.toViewPosition( modelPosition );
  893. insertMarkerAsElement( viewPosition, isStart, conversionApi, data, viewMarkerData );
  894. } else {
  895. let modelElement;
  896. let isBefore;
  897. // If possible, we want to add `data-group-start-before` and `data-group-end-after` attributes.
  898. // Below `if` is constructed in a way that will favor adding these attributes.
  899. //
  900. // Also, I assume that there will be always an element either after or before the position.
  901. // If not, then it is a case when we are not in a position where text is allowed and also there are no elements around...
  902. if ( isStart && modelPosition.nodeAfter || !isStart && !modelPosition.nodeBefore ) {
  903. modelElement = modelPosition.nodeAfter;
  904. isBefore = true;
  905. } else {
  906. modelElement = modelPosition.nodeBefore;
  907. isBefore = false;
  908. }
  909. const viewElement = conversionApi.mapper.toViewElement( modelElement );
  910. insertMarkerAsAttribute( viewElement, isStart, isBefore, conversionApi, data, viewMarkerData );
  911. }
  912. }
  913. // Helper function for `insertMarkerData()` that marks a marker boundary in the view as an attribute on a view element.
  914. function insertMarkerAsAttribute( viewElement, isStart, isBefore, conversionApi, data, viewMarkerData ) {
  915. const attributeName = `data-${ viewMarkerData.group }-${ isStart ? 'start' : 'end' }-${ isBefore ? 'before' : 'after' }`;
  916. const markerNames = viewElement.hasAttribute( attributeName ) ? viewElement.getAttribute( attributeName ).split( ',' ) : [];
  917. // Adding marker name at the beginning to have the same order in the attribute as there is with marker elements.
  918. markerNames.unshift( viewMarkerData.name );
  919. conversionApi.writer.setAttribute( attributeName, markerNames.join( ',' ), viewElement );
  920. conversionApi.mapper.bindElementToMarker( viewElement, data.markerName );
  921. }
  922. // Helper function for `insertMarkerData()` that marks a marker boundary in the view as a separate view ui element.
  923. function insertMarkerAsElement( position, isStart, conversionApi, data, viewMarkerData ) {
  924. const viewElementName = `${ viewMarkerData.group }-${ isStart ? 'start' : 'end' }`;
  925. const attrs = viewMarkerData.name ? { 'name': viewMarkerData.name } : null;
  926. const viewElement = conversionApi.writer.createUIElement( viewElementName, attrs );
  927. conversionApi.writer.insert( position, viewElement );
  928. conversionApi.mapper.bindElementToMarker( viewElement, data.markerName );
  929. }
  930. // Function factory that creates a converter for removing a model marker data added by the {@link #insertMarkerData} converter.
  931. //
  932. // @returns {Function} Remove marker converter.
  933. function removeMarkerData( viewCreator ) {
  934. return ( evt, data, conversionApi ) => {
  935. const viewData = viewCreator( data.markerName, conversionApi );
  936. if ( !viewData ) {
  937. return;
  938. }
  939. const elements = conversionApi.mapper.markerNameToElements( data.markerName );
  940. if ( !elements ) {
  941. return;
  942. }
  943. for ( const element of elements ) {
  944. conversionApi.mapper.unbindElementFromMarkerName( element, data.markerName );
  945. if ( element.is( 'containerElement' ) ) {
  946. removeMarkerFromAttribute( `data-${ viewData.group }-start-before`, element );
  947. removeMarkerFromAttribute( `data-${ viewData.group }-start-after`, element );
  948. removeMarkerFromAttribute( `data-${ viewData.group }-end-before`, element );
  949. removeMarkerFromAttribute( `data-${ viewData.group }-end-after`, element );
  950. } else {
  951. conversionApi.writer.clear( conversionApi.writer.createRangeOn( element ), element );
  952. }
  953. }
  954. conversionApi.writer.clearClonedElementsGroup( data.markerName );
  955. evt.stop();
  956. function removeMarkerFromAttribute( attributeName, element ) {
  957. if ( element.hasAttribute( attributeName ) ) {
  958. const markerNames = new Set( element.getAttribute( attributeName ).split( ',' ) );
  959. markerNames.delete( viewData.name );
  960. if ( markerNames.size == 0 ) {
  961. conversionApi.writer.removeAttribute( attributeName, element );
  962. } else {
  963. conversionApi.writer.setAttribute( attributeName, Array.from( markerNames ).join( ',' ), element );
  964. }
  965. }
  966. }
  967. };
  968. }
  969. // Function factory that creates a converter which converts set/change/remove attribute changes from the model to the view.
  970. //
  971. // Attributes from the model are converted to the view element attributes in the view. You may provide a custom function to generate
  972. // a key-value attribute pair to add/change/remove. If not provided, model attributes will be converted to view element
  973. // attributes on a one-to-one basis.
  974. //
  975. // *Note:** The provided attribute creator should always return the same `key` for a given attribute from the model.
  976. //
  977. // The converter automatically consumes the corresponding value from the consumables list and stops the event (see
  978. // {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}).
  979. //
  980. // modelDispatcher.on( 'attribute:customAttr:myElem', changeAttribute( ( value, data ) => {
  981. // // Change attribute key from `customAttr` to `class` in the view.
  982. // const key = 'class';
  983. // let value = data.attributeNewValue;
  984. //
  985. // // Force attribute value to 'empty' if the model element is empty.
  986. // if ( data.item.childCount === 0 ) {
  987. // value = 'empty';
  988. // }
  989. //
  990. // // Return the key-value pair.
  991. // return { key, value };
  992. // } ) );
  993. //
  994. // @param {Function} [attributeCreator] Function returning an object with two properties: `key` and `value`, which
  995. // represent the attribute key and attribute value to be set on a {@link module:engine/view/element~Element view element}.
  996. // The function is passed the model attribute value as the first parameter and additional data about the change as the second parameter.
  997. // @returns {Function} Set/change attribute converter.
  998. function changeAttribute( attributeCreator ) {
  999. return ( evt, data, conversionApi ) => {
  1000. const oldAttribute = attributeCreator( data.attributeOldValue, conversionApi );
  1001. const newAttribute = attributeCreator( data.attributeNewValue, conversionApi );
  1002. if ( !oldAttribute && !newAttribute ) {
  1003. return;
  1004. }
  1005. if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
  1006. return;
  1007. }
  1008. const viewElement = conversionApi.mapper.toViewElement( data.item );
  1009. const viewWriter = conversionApi.writer;
  1010. // If model item cannot be mapped to a view element, it means item is not an `Element` instance but a `TextProxy` node.
  1011. // Only elements can have attributes in a view so do not proceed for anything else (#1587).
  1012. if ( !viewElement ) {
  1013. /**
  1014. * This error occurs when a {@link module:engine/model/textproxy~TextProxy text node's} attribute is to be downcasted
  1015. * by {@link module:engine/conversion/conversion~Conversion#attributeToAttribute `Attribute to Attribute converter`}.
  1016. * In most cases it is caused by converters misconfiguration when only "generic" converter is defined:
  1017. *
  1018. * editor.conversion.for( 'downcast' ).attributeToAttribute( {
  1019. * model: 'attribute-name',
  1020. * view: 'attribute-name'
  1021. * } ) );
  1022. *
  1023. * and given attribute is used on text node, for example:
  1024. *
  1025. * model.change( writer => {
  1026. * writer.insertText( 'Foo', { 'attribute-name': 'bar' }, parent, 0 );
  1027. * } );
  1028. *
  1029. * In such cases, to convert the same attribute for both {@link module:engine/model/element~Element}
  1030. * and {@link module:engine/model/textproxy~TextProxy `Text`} nodes, text specific
  1031. * {@link module:engine/conversion/conversion~Conversion#attributeToElement `Attribute to Element converter`}
  1032. * with higher {@link module:utils/priorities~PriorityString priority} must also be defined:
  1033. *
  1034. * editor.conversion.for( 'downcast' ).attributeToElement( {
  1035. * model: {
  1036. * key: 'attribute-name',
  1037. * name: '$text'
  1038. * },
  1039. * view: ( value, { writer } ) => {
  1040. * return writer.createAttributeElement( 'span', { 'attribute-name': value } );
  1041. * },
  1042. * converterPriority: 'high'
  1043. * } ) );
  1044. *
  1045. * @error conversion-attribute-to-attribute-on-text
  1046. */
  1047. throw new CKEditorError(
  1048. 'conversion-attribute-to-attribute-on-text',
  1049. [ data, conversionApi ]
  1050. );
  1051. }
  1052. // First remove the old attribute if there was one.
  1053. if ( data.attributeOldValue !== null && oldAttribute ) {
  1054. if ( oldAttribute.key == 'class' ) {
  1055. const classes = Array.isArray( oldAttribute.value ) ? oldAttribute.value : [ oldAttribute.value ];
  1056. for ( const className of classes ) {
  1057. viewWriter.removeClass( className, viewElement );
  1058. }
  1059. } else if ( oldAttribute.key == 'style' ) {
  1060. const keys = Object.keys( oldAttribute.value );
  1061. for ( const key of keys ) {
  1062. viewWriter.removeStyle( key, viewElement );
  1063. }
  1064. } else {
  1065. viewWriter.removeAttribute( oldAttribute.key, viewElement );
  1066. }
  1067. }
  1068. // Then set the new attribute.
  1069. if ( data.attributeNewValue !== null && newAttribute ) {
  1070. if ( newAttribute.key == 'class' ) {
  1071. const classes = Array.isArray( newAttribute.value ) ? newAttribute.value : [ newAttribute.value ];
  1072. for ( const className of classes ) {
  1073. viewWriter.addClass( className, viewElement );
  1074. }
  1075. } else if ( newAttribute.key == 'style' ) {
  1076. const keys = Object.keys( newAttribute.value );
  1077. for ( const key of keys ) {
  1078. viewWriter.setStyle( key, newAttribute.value[ key ], viewElement );
  1079. }
  1080. } else {
  1081. viewWriter.setAttribute( newAttribute.key, newAttribute.value, viewElement );
  1082. }
  1083. }
  1084. };
  1085. }
  1086. // Function factory that creates a converter which converts the text inside marker's range. The converter wraps the text with
  1087. // {@link module:engine/view/attributeelement~AttributeElement} created from the provided descriptor.
  1088. // See {link module:engine/conversion/downcasthelpers~createViewElementFromHighlightDescriptor}.
  1089. //
  1090. // It can also be used to convert the selection that is inside a marker. In that case, an empty attribute element will be
  1091. // created and the selection will be put inside it.
  1092. //
  1093. // If the highlight descriptor does not provide the `priority` property, `10` will be used.
  1094. //
  1095. // If the highlight descriptor does not provide the `id` property, the name of the marker will be used.
  1096. //
  1097. // This converter binds the created {@link module:engine/view/attributeelement~AttributeElement attribute elemens} with the marker name
  1098. // using the {@link module:engine/conversion/mapper~Mapper#bindElementToMarker} method.
  1099. //
  1100. // @param {module:engine/conversion/downcasthelpers~HighlightDescriptor|Function} highlightDescriptor
  1101. // @returns {Function}
  1102. function highlightText( highlightDescriptor ) {
  1103. return ( evt, data, conversionApi ) => {
  1104. if ( !data.item ) {
  1105. return;
  1106. }
  1107. if ( !( data.item instanceof ModelSelection || data.item instanceof DocumentSelection ) && !data.item.is( '$textProxy' ) ) {
  1108. return;
  1109. }
  1110. const descriptor = prepareDescriptor( highlightDescriptor, data, conversionApi );
  1111. if ( !descriptor ) {
  1112. return;
  1113. }
  1114. if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
  1115. return;
  1116. }
  1117. const viewWriter = conversionApi.writer;
  1118. const viewElement = createViewElementFromHighlightDescriptor( viewWriter, descriptor );
  1119. const viewSelection = viewWriter.document.selection;
  1120. if ( data.item instanceof ModelSelection || data.item instanceof DocumentSelection ) {
  1121. viewWriter.wrap( viewSelection.getFirstRange(), viewElement, viewSelection );
  1122. } else {
  1123. const viewRange = conversionApi.mapper.toViewRange( data.range );
  1124. const rangeAfterWrap = viewWriter.wrap( viewRange, viewElement );
  1125. for ( const element of rangeAfterWrap.getItems() ) {
  1126. if ( element.is( 'attributeElement' ) && element.isSimilar( viewElement ) ) {
  1127. conversionApi.mapper.bindElementToMarker( element, data.markerName );
  1128. // One attribute element is enough, because all of them are bound together by the view writer.
  1129. // Mapper uses this binding to get all the elements no matter how many of them are registered in the mapper.
  1130. break;
  1131. }
  1132. }
  1133. }
  1134. };
  1135. }
  1136. // Converter function factory. It creates a function which applies the marker's highlight to an element inside the marker's range.
  1137. //
  1138. // The converter checks if an element has the `addHighlight` function stored as a
  1139. // {@link module:engine/view/element~Element#_setCustomProperty custom property} and, if so, uses it to apply the highlight.
  1140. // In such case the converter will consume all element's children, assuming that they were handled by the element itself.
  1141. //
  1142. // When the `addHighlight` custom property is not present, the element is not converted in any special way.
  1143. // This means that converters will proceed to convert the element's child nodes.
  1144. //
  1145. // If the highlight descriptor does not provide the `priority` property, `10` will be used.
  1146. //
  1147. // If the highlight descriptor does not provide the `id` property, the name of the marker will be used.
  1148. //
  1149. // This converter binds altered {@link module:engine/view/containerelement~ContainerElement container elements} with the marker name using
  1150. // the {@link module:engine/conversion/mapper~Mapper#bindElementToMarker} method.
  1151. //
  1152. // @param {module:engine/conversion/downcasthelpers~HighlightDescriptor|Function} highlightDescriptor
  1153. // @returns {Function}
  1154. function highlightElement( highlightDescriptor ) {
  1155. return ( evt, data, conversionApi ) => {
  1156. if ( !data.item ) {
  1157. return;
  1158. }
  1159. if ( !( data.item instanceof ModelElement ) ) {
  1160. return;
  1161. }
  1162. const descriptor = prepareDescriptor( highlightDescriptor, data, conversionApi );
  1163. if ( !descriptor ) {
  1164. return;
  1165. }
  1166. if ( !conversionApi.consumable.test( data.item, evt.name ) ) {
  1167. return;
  1168. }
  1169. const viewElement = conversionApi.mapper.toViewElement( data.item );
  1170. if ( viewElement && viewElement.getCustomProperty( 'addHighlight' ) ) {
  1171. // Consume element itself.
  1172. conversionApi.consumable.consume( data.item, evt.name );
  1173. // Consume all children nodes.
  1174. for ( const value of ModelRange._createIn( data.item ) ) {
  1175. conversionApi.consumable.consume( value.item, evt.name );
  1176. }
  1177. viewElement.getCustomProperty( 'addHighlight' )( viewElement, descriptor, conversionApi.writer );
  1178. conversionApi.mapper.bindElementToMarker( viewElement, data.markerName );
  1179. }
  1180. };
  1181. }
  1182. // Function factory that creates a converter which converts the removing model marker to the view.
  1183. //
  1184. // Both text nodes and elements are handled by this converter but they are handled a bit differently.
  1185. //
  1186. // Text nodes are unwrapped using the {@link module:engine/view/attributeelement~AttributeElement attribute element} created from the
  1187. // provided highlight descriptor. See {link module:engine/conversion/downcasthelpers~HighlightDescriptor}.
  1188. //
  1189. // For elements, the converter checks if an element has the `removeHighlight` function stored as a
  1190. // {@link module:engine/view/element~Element#_setCustomProperty custom property}. If so, it uses it to remove the highlight.
  1191. // In such case, the children of that element will not be converted.
  1192. //
  1193. // When `removeHighlight` is not present, the element is not converted in any special way.
  1194. // The converter will proceed to convert the element's child nodes instead.
  1195. //
  1196. // If the highlight descriptor does not provide the `priority` property, `10` will be used.
  1197. //
  1198. // If the highlight descriptor does not provide the `id` property, the name of the marker will be used.
  1199. //
  1200. // This converter unbinds elements from the marker name.
  1201. //
  1202. // @param {module:engine/conversion/downcasthelpers~HighlightDescriptor|Function} highlightDescriptor
  1203. // @returns {Function}
  1204. function removeHighlight( highlightDescriptor ) {
  1205. return ( evt, data, conversionApi ) => {
  1206. // This conversion makes sense only for non-collapsed range.
  1207. if ( data.markerRange.isCollapsed ) {
  1208. return;
  1209. }
  1210. const descriptor = prepareDescriptor( highlightDescriptor, data, conversionApi );
  1211. if ( !descriptor ) {
  1212. return;
  1213. }
  1214. // View element that will be used to unwrap `AttributeElement`s.
  1215. const viewHighlightElement = createViewElementFromHighlightDescriptor( conversionApi.writer, descriptor );
  1216. // Get all elements bound with given marker name.
  1217. const elements = conversionApi.mapper.markerNameToElements( data.markerName );
  1218. if ( !elements ) {
  1219. return;
  1220. }
  1221. for ( const element of elements ) {
  1222. conversionApi.mapper.unbindElementFromMarkerName( element, data.markerName );
  1223. if ( element.is( 'attributeElement' ) ) {
  1224. conversionApi.writer.unwrap( conversionApi.writer.createRangeOn( element ), viewHighlightElement );
  1225. } else {
  1226. // if element.is( 'containerElement' ).
  1227. element.getCustomProperty( 'removeHighlight' )( element, descriptor.id, conversionApi.writer );
  1228. }
  1229. }
  1230. conversionApi.writer.clearClonedElementsGroup( data.markerName );
  1231. evt.stop();
  1232. };
  1233. }
  1234. // Model element to view element conversion helper.
  1235. //
  1236. // See {@link ~DowncastHelpers#elementToElement `.elementToElement()` downcast helper} for examples.
  1237. //
  1238. // @param {Object} config Conversion configuration.
  1239. // @param {String} config.model The name of the model element to convert.
  1240. // @param {module:engine/view/elementdefinition~ElementDefinition|Function} config.view A view element definition or a function
  1241. // that takes the model element and {@link module:engine/view/downcastwriter~DowncastWriter view downcast writer}
  1242. // as parameters and returns a view container element.
  1243. // @returns {Function} Conversion helper.
  1244. function downcastElementToElement( config ) {
  1245. config = cloneDeep( config );
  1246. config.view = normalizeToElementConfig( config.view, 'container' );
  1247. return dispatcher => {
  1248. dispatcher.on( 'insert:' + config.model, insertElement( config.view ), { priority: config.converterPriority || 'normal' } );
  1249. if ( config.triggerBy ) {
  1250. dispatcher.mapRefreshEvents( config.model, config.triggerBy );
  1251. }
  1252. };
  1253. }
  1254. // Model attribute to view element conversion helper.
  1255. //
  1256. // See {@link ~DowncastHelpers#attributeToElement `.attributeToElement()` downcast helper} for examples.
  1257. //
  1258. // @param {Object} config Conversion configuration.
  1259. // @param {String|Object} config.model The key of the attribute to convert from or a `{ key, values }` object. `values` is an array
  1260. // of `String`s with possible values if the model attribute is an enumerable.
  1261. // @param {module:engine/view/elementdefinition~ElementDefinition|Function|Object} config.view A view element definition or a function
  1262. // that takes the model attribute value and {@link module:engine/view/downcastwriter~DowncastWriter view downcast writer}
  1263. // as parameters and returns a view attribute element. If `config.model.values` is
  1264. // given, `config.view` should be an object assigning values from `config.model.values` to view element definitions or functions.
  1265. // @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  1266. // @returns {Function} Conversion helper.
  1267. function downcastAttributeToElement( config ) {
  1268. config = cloneDeep( config );
  1269. const modelKey = config.model.key ? config.model.key : config.model;
  1270. let eventName = 'attribute:' + modelKey;
  1271. if ( config.model.name ) {
  1272. eventName += ':' + config.model.name;
  1273. }
  1274. if ( config.model.values ) {
  1275. for ( const modelValue of config.model.values ) {
  1276. config.view[ modelValue ] = normalizeToElementConfig( config.view[ modelValue ], 'attribute' );
  1277. }
  1278. } else {
  1279. config.view = normalizeToElementConfig( config.view, 'attribute' );
  1280. }
  1281. const elementCreator = getFromAttributeCreator( config );
  1282. return dispatcher => {
  1283. dispatcher.on( eventName, wrap( elementCreator ), { priority: config.converterPriority || 'normal' } );
  1284. };
  1285. }
  1286. // Model attribute to view attribute conversion helper.
  1287. //
  1288. // See {@link ~DowncastHelpers#attributeToAttribute `.attributeToAttribute()` downcast helper} for examples.
  1289. //
  1290. // @param {Object} config Conversion configuration.
  1291. // @param {String|Object} config.model The key of the attribute to convert from or a `{ key, values, [ name ] }` object describing
  1292. // the attribute key, possible values and, optionally, an element name to convert from.
  1293. // @param {String|Object|Function} config.view A view attribute key, or a `{ key, value }` object or a function that takes
  1294. // the model attribute value and returns a `{ key, value }` object. If `key` is `'class'`, `value` can be a `String` or an
  1295. // array of `String`s. If `key` is `'style'`, `value` is an object with key-value pairs. In other cases, `value` is a `String`.
  1296. // If `config.model.values` is set, `config.view` should be an object assigning values from `config.model.values` to
  1297. // `{ key, value }` objects or a functions.
  1298. // @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  1299. // @returns {Function} Conversion helper.
  1300. function downcastAttributeToAttribute( config ) {
  1301. config = cloneDeep( config );
  1302. const modelKey = config.model.key ? config.model.key : config.model;
  1303. let eventName = 'attribute:' + modelKey;
  1304. if ( config.model.name ) {
  1305. eventName += ':' + config.model.name;
  1306. }
  1307. if ( config.model.values ) {
  1308. for ( const modelValue of config.model.values ) {
  1309. config.view[ modelValue ] = normalizeToAttributeConfig( config.view[ modelValue ] );
  1310. }
  1311. } else {
  1312. config.view = normalizeToAttributeConfig( config.view );
  1313. }
  1314. const elementCreator = getFromAttributeCreator( config );
  1315. return dispatcher => {
  1316. dispatcher.on( eventName, changeAttribute( elementCreator ), { priority: config.converterPriority || 'normal' } );
  1317. };
  1318. }
  1319. // Model marker to view element conversion helper.
  1320. //
  1321. // See {@link ~DowncastHelpers#markerToElement `.markerToElement()` downcast helper} for examples.
  1322. //
  1323. // @param {Object} config Conversion configuration.
  1324. // @param {String} config.model The name of the model marker (or model marker group) to convert.
  1325. // @param {module:engine/view/elementdefinition~ElementDefinition|Function} config.view A view element definition or a function
  1326. // that takes the model marker data as a parameter and returns a view UI element.
  1327. // @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  1328. // @returns {Function} Conversion helper.
  1329. function downcastMarkerToElement( config ) {
  1330. config = cloneDeep( config );
  1331. config.view = normalizeToElementConfig( config.view, 'ui' );
  1332. return dispatcher => {
  1333. dispatcher.on( 'addMarker:' + config.model, insertUIElement( config.view ), { priority: config.converterPriority || 'normal' } );
  1334. dispatcher.on( 'removeMarker:' + config.model, removeUIElement( config.view ), { priority: config.converterPriority || 'normal' } );
  1335. };
  1336. }
  1337. // Model marker to view data conversion helper.
  1338. //
  1339. // See {@link ~DowncastHelpers#markerToData `markerToData()` downcast helper} to learn more.
  1340. //
  1341. // @param {Object} config
  1342. // @param {String} config.model
  1343. // @param {Function} [config.view]
  1344. // @param {module:utils/priorities~PriorityString} [config.converterPriority='normal']
  1345. // @returns {Function} Conversion helper.
  1346. function downcastMarkerToData( config ) {
  1347. config = cloneDeep( config );
  1348. const group = config.model;
  1349. // Default conversion.
  1350. if ( !config.view ) {
  1351. config.view = markerName => ( {
  1352. group,
  1353. name: markerName.substr( config.model.length + 1 )
  1354. } );
  1355. }
  1356. return dispatcher => {
  1357. dispatcher.on( 'addMarker:' + group, insertMarkerData( config.view ), { priority: config.converterPriority || 'normal' } );
  1358. dispatcher.on( 'removeMarker:' + group, removeMarkerData( config.view ), { priority: config.converterPriority || 'normal' } );
  1359. };
  1360. }
  1361. // Model marker to highlight conversion helper.
  1362. //
  1363. // See {@link ~DowncastHelpers#markerToElement `.markerToElement()` downcast helper} for examples.
  1364. //
  1365. // @param {Object} config Conversion configuration.
  1366. // @param {String} config.model The name of the model marker (or model marker group) to convert.
  1367. // @param {module:engine/conversion/downcasthelpers~HighlightDescriptor|Function} config.view A highlight descriptor
  1368. // that will be used for highlighting or a function that takes the model marker data as a parameter and returns a highlight descriptor.
  1369. // @param {module:utils/priorities~PriorityString} [config.converterPriority='normal'] Converter priority.
  1370. // @returns {Function} Conversion helper.
  1371. function downcastMarkerToHighlight( config ) {
  1372. return dispatcher => {
  1373. dispatcher.on( 'addMarker:' + config.model, highlightText( config.view ), { priority: config.converterPriority || 'normal' } );
  1374. dispatcher.on( 'addMarker:' + config.model, highlightElement( config.view ), { priority: config.converterPriority || 'normal' } );
  1375. dispatcher.on( 'removeMarker:' + config.model, removeHighlight( config.view ), { priority: config.converterPriority || 'normal' } );
  1376. };
  1377. }
  1378. // Takes `config.view`, and if it is an {@link module:engine/view/elementdefinition~ElementDefinition}, converts it
  1379. // to a function (because lower level converters accept only element creator functions).
  1380. //
  1381. // @param {module:engine/view/elementdefinition~ElementDefinition|Function} view View configuration.
  1382. // @param {'container'|'attribute'|'ui'} viewElementType View element type to create.
  1383. // @returns {Function} Element creator function to use in lower level converters.
  1384. function normalizeToElementConfig( view, viewElementType ) {
  1385. if ( typeof view == 'function' ) {
  1386. // If `view` is already a function, don't do anything.
  1387. return view;
  1388. }
  1389. return ( modelData, conversionApi ) => createViewElementFromDefinition( view, conversionApi, viewElementType );
  1390. }
  1391. // Creates a view element instance from the provided {@link module:engine/view/elementdefinition~ElementDefinition} and class.
  1392. //
  1393. // @param {module:engine/view/elementdefinition~ElementDefinition} viewElementDefinition
  1394. // @param {module:engine/view/downcastwriter~DowncastWriter} viewWriter
  1395. // @param {'container'|'attribute'|'ui'} viewElementType
  1396. // @returns {module:engine/view/element~Element}
  1397. function createViewElementFromDefinition( viewElementDefinition, conversionApi, viewElementType ) {
  1398. if ( typeof viewElementDefinition == 'string' ) {
  1399. // If `viewElementDefinition` is given as a `String`, normalize it to an object with `name` property.
  1400. viewElementDefinition = { name: viewElementDefinition };
  1401. }
  1402. let element;
  1403. const viewWriter = conversionApi.writer;
  1404. const attributes = Object.assign( {}, viewElementDefinition.attributes );
  1405. if ( viewElementType == 'container' ) {
  1406. element = viewWriter.createContainerElement( viewElementDefinition.name, attributes );
  1407. } else if ( viewElementType == 'attribute' ) {
  1408. const options = {
  1409. priority: viewElementDefinition.priority || ViewAttributeElement.DEFAULT_PRIORITY
  1410. };
  1411. element = viewWriter.createAttributeElement( viewElementDefinition.name, attributes, options );
  1412. } else {
  1413. // 'ui'.
  1414. element = viewWriter.createUIElement( viewElementDefinition.name, attributes );
  1415. }
  1416. if ( viewElementDefinition.styles ) {
  1417. const keys = Object.keys( viewElementDefinition.styles );
  1418. for ( const key of keys ) {
  1419. viewWriter.setStyle( key, viewElementDefinition.styles[ key ], element );
  1420. }
  1421. }
  1422. if ( viewElementDefinition.classes ) {
  1423. const classes = viewElementDefinition.classes;
  1424. if ( typeof classes == 'string' ) {
  1425. viewWriter.addClass( classes, element );
  1426. } else {
  1427. for ( const className of classes ) {
  1428. viewWriter.addClass( className, element );
  1429. }
  1430. }
  1431. }
  1432. return element;
  1433. }
  1434. function getFromAttributeCreator( config ) {
  1435. if ( config.model.values ) {
  1436. return ( modelAttributeValue, conversionApi ) => {
  1437. const view = config.view[ modelAttributeValue ];
  1438. if ( view ) {
  1439. return view( modelAttributeValue, conversionApi );
  1440. }
  1441. return null;
  1442. };
  1443. } else {
  1444. return config.view;
  1445. }
  1446. }
  1447. // Takes the configuration, adds default parameters if they do not exist and normalizes other parameters to be used in downcast converters
  1448. // for generating a view attribute.
  1449. //
  1450. // @param {Object} view View configuration.
  1451. function normalizeToAttributeConfig( view ) {
  1452. if ( typeof view == 'string' ) {
  1453. return modelAttributeValue => ( { key: view, value: modelAttributeValue } );
  1454. } else if ( typeof view == 'object' ) {
  1455. // { key, value, ... }
  1456. if ( view.value ) {
  1457. return () => view;
  1458. }
  1459. // { key, ... }
  1460. else {
  1461. return modelAttributeValue => ( { key: view.key, value: modelAttributeValue } );
  1462. }
  1463. } else {
  1464. // function.
  1465. return view;
  1466. }
  1467. }
  1468. // Helper function for `highlight`. Prepares the actual descriptor object using value passed to the converter.
  1469. function prepareDescriptor( highlightDescriptor, data, conversionApi ) {
  1470. // If passed descriptor is a creator function, call it. If not, just use passed value.
  1471. const descriptor = typeof highlightDescriptor == 'function' ?
  1472. highlightDescriptor( data, conversionApi ) :
  1473. highlightDescriptor;
  1474. if ( !descriptor ) {
  1475. return null;
  1476. }
  1477. // Apply default descriptor priority.
  1478. if ( !descriptor.priority ) {
  1479. descriptor.priority = 10;
  1480. }
  1481. // Default descriptor id is marker name.
  1482. if ( !descriptor.id ) {
  1483. descriptor.id = data.markerName;
  1484. }
  1485. return descriptor;
  1486. }
  1487. /**
  1488. * An object describing how the marker highlight should be represented in the view.
  1489. *
  1490. * Each text node contained in a highlighted range will be wrapped in a `<span>`
  1491. * {@link module:engine/view/attributeelement~AttributeElement view attribute element} with CSS class(es), attributes and a priority
  1492. * described by this object.
  1493. *
  1494. * Additionally, each {@link module:engine/view/containerelement~ContainerElement container element} can handle displaying the highlight
  1495. * separately by providing the `addHighlight` and `removeHighlight` custom properties. In this case:
  1496. *
  1497. * * The `HighlightDescriptor` object is passed to the `addHighlight` function upon conversion and should be used to apply the highlight to
  1498. * the element.
  1499. * * The descriptor `id` is passed to the `removeHighlight` function upon conversion and should be used to remove the highlight with the
  1500. * given ID from the element.
  1501. *
  1502. * @typedef {Object} module:engine/conversion/downcasthelpers~HighlightDescriptor
  1503. *
  1504. * @property {String|Array.<String>} classes A CSS class or an array of classes to set. If the descriptor is used to
  1505. * create an {@link module:engine/view/attributeelement~AttributeElement attribute element} over text nodes, these classes will be set
  1506. * on that attribute element. If the descriptor is applied to an element, usually these classes will be set on that element, however,
  1507. * this depends on how the element converts the descriptor.
  1508. *
  1509. * @property {String} [id] Descriptor identifier. If not provided, it defaults to the converted marker's name.
  1510. *
  1511. * @property {Number} [priority] Descriptor priority. If not provided, it defaults to `10`. If the descriptor is used to create
  1512. * an {@link module:engine/view/attributeelement~AttributeElement attribute element}, it will be that element's
  1513. * {@link module:engine/view/attributeelement~AttributeElement#priority priority}. If the descriptor is applied to an element,
  1514. * the priority will be used to determine which descriptor is more important.
  1515. *
  1516. * @property {Object} [attributes] Attributes to set. If the descriptor is used to create
  1517. * an {@link module:engine/view/attributeelement~AttributeElement attribute element} over text nodes, these attributes will be set on that
  1518. * attribute element. If the descriptor is applied to an element, usually these attributes will be set on that element, however,
  1519. * this depends on how the element converts the descriptor.
  1520. */