styles.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module engine/view/styles
  7. */
  8. import { get, has, isObject, isPlainObject, merge, set, unset } from 'lodash-es';
  9. const setOnPathStyles = [
  10. // Margin & padding.
  11. 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
  12. 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
  13. // Background.
  14. 'background-color'
  15. ];
  16. /**
  17. * Styles class.
  18. *
  19. * Handles styles normalization.
  20. */
  21. export default class Styles {
  22. /**
  23. * Creates Styles instance.
  24. *
  25. * @param {String} styleString Initial styles value.
  26. */
  27. constructor( styleString = '' ) {
  28. this._styles = {};
  29. this.parsers = new Map();
  30. this.parsers.set( 'border', parseBorder );
  31. this.parsers.set( 'border-top', parseBorderSide( 'top' ) );
  32. this.parsers.set( 'border-right', parseBorderSide( 'right' ) );
  33. this.parsers.set( 'border-bottom', parseBorderSide( 'bottom' ) );
  34. this.parsers.set( 'border-left', parseBorderSide( 'left' ) );
  35. this.parsers.set( 'border-color', parseBorderProperty( 'color' ) );
  36. this.parsers.set( 'border-width', parseBorderProperty( 'width' ) );
  37. this.parsers.set( 'border-style', parseBorderProperty( 'style' ) );
  38. this.parsers.set( 'background', parseBackground );
  39. this.parsers.set( 'margin', parseShorthandSides( 'margin' ) );
  40. this.parsers.set( 'padding', parseShorthandSides( 'padding' ) );
  41. this.setStyle( styleString );
  42. }
  43. /**
  44. * Number of styles defined.
  45. *
  46. * @type {Number}
  47. */
  48. get size() {
  49. return this.getStyleNames().length;
  50. }
  51. /**
  52. * Re-sets internal styles definition.
  53. *
  54. * @param styleString
  55. */
  56. setStyle( styleString = '' ) {
  57. this.clear();
  58. const map = parseInlineStyles( styleString );
  59. for ( const key of map.keys() ) {
  60. const value = map.get( key );
  61. this._parseProperty( key, value );
  62. }
  63. }
  64. /**
  65. * Checks if single style rule is set.
  66. *
  67. * Supports shorthands.
  68. *
  69. * @param {String} name
  70. * @returns {Boolean}
  71. */
  72. hasProperty( name ) {
  73. const nameNorm = toPath( name );
  74. return has( this._styles, nameNorm ) || !!this._styles[ name ];
  75. }
  76. /**
  77. * Inserts single style rule.
  78. *
  79. * Supports shorthands.
  80. *
  81. * @param {String|Object} nameOrObject
  82. * @param {String|Object} value
  83. * @returns {Boolean}
  84. */
  85. insertProperty( nameOrObject, value ) {
  86. if ( isPlainObject( nameOrObject ) ) {
  87. for ( const key of Object.keys( nameOrObject ) ) {
  88. this.insertProperty( key, nameOrObject[ key ] );
  89. }
  90. } else {
  91. this._parseProperty( nameOrObject, value );
  92. }
  93. }
  94. removeProperty( name ) {
  95. unset( this._styles, toPath( name ) );
  96. delete this._styles[ name ];
  97. }
  98. getNormalized( name ) {
  99. if ( !name ) {
  100. return merge( {}, this._styles );
  101. }
  102. const path = toPath( name );
  103. if ( has( this._styles, path ) ) {
  104. return get( this._styles, path );
  105. } else {
  106. return this._styles[ name ];
  107. }
  108. }
  109. getInlineStyle() {
  110. const parsed = [];
  111. const keys = Object.keys( this._styles ).sort();
  112. if ( !keys.length ) {
  113. return;
  114. }
  115. for ( const key of keys ) {
  116. const normalized = this.getNormalized( key );
  117. parsed.push( toInlineStyle( key, normalized ) );
  118. }
  119. return parsed.join( ';' ) + ';';
  120. }
  121. getInlineProperty( name ) {
  122. const normalized = this.getNormalized( name );
  123. if ( !normalized ) {
  124. // Try return directly
  125. return this._styles[ name ];
  126. }
  127. if ( isObject( normalized ) ) {
  128. return toInlineStyleProperty( name, normalized );
  129. }
  130. // String value
  131. else {
  132. return normalized;
  133. }
  134. }
  135. getStyleNames() {
  136. const inlineStyle = this.getInlineStyle();
  137. return ( inlineStyle || '' ).split( ';' ).filter( f => f !== '' ).map( abc => abc.split( ':' )[ 0 ] ).sort();
  138. }
  139. clear() {
  140. this._styles = {};
  141. }
  142. _appendStyleValue( nameOrPath, valueOrObject ) {
  143. if ( typeof valueOrObject === 'object' ) {
  144. if ( nameOrPath.includes( '.' ) ) {
  145. const got = get( this._styles, nameOrPath );
  146. set( this._styles, nameOrPath, merge( {}, got, valueOrObject ) );
  147. } else {
  148. this._styles[ nameOrPath ] = merge( {}, this._styles[ nameOrPath ], valueOrObject );
  149. }
  150. } else {
  151. set( this._styles, nameOrPath, valueOrObject );
  152. }
  153. }
  154. _parseProperty( key, value ) {
  155. if ( isPlainObject( value ) ) {
  156. this._appendStyleValue( toPath( key ), value );
  157. return;
  158. }
  159. // Set directly to an object.
  160. if ( setOnPathStyles.includes( key ) ) {
  161. this._appendStyleValue( toPath( key ), value );
  162. return;
  163. }
  164. if ( this.parsers.has( key ) ) {
  165. const parser = this.parsers.get( key );
  166. this._styles = merge( {}, this._styles, parser( value ) );
  167. } else {
  168. this._appendStyleValue( key, value );
  169. }
  170. }
  171. }
  172. function getTopRightBottomLeftValues( value = '' ) {
  173. const values = value.split( ' ' );
  174. const top = values[ 0 ];
  175. const bottom = values[ 2 ] || top;
  176. const right = values[ 1 ] || top;
  177. const left = values[ 3 ] || right;
  178. return { top, bottom, right, left };
  179. }
  180. function toBorderPropertyShorthand( value, property ) {
  181. return {
  182. [ property ]: getTopRightBottomLeftValues( value )
  183. };
  184. }
  185. function parseShorthandSides( longhand ) {
  186. return value => {
  187. return { [ longhand ]: getTopRightBottomLeftValues( value ) };
  188. };
  189. }
  190. function parseBorder( value ) {
  191. const { color, style, width } = parseShorthandBorderAttribute( value );
  192. return {
  193. border: {
  194. color: getTopRightBottomLeftValues( color ),
  195. style: getTopRightBottomLeftValues( style ),
  196. width: getTopRightBottomLeftValues( width )
  197. }
  198. };
  199. }
  200. function parseBorderSide( side ) {
  201. return value => {
  202. const { color, style, width } = parseShorthandBorderAttribute( value );
  203. const border = {};
  204. if ( color !== undefined ) {
  205. border.color = { [ side ]: color };
  206. }
  207. if ( style !== undefined ) {
  208. border.style = { [ side ]: style };
  209. }
  210. if ( width !== undefined ) {
  211. border.width = { [ side ]: width };
  212. }
  213. return { border };
  214. };
  215. }
  216. function parseBorderProperty( foo ) {
  217. return value => ( {
  218. border: toBorderPropertyShorthand( value, foo )
  219. } );
  220. }
  221. function parseShorthandBorderAttribute( string ) {
  222. const result = {};
  223. for ( const part of string.split( ' ' ) ) {
  224. if ( isLength( part ) ) {
  225. result.width = part;
  226. }
  227. if ( isLineStyle( part ) ) {
  228. result.style = part;
  229. }
  230. if ( isColor( part ) ) {
  231. result.color = part;
  232. }
  233. }
  234. return result;
  235. }
  236. function parseBackground( value ) {
  237. const background = {};
  238. const parts = value.split( ' ' );
  239. for ( const part of parts ) {
  240. if ( isColor( part ) ) {
  241. background.color = part;
  242. }
  243. }
  244. return { background };
  245. }
  246. function isColor( string ) {
  247. return /^([#0-9A-Fa-f]{3,8}|[a-zA-Z]+)$/.test( string ) && !isLineStyle( string );
  248. }
  249. function isLineStyle( string ) {
  250. return /^(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/.test( string );
  251. }
  252. function isLength( string ) {
  253. return /^[+-]?[0-9]?[.]?[0-9]+([a-z]+|%)$/.test( string );
  254. }
  255. function printSingleValues( { top, right, bottom, left }, prefix ) {
  256. const ret = [];
  257. if ( top ) {
  258. ret.push( prefix + '-top:' + top );
  259. }
  260. if ( right ) {
  261. ret.push( prefix + '-right:' + right );
  262. }
  263. if ( bottom ) {
  264. ret.push( prefix + '-bottom:' + bottom );
  265. }
  266. if ( left ) {
  267. ret.push( prefix + '-left:' + left );
  268. }
  269. return ret.join( ';' );
  270. }
  271. function shBorder( which ) {
  272. return value => {
  273. return outputShorthandableValue( value[ which ], false, `border-${ which }` );
  274. };
  275. }
  276. function getABCDEDGHIJK( { left, right, top, bottom } ) {
  277. const out = [];
  278. if ( left !== right ) {
  279. out.push( top, right, bottom, left );
  280. } else if ( bottom !== top ) {
  281. out.push( top, right, bottom );
  282. } else if ( right != top ) {
  283. out.push( top, right );
  284. } else {
  285. out.push( top );
  286. }
  287. return out;
  288. }
  289. function outputShorthandableValue( styleObject = {}, strict, styleShorthand ) {
  290. const { top, right, bottom, left } = styleObject;
  291. if ( top === left && left === bottom && bottom === right ) {
  292. // Might be not set.
  293. if ( top === undefined ) {
  294. return '';
  295. }
  296. return ( strict ? '' : styleShorthand + ':' ) + top;
  297. } else if ( ![ top, right, left, bottom ].every( value => !!value ) ) {
  298. return printSingleValues( { top, right, bottom, left }, 'margin' );
  299. } else {
  300. const out = getABCDEDGHIJK( styleObject );
  301. return `${ strict ? '' : styleShorthand + ':' }${ out.join( ' ' ) }`;
  302. }
  303. }
  304. function stringifyBorderProperty( styleObjectOrString ) {
  305. const top = toInlineBorder( styleObjectOrString.top );
  306. const right = toInlineBorder( styleObjectOrString.right );
  307. const bottom = toInlineBorder( styleObjectOrString.bottom );
  308. const left = toInlineBorder( styleObjectOrString.left );
  309. if ( top === right && right === bottom && bottom === left ) {
  310. return top;
  311. }
  312. }
  313. function toInlineStyleProperty( styleName, styleObjectOrString ) {
  314. if ( styleName === 'border' ) {
  315. return stringifyBorderProperty( styleObjectOrString );
  316. }
  317. if ( styleName === 'border-color' ) {
  318. return outputShorthandableValue( styleObjectOrString, true, 'border-color' );
  319. }
  320. if ( styleName === 'border-style' ) {
  321. return outputShorthandableValue( styleObjectOrString, true, 'border-style' );
  322. }
  323. if ( styleName === 'border-width' ) {
  324. return outputShorthandableValue( styleObjectOrString, true, 'border-width' );
  325. }
  326. if ( styleName === 'margin' ) {
  327. return outputShorthandableValue( styleObjectOrString, true, 'margin' );
  328. }
  329. if ( styleName === 'padding' ) {
  330. return outputShorthandableValue( styleObjectOrString, true, 'padding' );
  331. }
  332. return styleObjectOrString;
  333. }
  334. function leWhat( styleObjectOrString, styleName ) {
  335. const values = [];
  336. for ( const key of Object.keys( styleObjectOrString ) ) {
  337. let styleObjectOrStringElement;
  338. if ( isObject( styleObjectOrString[ key ] ) ) {
  339. styleObjectOrStringElement = outputShorthandableValue( styleObjectOrString[ key ], true, styleName + 'key' );
  340. } else {
  341. styleObjectOrStringElement = styleObjectOrString[ key ];
  342. }
  343. values.push( `${ styleName }-${ key }:${ styleObjectOrStringElement }` );
  344. }
  345. return values.join( ';' );
  346. }
  347. function toInlineStyle( styleName, styleObjectOrString ) {
  348. const inliners = new Map();
  349. inliners.set( 'border-color', shBorder( 'color' ) );
  350. inliners.set( 'border-style', shBorder( 'style' ) );
  351. inliners.set( 'border-width', shBorder( 'width' ) );
  352. inliners.set( 'margin', value => outputShorthandableValue( value, false, 'margin' ) );
  353. inliners.set( 'padding', value => outputShorthandableValue( value, false, 'padding' ) );
  354. if ( inliners.has( styleName ) ) {
  355. const inliner = inliners.get( styleName );
  356. return inliner( styleObjectOrString );
  357. }
  358. // Generic, one-level, object to style:
  359. if ( isObject( styleObjectOrString ) ) {
  360. return leWhat( styleObjectOrString, styleName );
  361. }
  362. return `${ styleName }:${ styleObjectOrString }`;
  363. }
  364. function toInlineBorder( object = {} ) {
  365. const style = [];
  366. if ( object.width ) {
  367. style.push( object.width );
  368. }
  369. if ( object.style ) {
  370. style.push( object.style );
  371. }
  372. if ( object.color ) {
  373. style.push( object.color );
  374. }
  375. return style.join( ' ' );
  376. }
  377. // Parses inline styles and puts property - value pairs into styles map.
  378. //
  379. // @param {String} stylesString Styles to parse.
  380. // @returns {Map.<String, String>} stylesMap Map of parsed properties and values.
  381. function parseInlineStyles( stylesString ) {
  382. // `null` if no quote was found in input string or last found quote was a closing quote. See below.
  383. let quoteType = null;
  384. let propertyNameStart = 0;
  385. let propertyValueStart = 0;
  386. let propertyName = null;
  387. const stylesMap = new Map();
  388. // Do not set anything if input string is empty.
  389. if ( stylesString === '' ) {
  390. return stylesMap;
  391. }
  392. // Fix inline styles that do not end with `;` so they are compatible with algorithm below.
  393. if ( stylesString.charAt( stylesString.length - 1 ) != ';' ) {
  394. stylesString = stylesString + ';';
  395. }
  396. // Seek the whole string for "special characters".
  397. for ( let i = 0; i < stylesString.length; i++ ) {
  398. const char = stylesString.charAt( i );
  399. if ( quoteType === null ) {
  400. // No quote found yet or last found quote was a closing quote.
  401. switch ( char ) {
  402. case ':':
  403. // Most of time colon means that property name just ended.
  404. // Sometimes however `:` is found inside property value (for example in background image url).
  405. if ( !propertyName ) {
  406. // Treat this as end of property only if property name is not already saved.
  407. // Save property name.
  408. propertyName = stylesString.substr( propertyNameStart, i - propertyNameStart );
  409. // Save this point as the start of property value.
  410. propertyValueStart = i + 1;
  411. }
  412. break;
  413. case '"':
  414. case '\'':
  415. // Opening quote found (this is an opening quote, because `quoteType` is `null`).
  416. quoteType = char;
  417. break;
  418. case ';': {
  419. // Property value just ended.
  420. // Use previously stored property value start to obtain property value.
  421. const propertyValue = stylesString.substr( propertyValueStart, i - propertyValueStart );
  422. if ( propertyName ) {
  423. // Save parsed part.
  424. stylesMap.set( propertyName.trim(), propertyValue.trim() );
  425. }
  426. propertyName = null;
  427. // Save this point as property name start. Property name starts immediately after previous property value ends.
  428. propertyNameStart = i + 1;
  429. break;
  430. }
  431. }
  432. } else if ( char === quoteType ) {
  433. // If a quote char is found and it is a closing quote, mark this fact by `null`-ing `quoteType`.
  434. quoteType = null;
  435. }
  436. }
  437. return stylesMap;
  438. }
  439. function toPath( name ) {
  440. return name.replace( '-', '.' );
  441. }
  442. // 'border-style' -> d{}
  443. // 'border-top' -> d{}
  444. // 'border' -> d{}
  445. // {} -> style=""
  446. // {} -> border-top=""