matcher.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/view/matcher
  7. */
  8. /**
  9. * View matcher class.
  10. * Instance of this class can be used to find {@link module:engine/view/element~Element elements} that match given pattern.
  11. */
  12. export default class Matcher {
  13. /**
  14. * Creates new instance of Matcher.
  15. *
  16. * @param {String|RegExp|Object} [pattern] Match patterns. See {@link module:engine/view/matcher~Matcher#add add method} for
  17. * more information.
  18. */
  19. constructor( ...pattern ) {
  20. /**
  21. * @private
  22. * @type {Array<String|RegExp|Object>}
  23. */
  24. this._patterns = [];
  25. this.add( ...pattern );
  26. }
  27. /**
  28. * Adds pattern or patterns to matcher instance.
  29. *
  30. * // String.
  31. * matcher.add( 'div' );
  32. *
  33. * // Regular expression.
  34. * matcher.add( /^\w/ );
  35. *
  36. * // Single class.
  37. * matcher.add( {
  38. * classes: 'foobar'
  39. * } );
  40. *
  41. * See {@link module:engine/view/matcher~MatcherPattern} for more examples.
  42. *
  43. * Multiple patterns can be added in one call:
  44. *
  45. * matcher.add( 'div', { classes: 'foobar' } );
  46. *
  47. * @param {Object|String|RegExp|Function} pattern Object describing pattern details. If string or regular expression
  48. * is provided it will be used to match element's name. Pattern can be also provided in a form
  49. * of a function - then this function will be called with each {@link module:engine/view/element~Element element} as a parameter.
  50. * Function's return value will be stored under `match` key of the object returned from
  51. * {@link module:engine/view/matcher~Matcher#match match} or {@link module:engine/view/matcher~Matcher#matchAll matchAll} methods.
  52. * @param {String|RegExp} [pattern.name] Name or regular expression to match element's name.
  53. * @param {Object} [pattern.attributes] Object with key-value pairs representing attributes to match. Each object key
  54. * represents attribute name. Value under that key can be either:
  55. * * `true` - then attribute is just required (can be empty),
  56. * * a string - then attribute has to be equal, or
  57. * * a regular expression - then attribute has to match the expression.
  58. * @param {String|RegExp|Array} [pattern.classes] Class name or array of class names to match. Each name can be
  59. * provided in a form of string or regular expression.
  60. * @param {Object} [pattern.styles] Object with key-value pairs representing styles to match. Each object key
  61. * represents style name. Value under that key can be either a string or a regular expression and it will be used
  62. * to match style value.
  63. */
  64. add( ...pattern ) {
  65. for ( let item of pattern ) {
  66. // String or RegExp pattern is used as element's name.
  67. if ( typeof item == 'string' || item instanceof RegExp ) {
  68. item = { name: item };
  69. }
  70. // Single class name/RegExp can be provided.
  71. if ( item.classes && ( typeof item.classes == 'string' || item.classes instanceof RegExp ) ) {
  72. item.classes = [ item.classes ];
  73. }
  74. this._patterns.push( item );
  75. }
  76. }
  77. /**
  78. * Matches elements for currently stored patterns. Returns match information about first found
  79. * {@link module:engine/view/element~Element element}, otherwise returns `null`.
  80. *
  81. * Example of returned object:
  82. *
  83. * {
  84. * element: <instance of found element>,
  85. * pattern: <pattern used to match found element>,
  86. * match: {
  87. * name: true,
  88. * attributes: [ 'title', 'href' ],
  89. * classes: [ 'foo' ],
  90. * styles: [ 'color', 'position' ]
  91. * }
  92. * }
  93. *
  94. * @see module:engine/view/matcher~Matcher#add
  95. * @see module:engine/view/matcher~Matcher#matchAll
  96. * @param {...module:engine/view/element~Element} element View element to match against stored patterns.
  97. * @returns {Object|null} result
  98. * @returns {module:engine/view/element~Element} result.element Matched view element.
  99. * @returns {Object|String|RegExp|Function} result.pattern Pattern that was used to find matched element.
  100. * @returns {Object} result.match Object representing matched element parts.
  101. * @returns {Boolean} [result.match.name] True if name of the element was matched.
  102. * @returns {Array} [result.match.attributes] Array with matched attribute names.
  103. * @returns {Array} [result.match.classes] Array with matched class names.
  104. * @returns {Array} [result.match.styles] Array with matched style names.
  105. */
  106. match( ...element ) {
  107. for ( const singleElement of element ) {
  108. for ( const pattern of this._patterns ) {
  109. const match = isElementMatching( singleElement, pattern );
  110. if ( match ) {
  111. return {
  112. element: singleElement,
  113. pattern,
  114. match
  115. };
  116. }
  117. }
  118. }
  119. return null;
  120. }
  121. /**
  122. * Matches elements for currently stored patterns. Returns array of match information with all found
  123. * {@link module:engine/view/element~Element elements}. If no element is found - returns `null`.
  124. *
  125. * @see module:engine/view/matcher~Matcher#add
  126. * @see module:engine/view/matcher~Matcher#match
  127. * @param {...module:engine/view/element~Element} element View element to match against stored patterns.
  128. * @returns {Array.<Object>|null} Array with match information about found elements or `null`. For more information
  129. * see {@link module:engine/view/matcher~Matcher#match match method} description.
  130. */
  131. matchAll( ...element ) {
  132. const results = [];
  133. for ( const singleElement of element ) {
  134. for ( const pattern of this._patterns ) {
  135. const match = isElementMatching( singleElement, pattern );
  136. if ( match ) {
  137. results.push( {
  138. element: singleElement,
  139. pattern,
  140. match
  141. } );
  142. }
  143. }
  144. }
  145. return results.length > 0 ? results : null;
  146. }
  147. /**
  148. * Returns the name of the element to match if there is exactly one pattern added to the matcher instance
  149. * and it matches element name defined by `string` (not `RegExp`). Otherwise, returns `null`.
  150. *
  151. * @returns {String|null} Element name trying to match.
  152. */
  153. getElementName() {
  154. if ( this._patterns.length !== 1 ) {
  155. return null;
  156. }
  157. const pattern = this._patterns[ 0 ];
  158. const name = pattern.name;
  159. return ( typeof pattern != 'function' && name && !( name instanceof RegExp ) ) ? name : null;
  160. }
  161. }
  162. // Returns match information if {@link module:engine/view/element~Element element} is matching provided pattern.
  163. // If element cannot be matched to provided pattern - returns `null`.
  164. //
  165. // @param {module:engine/view/element~Element} element
  166. // @param {Object|String|RegExp|Function} pattern
  167. // @returns {Object|null} Returns object with match information or null if element is not matching.
  168. function isElementMatching( element, pattern ) {
  169. // If pattern is provided as function - return result of that function;
  170. if ( typeof pattern == 'function' ) {
  171. return pattern( element );
  172. }
  173. const match = {};
  174. // Check element's name.
  175. if ( pattern.name ) {
  176. match.name = matchName( pattern.name, element.name );
  177. if ( !match.name ) {
  178. return null;
  179. }
  180. }
  181. // Check element's attributes.
  182. if ( pattern.attributes ) {
  183. match.attributes = matchAttributes( pattern.attributes, element );
  184. if ( !match.attributes ) {
  185. return null;
  186. }
  187. }
  188. // Check element's classes.
  189. if ( pattern.classes ) {
  190. match.classes = matchClasses( pattern.classes, element );
  191. if ( !match.classes ) {
  192. return false;
  193. }
  194. }
  195. // Check element's styles.
  196. if ( pattern.styles ) {
  197. match.styles = matchStyles( pattern.styles, element );
  198. if ( !match.styles ) {
  199. return false;
  200. }
  201. }
  202. return match;
  203. }
  204. // Checks if name can be matched by provided pattern.
  205. //
  206. // @param {String|RegExp} pattern
  207. // @param {String} name
  208. // @returns {Boolean} Returns `true` if name can be matched, `false` otherwise.
  209. function matchName( pattern, name ) {
  210. // If pattern is provided as RegExp - test against this regexp.
  211. if ( pattern instanceof RegExp ) {
  212. return pattern.test( name );
  213. }
  214. return pattern === name;
  215. }
  216. // Checks if attributes of provided element can be matched against provided patterns.
  217. //
  218. // @param {Object} patterns Object with information about attributes to match. Each key of the object will be
  219. // used as attribute name. Value of each key can be a string or regular expression to match against attribute value.
  220. // @param {module:engine/view/element~Element} element Element which attributes will be tested.
  221. // @returns {Array|null} Returns array with matched attribute names or `null` if no attributes were matched.
  222. function matchAttributes( patterns, element ) {
  223. const match = [];
  224. for ( const name in patterns ) {
  225. const pattern = patterns[ name ];
  226. if ( element.hasAttribute( name ) ) {
  227. const attribute = element.getAttribute( name );
  228. if ( pattern === true ) {
  229. match.push( name );
  230. } else if ( pattern instanceof RegExp ) {
  231. if ( pattern.test( attribute ) ) {
  232. match.push( name );
  233. } else {
  234. return null;
  235. }
  236. } else if ( attribute === pattern ) {
  237. match.push( name );
  238. } else {
  239. return null;
  240. }
  241. } else {
  242. return null;
  243. }
  244. }
  245. return match;
  246. }
  247. // Checks if classes of provided element can be matched against provided patterns.
  248. //
  249. // @param {Array.<String|RegExp>} patterns Array of strings or regular expressions to match against element's classes.
  250. // @param {module:engine/view/element~Element} element Element which classes will be tested.
  251. // @returns {Array|null} Returns array with matched class names or `null` if no classes were matched.
  252. function matchClasses( patterns, element ) {
  253. const match = [];
  254. for ( const pattern of patterns ) {
  255. if ( pattern instanceof RegExp ) {
  256. const classes = element.getClassNames();
  257. for ( const name of classes ) {
  258. if ( pattern.test( name ) ) {
  259. match.push( name );
  260. }
  261. }
  262. if ( match.length === 0 ) {
  263. return null;
  264. }
  265. } else if ( element.hasClass( pattern ) ) {
  266. match.push( pattern );
  267. } else {
  268. return null;
  269. }
  270. }
  271. return match;
  272. }
  273. // Checks if styles of provided element can be matched against provided patterns.
  274. //
  275. // @param {Object} patterns Object with information about styles to match. Each key of the object will be
  276. // used as style name. Value of each key can be a string or regular expression to match against style value.
  277. // @param {module:engine/view/element~Element} element Element which styles will be tested.
  278. // @returns {Array|null} Returns array with matched style names or `null` if no styles were matched.
  279. function matchStyles( patterns, element ) {
  280. const match = [];
  281. for ( const name in patterns ) {
  282. const pattern = patterns[ name ];
  283. if ( element.hasStyle( name ) ) {
  284. const style = element.getStyle( name );
  285. if ( pattern instanceof RegExp ) {
  286. if ( pattern.test( style ) ) {
  287. match.push( name );
  288. } else {
  289. return null;
  290. }
  291. } else if ( style === pattern ) {
  292. match.push( name );
  293. } else {
  294. return null;
  295. }
  296. } else {
  297. return null;
  298. }
  299. }
  300. return match;
  301. }
  302. /**
  303. * An entity that is a valid pattern recognized by a matcher. `MatcherPattern` is used by {@link ~Matcher} to recognize
  304. * if a view element fits in a group of view elements described by the pattern.
  305. *
  306. * `MatcherPattern` can be given as a `String`, a `RegExp`, an `Object` or a `Function`.
  307. *
  308. * If `MatcherPattern` is given as a `String` or `RegExp`, it will match any view element that has a matching name:
  309. *
  310. * // Match any element with name equal to 'div'.
  311. * const pattern = 'div';
  312. *
  313. * // Match any element which name starts on 'p'.
  314. * const pattern = /^p/;
  315. *
  316. * If `MatcherPattern` is given as an `Object`, all the object's properties will be matched with view element properties.
  317. *
  318. * // Match view element's name.
  319. * const pattern = { name: /^p/ };
  320. *
  321. * // Match view element which has matching attributes.
  322. * const pattern = {
  323. * attribute: {
  324. * title: 'foobar', // Attribute title should equal 'foobar'.
  325. * foo: /^\w+/, // Attribute foo should match /^\w+/ regexp.
  326. * bar: true // Attribute bar should be set (can be empty).
  327. * }
  328. * };
  329. *
  330. * // Match view element which has given class.
  331. * const pattern = {
  332. * classes: 'foobar'
  333. * };
  334. *
  335. * // Match view element class using regular expression.
  336. * const pattern = {
  337. * classes: /foo.../
  338. * };
  339. *
  340. * // Multiple classes to match.
  341. * const pattern = {
  342. * classes: [ 'baz', 'bar', /foo.../ ]
  343. * }:
  344. *
  345. * // Match view element which has given styles.
  346. * const pattern = {
  347. * styles: {
  348. * position: 'absolute',
  349. * color: /^\w*blue$/
  350. * }
  351. * };
  352. *
  353. * // Pattern with multiple properties.
  354. * const pattern = {
  355. * name: 'span',
  356. * styles: {
  357. * 'font-weight': 'bold'
  358. * },
  359. * classes: 'highlighted'
  360. * };
  361. *
  362. * If `MatcherPattern` is given as a `Function`, the function takes a view element as a first and only parameter and
  363. * the function should decide whether that element matches. If so, it should return what part of the view element has been matched.
  364. * Otherwise, the function should return `null`. The returned result will be included in `match` property of the object
  365. * returned by {@link ~Matcher#match} call.
  366. *
  367. * // Match an empty <div> element.
  368. * const pattern = element => {
  369. * if ( element.name == 'div' && element.childCount > 0 ) {
  370. * // Return which part of the element was matched.
  371. * return { name: true };
  372. * }
  373. *
  374. * return null;
  375. * };
  376. *
  377. * // Match a <p> element with big font ("heading-like" element).
  378. * const pattern = element => {
  379. * if ( element.name == 'p' ) {
  380. * const fontSize = element.getStyle( 'font-size' );
  381. * const size = fontSize.match( /(\d+)/px );
  382. *
  383. * if ( size && Number( size[ 1 ] ) > 26 ) {
  384. * return { name: true, attribute: [ 'font-size' ] };
  385. * }
  386. * }
  387. *
  388. * return null;
  389. * };
  390. *
  391. * `MatcherPattern` is defined in a way that it is a superset of {@link module:engine/view/elementdefinition~ElementDefinition},
  392. * that is, every `ElementDefinition` also can be used as a `MatcherPattern`.
  393. *
  394. * @typedef {String|RegExp|Object|Function} module:engine/view/matcher~MatcherPattern
  395. *
  396. * @property {String|RegExp} [name] View element name to match.
  397. * @property {String|RegExp|Array.<String|RegExp>} [classes] View element's class name(s) to match.
  398. * @property {Object} [styles] Object with key-value pairs representing styles to match.
  399. * Each object key represents style name. Value can be given as `String` or `RegExp`.
  400. * @property {Object} [attributes] Object with key-value pairs representing attributes to match.
  401. * Each object key represents attribute name. Value can be given as `String` or `RegExp`.
  402. */