styles.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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( ...newNewGetStyleFromNormalized( key, normalized ) );
  118. }
  119. return parsed
  120. .filter( v => Array.isArray( v ) )// TODO: not needed?
  121. .map( arr => arr.join( ':' ) )
  122. .join( ';' ) + ';';
  123. }
  124. getInlineProperty( propertyName ) {
  125. const normalized = this.getNormalized( propertyName );
  126. if ( !normalized ) {
  127. // Try return directly
  128. return this._styles[ propertyName ];
  129. }
  130. if ( isObject( normalized ) ) {
  131. const ret = toInlineStyleProperty( propertyName, normalized );
  132. if ( Array.isArray( ret ) ) {
  133. return ret[ 1 ];
  134. } else {
  135. return '';
  136. }
  137. }
  138. // String value
  139. else {
  140. return normalized;
  141. }
  142. }
  143. getStyleNames() {
  144. const inlineStyle = this.getInlineStyle();
  145. return ( inlineStyle || '' )
  146. .split( ';' )
  147. .filter( f => f !== '' )
  148. .map( abc => abc.split( ':' )[ 0 ] )
  149. .sort( sortTopRightBottomLeftProperties );
  150. }
  151. clear() {
  152. this._styles = {};
  153. }
  154. _appendStyleValue( nameOrPath, valueOrObject ) {
  155. if ( typeof valueOrObject === 'object' ) {
  156. if ( nameOrPath.includes( '.' ) ) {
  157. const got = get( this._styles, nameOrPath );
  158. set( this._styles, nameOrPath, merge( {}, got, valueOrObject ) );
  159. } else {
  160. this._styles[ nameOrPath ] = merge( {}, this._styles[ nameOrPath ], valueOrObject );
  161. }
  162. } else {
  163. set( this._styles, nameOrPath, valueOrObject );
  164. }
  165. }
  166. _parseProperty( key, value ) {
  167. if ( isPlainObject( value ) ) {
  168. this._appendStyleValue( toPath( key ), value );
  169. return;
  170. }
  171. // Set directly to an object.
  172. if ( setOnPathStyles.includes( key ) ) {
  173. this._appendStyleValue( toPath( key ), value );
  174. return;
  175. }
  176. if ( this.parsers.has( key ) ) {
  177. const parser = this.parsers.get( key );
  178. this._styles = merge( {}, this._styles, parser( value ) );
  179. } else {
  180. this._appendStyleValue( key, value );
  181. }
  182. }
  183. }
  184. function getTopRightBottomLeftValues( value = '' ) {
  185. const values = value.split( ' ' );
  186. const top = values[ 0 ];
  187. const bottom = values[ 2 ] || top;
  188. const right = values[ 1 ] || top;
  189. const left = values[ 3 ] || right;
  190. return { top, bottom, right, left };
  191. }
  192. function toBorderPropertyShorthand( value, property ) {
  193. return {
  194. [ property ]: getTopRightBottomLeftValues( value )
  195. };
  196. }
  197. function parseShorthandSides( longhand ) {
  198. return value => {
  199. return { [ longhand ]: getTopRightBottomLeftValues( value ) };
  200. };
  201. }
  202. function parseBorder( value ) {
  203. const { color, style, width } = parseShorthandBorderAttribute( value );
  204. return {
  205. border: {
  206. color: getTopRightBottomLeftValues( color ),
  207. style: getTopRightBottomLeftValues( style ),
  208. width: getTopRightBottomLeftValues( width )
  209. }
  210. };
  211. }
  212. function parseBorderSide( side ) {
  213. return value => {
  214. const { color, style, width } = parseShorthandBorderAttribute( value );
  215. const border = {};
  216. if ( color !== undefined ) {
  217. border.color = { [ side ]: color };
  218. }
  219. if ( style !== undefined ) {
  220. border.style = { [ side ]: style };
  221. }
  222. if ( width !== undefined ) {
  223. border.width = { [ side ]: width };
  224. }
  225. return { border };
  226. };
  227. }
  228. function parseBorderProperty( foo ) {
  229. return value => ( {
  230. border: toBorderPropertyShorthand( value, foo )
  231. } );
  232. }
  233. function parseShorthandBorderAttribute( string ) {
  234. const result = {};
  235. for ( const part of string.split( ' ' ) ) {
  236. if ( isLength( part ) ) {
  237. result.width = part;
  238. }
  239. if ( isLineStyle( part ) ) {
  240. result.style = part;
  241. }
  242. if ( isColor( part ) ) {
  243. result.color = part;
  244. }
  245. }
  246. return result;
  247. }
  248. function parseBackground( value ) {
  249. const background = {};
  250. const parts = value.split( ' ' );
  251. for ( const part of parts ) {
  252. if ( isColor( part ) ) {
  253. background.color = part;
  254. }
  255. }
  256. return { background };
  257. }
  258. function isColor( string ) {
  259. return /^([#0-9A-Fa-f]{3,8}|[a-zA-Z]+)$/.test( string ) && !isLineStyle( string );
  260. }
  261. function isLineStyle( string ) {
  262. return /^(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/.test( string );
  263. }
  264. function isLength( string ) {
  265. return /^[+-]?[0-9]?[.]?[0-9]+([a-z]+|%)$/.test( string );
  266. }
  267. function printSingleValues( { top, right, bottom, left }, prefix ) {
  268. const ret = [];
  269. if ( top ) {
  270. ret.push( [ prefix + '-top', top ] );
  271. }
  272. if ( right ) {
  273. ret.push( [ prefix + '-right', right ] );
  274. }
  275. if ( bottom ) {
  276. ret.push( [ prefix + '-bottom', bottom ] );
  277. }
  278. if ( left ) {
  279. ret.push( [ prefix + '-left', left ] );
  280. }
  281. return ret;
  282. }
  283. function shBorderProperty( which ) {
  284. return value => {
  285. return outputShorthandableValue( value, false, `border-${ which }` );
  286. };
  287. }
  288. function getTopRightBottomLeftShorthand( { left, right, top, bottom } ) {
  289. const out = [];
  290. if ( left !== right ) {
  291. out.push( top, right, bottom, left );
  292. } else if ( bottom !== top ) {
  293. out.push( top, right, bottom );
  294. } else if ( right !== top ) {
  295. out.push( top, right );
  296. } else {
  297. out.push( top );
  298. }
  299. return out.join( ' ' );
  300. }
  301. function outputShorthandableValue( styleObject = {}, strict, styleShorthand ) {
  302. const { top, right, bottom, left } = styleObject;
  303. if ( top === left && left === bottom && bottom === right ) {
  304. // Might be not set.
  305. if ( top === undefined ) {
  306. return [];
  307. }
  308. return [ [ styleShorthand, top ] ];
  309. } else if ( ![ top, right, left, bottom ].every( value => !!value ) ) {
  310. return printSingleValues( { top, right, bottom, left }, styleShorthand );
  311. } else {
  312. return [ [ styleShorthand, getTopRightBottomLeftShorthand( styleObject ) ] ];
  313. }
  314. }
  315. function newNewGetStyleFromNormalized( styleName, styleObjectOrString ) {
  316. const styleGetters = new Map();
  317. styleGetters.set( 'border-color', shBorderProperty( 'color' ) );
  318. styleGetters.set( 'border-style', shBorderProperty( 'style' ) );
  319. styleGetters.set( 'border-width', shBorderProperty( 'width' ) );
  320. styleGetters.set( 'border', value => {
  321. const ret = [];
  322. ret.push( ...shBorderProperty( 'color' )( value.color ) );
  323. ret.push( ...shBorderProperty( 'style' )( value.style ) );
  324. ret.push( ...shBorderProperty( 'width' )( value.width ) );
  325. return ret;
  326. } );
  327. styleGetters.set( 'margin', value => {
  328. return outputShorthandableValue( value, false, 'margin' );
  329. } );
  330. styleGetters.set( 'background', value => {
  331. const ret = [];
  332. ret.push( [ 'background-color', value.color ] );
  333. return ret;
  334. } );
  335. let stylesArray;
  336. if ( styleGetters.has( styleName ) ) {
  337. const styleGetter = styleGetters.get( styleName );
  338. stylesArray = styleGetter( styleObjectOrString );
  339. } else {
  340. stylesArray = [ [ styleName, styleObjectOrString ] ];
  341. }
  342. return stylesArray || [];
  343. }
  344. function toInlineStyleProperty( styleName, styleObjectOrString ) {
  345. const styles = newNewGetStyleFromNormalized( styleName, styleObjectOrString );
  346. return styles.find( ( [ property ] ) => property === styleName );
  347. }
  348. const topRightBottomLeftOrder = [ 'top', 'right', 'bottom', 'left' ];
  349. function sortTopRightBottomLeftProperties( a, b ) {
  350. if ( topRightBottomLeftOrder.includes( a ) && topRightBottomLeftOrder.includes( b ) ) {
  351. return topRightBottomLeftOrder.indexOf( a ) - topRightBottomLeftOrder.indexOf( b );
  352. }
  353. return 0;
  354. }
  355. // Parses inline styles and puts property - value pairs into styles map.
  356. //
  357. // @param {String} stylesString Styles to parse.
  358. // @returns {Map.<String, String>} stylesMap Map of parsed properties and values.
  359. function parseInlineStyles( stylesString ) {
  360. // `null` if no quote was found in input string or last found quote was a closing quote. See below.
  361. let quoteType = null;
  362. let propertyNameStart = 0;
  363. let propertyValueStart = 0;
  364. let propertyName = null;
  365. const stylesMap = new Map();
  366. // Do not set anything if input string is empty.
  367. if ( stylesString === '' ) {
  368. return stylesMap;
  369. }
  370. // Fix inline styles that do not end with `;` so they are compatible with algorithm below.
  371. if ( stylesString.charAt( stylesString.length - 1 ) != ';' ) {
  372. stylesString = stylesString + ';';
  373. }
  374. // Seek the whole string for "special characters".
  375. for ( let i = 0; i < stylesString.length; i++ ) {
  376. const char = stylesString.charAt( i );
  377. if ( quoteType === null ) {
  378. // No quote found yet or last found quote was a closing quote.
  379. switch ( char ) {
  380. case ':':
  381. // Most of time colon means that property name just ended.
  382. // Sometimes however `:` is found inside property value (for example in background image url).
  383. if ( !propertyName ) {
  384. // Treat this as end of property only if property name is not already saved.
  385. // Save property name.
  386. propertyName = stylesString.substr( propertyNameStart, i - propertyNameStart );
  387. // Save this point as the start of property value.
  388. propertyValueStart = i + 1;
  389. }
  390. break;
  391. case '"':
  392. case '\'':
  393. // Opening quote found (this is an opening quote, because `quoteType` is `null`).
  394. quoteType = char;
  395. break;
  396. case ';': {
  397. // Property value just ended.
  398. // Use previously stored property value start to obtain property value.
  399. const propertyValue = stylesString.substr( propertyValueStart, i - propertyValueStart );
  400. if ( propertyName ) {
  401. // Save parsed part.
  402. stylesMap.set( propertyName.trim(), propertyValue.trim() );
  403. }
  404. propertyName = null;
  405. // Save this point as property name start. Property name starts immediately after previous property value ends.
  406. propertyNameStart = i + 1;
  407. break;
  408. }
  409. }
  410. } else if ( char === quoteType ) {
  411. // If a quote char is found and it is a closing quote, mark this fact by `null`-ing `quoteType`.
  412. quoteType = null;
  413. }
  414. }
  415. return stylesMap;
  416. }
  417. function toPath( name ) {
  418. return name.replace( '-', '.' );
  419. }