/
stylesmap.ts
1039 lines (931 loc) · 27.2 KB
/
stylesmap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module engine/view/stylesmap
*/
import { get, isObject, merge, set, unset } from 'lodash-es';
/**
* Styles map. Allows handling (adding, removing, retrieving) a set of style rules (usually, of an element).
*/
export default class StylesMap {
/**
* Keeps an internal representation of styles map. Normalized styles are kept as object tree to allow unified modification and
* value access model using lodash's get, set, unset, etc methods.
*
* When no style processor rules are defined it acts as simple key-value storage.
*/
private _styles: Styles;
/**
* An instance of the {@link module:engine/view/stylesmap~StylesProcessor}.
*/
private readonly _styleProcessor: StylesProcessor;
/**
* Creates Styles instance.
*/
constructor( styleProcessor: StylesProcessor ) {
this._styles = {};
this._styleProcessor = styleProcessor;
}
/**
* Returns true if style map has no styles set.
*/
public get isEmpty(): boolean {
const entries = Object.entries( this._styles );
return !entries.length;
}
/**
* Number of styles defined.
*/
public get size(): number {
if ( this.isEmpty ) {
return 0;
}
return this.getStyleNames().length;
}
/**
* Set styles map to a new value.
*
* ```ts
* styles.setTo( 'border:1px solid blue;margin-top:1px;' );
* ```
*/
public setTo( inlineStyle: string ): void {
this.clear();
const parsedStyles = parseInlineStyles( inlineStyle );
for ( const [ key, value ] of parsedStyles ) {
this._styleProcessor.toNormalizedForm( key, value, this._styles );
}
}
/**
* Checks if a given style is set.
*
* ```ts
* styles.setTo( 'margin-left:1px;' );
*
* styles.has( 'margin-left' ); // -> true
* styles.has( 'padding' ); // -> false
* ```
*
* **Note**: This check supports normalized style names.
*
* ```ts
* // Enable 'margin' shorthand processing:
* editor.data.addStyleProcessorRules( addMarginRules );
*
* styles.setTo( 'margin:2px;' );
*
* styles.has( 'margin' ); // -> true
* styles.has( 'margin-top' ); // -> true
* styles.has( 'margin-left' ); // -> true
*
* styles.remove( 'margin-top' );
*
* styles.has( 'margin' ); // -> false
* styles.has( 'margin-top' ); // -> false
* styles.has( 'margin-left' ); // -> true
* ```
*
* @param name Style name.
*/
public has( name: string ): boolean {
if ( this.isEmpty ) {
return false;
}
const styles = this._styleProcessor.getReducedForm( name, this._styles );
const propertyDescriptor = styles.find( ( [ property ] ) => property === name );
// Only return a value if it is set;
return Array.isArray( propertyDescriptor );
}
/**
* Sets a given style.
*
* Can insert one by one:
*
* ```ts
* styles.set( 'color', 'blue' );
* styles.set( 'margin-right', '1em' );
* ```
*
* ***Note**:* This method uses {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules
* enabled style processor rules} to normalize passed values.
*
* ```ts
* // Enable 'margin' shorthand processing:
* editor.data.addStyleProcessorRules( addMarginRules );
*
* styles.set( 'margin', '2px' );
* ```
*
* The above code will set margin to:
*
* ```ts
* styles.getNormalized( 'margin' );
* // -> { top: '2px', right: '2px', bottom: '2px', left: '2px' }
* ```
*
* Which makes it possible to retrieve a "sub-value":
*
* ```ts
* styles.get( 'margin-left' ); // -> '2px'
* ```
*
* Or modify it:
*
* ```ts
* styles.remove( 'margin-left' );
*
* styles.getNormalized( 'margin' ); // -> { top: '1px', bottom: '1px', right: '1px' }
* styles.toString(); // -> 'margin-bottom:1px;margin-right:1px;margin-top:1px;'
* ```
*
* This method also allows to set normalized values directly (if a particular styles processor rule was enabled):
*
* ```ts
* styles.set( 'border-color', { top: 'blue' } );
* styles.set( 'margin', { right: '2em' } );
*
* styles.toString(); // -> 'border-color-top:blue;margin-right:2em;'
* ```
*
* @label KEY_VALUE
* @param name Style property name.
* @param value Value to set.
*/
public set( name: string, value: StyleValue ): void;
/**
* Sets many styles at once:
*
* ```ts
* styles.set( {
* color: 'blue',
* 'margin-right': '1em'
* } );
* ```
*
* It is equivalent to:
*
* ```ts
* styles.set( 'color', 'blue' );
* styles.set( 'margin-right', '1em' );
* ```
*
* See {@link #set:KEY_VALUE}
*
* @label CONFIG_OBJECT
*/
public set( styles: Styles ): void;
public set( nameOrObject: string | Styles, valueOrObject?: StyleValue ): void {
if ( isObject( nameOrObject ) ) {
for ( const [ key, value ] of Object.entries( nameOrObject ) ) {
this._styleProcessor.toNormalizedForm( key, value, this._styles );
}
} else {
this._styleProcessor.toNormalizedForm( nameOrObject, valueOrObject!, this._styles );
}
}
/**
* Removes given style.
*
* ```ts
* styles.setTo( 'background:#f00;margin-right:2px;' );
*
* styles.remove( 'background' );
*
* styles.toString(); // -> 'margin-right:2px;'
* ```
*
* ***Note**:* This method uses {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules
* enabled style processor rules} to normalize passed values.
*
* ```ts
* // Enable 'margin' shorthand processing:
* editor.data.addStyleProcessorRules( addMarginRules );
*
* styles.setTo( 'margin:1px' );
*
* styles.remove( 'margin-top' );
* styles.remove( 'margin-right' );
*
* styles.toString(); // -> 'margin-bottom:1px;margin-left:1px;'
* ```
*
* @param name Style name.
*/
public remove( name: string ): void {
const path = toPath( name );
unset( this._styles, path );
delete this._styles[ name ];
this._cleanEmptyObjectsOnPath( path );
}
/**
* Returns a normalized style object or a single value.
*
* ```ts
* // Enable 'margin' shorthand processing:
* editor.data.addStyleProcessorRules( addMarginRules );
*
* const styles = new Styles();
* styles.setTo( 'margin:1px 2px 3em;' );
*
* styles.getNormalized( 'margin' );
* // will log:
* // {
* // top: '1px',
* // right: '2px',
* // bottom: '3em',
* // left: '2px' // normalized value from margin shorthand
* // }
*
* styles.getNormalized( 'margin-left' ); // -> '2px'
* ```
*
* **Note**: This method will only return normalized styles if a style processor was defined.
*
* @param name Style name.
*/
public getNormalized( name?: string ): StyleValue {
return this._styleProcessor.getNormalized( name, this._styles );
}
/**
* Returns a normalized style string. Styles are sorted by name.
*
* ```ts
* styles.set( 'margin' , '1px' );
* styles.set( 'background', '#f00' );
*
* styles.toString(); // -> 'background:#f00;margin:1px;'
* ```
*
* **Note**: This method supports normalized styles if defined.
*
* ```ts
* // Enable 'margin' shorthand processing:
* editor.data.addStyleProcessorRules( addMarginRules );
*
* styles.set( 'margin' , '1px' );
* styles.set( 'background', '#f00' );
* styles.remove( 'margin-top' );
* styles.remove( 'margin-right' );
*
* styles.toString(); // -> 'background:#f00;margin-bottom:1px;margin-left:1px;'
* ```
*/
public toString(): string {
if ( this.isEmpty ) {
return '';
}
return this.getStylesEntries()
.map( arr => arr.join( ':' ) )
.sort()
.join( ';' ) + ';';
}
/**
* Returns property as a value string or undefined if property is not set.
*
* ```ts
* // Enable 'margin' shorthand processing:
* editor.data.addStyleProcessorRules( addMarginRules );
*
* const styles = new Styles();
* styles.setTo( 'margin:1px;' );
* styles.set( 'margin-bottom', '3em' );
*
* styles.getAsString( 'margin' ); // -> 'margin: 1px 1px 3em;'
* ```
*
* Note, however, that all sub-values must be set for the longhand property name to return a value:
*
* ```ts
* const styles = new Styles();
* styles.setTo( 'margin:1px;' );
* styles.remove( 'margin-bottom' );
*
* styles.getAsString( 'margin' ); // -> undefined
* ```
*
* In the above scenario, it is not possible to return a `margin` value, so `undefined` is returned.
* Instead, you should use:
*
* ```ts
* const styles = new Styles();
* styles.setTo( 'margin:1px;' );
* styles.remove( 'margin-bottom' );
*
* for ( const styleName of styles.getStyleNames() ) {
* console.log( styleName, styles.getAsString( styleName ) );
* }
* // 'margin-top', '1px'
* // 'margin-right', '1px'
* // 'margin-left', '1px'
* ```
*
* In general, it is recommend to iterate over style names like in the example above. This way, you will always get all
* the currently set style values. So, if all the 4 margin values would be set
* the for-of loop above would yield only `'margin'`, `'1px'`:
*
* ```ts
* const styles = new Styles();
* styles.setTo( 'margin:1px;' );
*
* for ( const styleName of styles.getStyleNames() ) {
* console.log( styleName, styles.getAsString( styleName ) );
* }
* // 'margin', '1px'
* ```
*
* **Note**: To get a normalized version of a longhand property use the {@link #getNormalized `#getNormalized()`} method.
*/
public getAsString( propertyName: string ): string | undefined {
if ( this.isEmpty ) {
return;
}
if ( this._styles[ propertyName ] && !isObject( this._styles[ propertyName ] ) ) {
// Try return styles set directly - values that are not parsed.
return this._styles[ propertyName ] as string;
}
const styles = this._styleProcessor.getReducedForm( propertyName, this._styles );
const propertyDescriptor = styles.find( ( [ property ] ) => property === propertyName );
// Only return a value if it is set;
if ( Array.isArray( propertyDescriptor ) ) {
return propertyDescriptor[ 1 ];
}
}
/**
* Returns all style properties names as they would appear when using {@link #toString `#toString()`}.
*
* When `expand` is set to true and there's a shorthand style property set, it will also return all equivalent styles:
*
* ```ts
* stylesMap.setTo( 'margin: 1em' )
* ```
*
* will be expanded to:
*
* ```ts
* [ 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]
* ```
*
* @param expand Expand shorthand style properties and all return equivalent style representations.
*/
public getStyleNames( expand = false ): Array<string> {
if ( this.isEmpty ) {
return [];
}
if ( expand ) {
return this._styleProcessor.getStyleNames( this._styles );
}
const entries = this.getStylesEntries();
return entries.map( ( [ key ] ) => key );
}
/**
* Removes all styles.
*/
public clear(): void {
this._styles = {};
}
/**
* Returns normalized styles entries for further processing.
*/
public getStylesEntries(): Array<PropertyDescriptor> {
const parsed: Array<PropertyDescriptor> = [];
const keys = Object.keys( this._styles );
for ( const key of keys ) {
parsed.push( ...this._styleProcessor.getReducedForm( key, this._styles ) );
}
return parsed;
}
/**
* Removes empty objects upon removing an entry from internal object.
*/
private _cleanEmptyObjectsOnPath( path: string ): void {
const pathParts = path.split( '.' );
const isChildPath = pathParts.length > 1;
if ( !isChildPath ) {
return;
}
const parentPath = pathParts.splice( 0, pathParts.length - 1 ).join( '.' );
const parentObject = get( this._styles, parentPath );
if ( !parentObject ) {
return;
}
const isParentEmpty = !Object.keys( parentObject ).length;
if ( isParentEmpty ) {
this.remove( parentPath );
}
}
}
/**
* Style processor is responsible for writing and reading a normalized styles object.
*/
export class StylesProcessor {
private readonly _normalizers: Map<string, Normalizer>;
private readonly _extractors: Map<string, Extractor>;
private readonly _reducers: Map<string, Reducer>;
private readonly _consumables: Map<string, Array<string>>;
/**
* Creates StylesProcessor instance.
*
* @internal
*/
constructor() {
this._normalizers = new Map();
this._extractors = new Map();
this._reducers = new Map();
this._consumables = new Map();
}
/**
* Parse style string value to a normalized object and appends it to styles object.
*
* ```ts
* const styles = {};
*
* stylesProcessor.toNormalizedForm( 'margin', '1px', styles );
*
* // styles will consist: { margin: { top: '1px', right: '1px', bottom: '1px', left: '1px; } }
* ```
*
* **Note**: To define normalizer callbacks use {@link #setNormalizer}.
*
* @param name Name of style property.
* @param propertyValue Value of style property.
* @param styles Object holding normalized styles.
*/
public toNormalizedForm( name: string, propertyValue: StyleValue, styles: Styles ): void {
if ( isObject( propertyValue ) ) {
appendStyleValue( styles, toPath( name ), propertyValue );
return;
}
if ( this._normalizers.has( name ) ) {
const normalizer = this._normalizers.get( name )!;
const { path, value } = normalizer( propertyValue );
appendStyleValue( styles, path, value );
} else {
appendStyleValue( styles, name, propertyValue );
}
}
/**
* Returns a normalized version of a style property.
*
* ```ts
* const styles = {
* margin: { top: '1px', right: '1px', bottom: '1px', left: '1px; },
* background: { color: '#f00' }
* };
*
* stylesProcessor.getNormalized( 'background' );
* // will return: { color: '#f00' }
*
* stylesProcessor.getNormalized( 'margin-top' );
* // will return: '1px'
* ```
*
* **Note**: In some cases extracting single value requires defining an extractor callback {@link #setExtractor}.
*
* @param name Name of style property.
* @param styles Object holding normalized styles.
*/
public getNormalized( name: string | undefined, styles: Styles ): StyleValue {
if ( !name ) {
return merge( {}, styles );
}
// Might be empty string.
if ( styles[ name ] !== undefined ) {
return styles[ name ];
}
if ( this._extractors.has( name ) ) {
const extractor = this._extractors.get( name )!;
if ( typeof extractor === 'string' ) {
return get( styles, extractor );
}
const value = extractor( name, styles );
if ( value ) {
return value;
}
}
return get( styles, toPath( name ) );
}
/**
* Returns a reduced form of style property form normalized object.
*
* For default margin reducer, the below code:
*
* ```ts
* stylesProcessor.getReducedForm( 'margin', {
* margin: { top: '1px', right: '1px', bottom: '2px', left: '1px; }
* } );
* ```
*
* will return:
*
* ```ts
* [
* [ 'margin', '1px 1px 2px' ]
* ]
* ```
*
* because it might be represented as a shorthand 'margin' value. However if one of margin long hand values is missing it should return:
*
* ```ts
* [
* [ 'margin-top', '1px' ],
* [ 'margin-right', '1px' ],
* [ 'margin-bottom', '2px' ]
* // the 'left' value is missing - cannot use 'margin' shorthand.
* ]
* ```
*
* **Note**: To define reducer callbacks use {@link #setReducer}.
*
* @param name Name of style property.
*/
public getReducedForm( name: string, styles: Styles ): Array<PropertyDescriptor> {
const normalizedValue = this.getNormalized( name, styles );
// Might be empty string.
if ( normalizedValue === undefined ) {
return [];
}
if ( this._reducers.has( name ) ) {
const reducer = this._reducers.get( name )!;
return reducer( normalizedValue );
}
return [ [ name, normalizedValue as string ] ];
}
/**
* Return all style properties. Also expand shorthand properties (e.g. `margin`, `background`) if respective extractor is available.
*
* @param styles Object holding normalized styles.
*/
public getStyleNames( styles: Styles ): Array<string> {
// Find all extractable styles that have a value.
const expandedStyleNames = Array.from( this._consumables.keys() ).filter( name => {
const style = this.getNormalized( name, styles );
if ( style && typeof style == 'object' ) {
return Object.keys( style ).length;
}
return style;
} );
// For simple styles (for example `color`) we don't have a map of those styles
// but they are 1 to 1 with normalized object keys.
const styleNamesKeysSet = new Set( [
...expandedStyleNames,
...Object.keys( styles )
] );
return Array.from( styleNamesKeysSet );
}
/**
* Returns related style names.
*
* ```ts
* stylesProcessor.getRelatedStyles( 'margin' );
* // will return: [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ];
*
* stylesProcessor.getRelatedStyles( 'margin-top' );
* // will return: [ 'margin' ];
* ```
*
* **Note**: To define new style relations load an existing style processor or use
* {@link module:engine/view/stylesmap~StylesProcessor#setStyleRelation `StylesProcessor.setStyleRelation()`}.
*/
public getRelatedStyles( name: string ): Array<string> {
return this._consumables.get( name ) || [];
}
/**
* Adds a normalizer method for a style property.
*
* A normalizer returns describing how the value should be normalized.
*
* For instance 'margin' style is a shorthand for four margin values:
*
* - 'margin-top'
* - 'margin-right'
* - 'margin-bottom'
* - 'margin-left'
*
* and can be written in various ways if some values are equal to others. For instance `'margin: 1px 2em;'` is a shorthand for
* `'margin-top: 1px;margin-right: 2em;margin-bottom: 1px;margin-left: 2em'`.
*
* A normalizer should parse various margin notations as a single object:
*
* ```ts
* const styles = {
* margin: {
* top: '1px',
* right: '2em',
* bottom: '1px',
* left: '2em'
* }
* };
* ```
*
* Thus a normalizer for 'margin' style should return an object defining style path and value to store:
*
* ```ts
* const returnValue = {
* path: 'margin',
* value: {
* top: '1px',
* right: '2em',
* bottom: '1px',
* left: '2em'
* }
* };
* ```
*
* Additionally to fully support all margin notations there should be also defined 4 normalizers for longhand margin notations. Below
* is an example for 'margin-top' style property normalizer:
*
* ```ts
* stylesProcessor.setNormalizer( 'margin-top', valueString => {
* return {
* path: 'margin.top',
* value: valueString
* }
* } );
* ```
*/
public setNormalizer( name: string, callback: Normalizer ): void {
this._normalizers.set( name, callback );
}
/**
* Adds a extractor callback for a style property.
*
* Most normalized style values are stored as one level objects. It is assumed that `'margin-top'` style will be stored as:
*
* ```ts
* const styles = {
* margin: {
* top: 'value'
* }
* }
* ```
*
* However, some styles can have conflicting notations and thus it might be harder to extract a style value from shorthand. For instance
* the 'border-top-style' can be defined using `'border-top:solid'`, `'border-style:solid none none none'` or by `'border:solid'`
* shorthands. The default border styles processors stores styles as:
*
* ```ts
* const styles = {
* border: {
* style: {
* top: 'solid'
* }
* }
* }
* ```
*
* as it is better to modify border style independently from other values. On the other part the output of the border might be
* desired as `border-top`, `border-left`, etc notation.
*
* In the above example an extractor should return a side border value that combines style, color and width:
*
* ```ts
* styleProcessor.setExtractor( 'border-top', styles => {
* return {
* color: styles.border.color.top,
* style: styles.border.style.top,
* width: styles.border.width.top
* }
* } );
* ```
*
* @param callbackOrPath Callback that return a requested value or path string for single values.
*/
public setExtractor( name: string, callbackOrPath: Extractor ): void {
this._extractors.set( name, callbackOrPath );
}
/**
* Adds a reducer callback for a style property.
*
* Reducer returns a minimal notation for given style name. For longhand properties it is not required to write a reducer as
* by default the direct value from style path is taken.
*
* For shorthand styles a reducer should return minimal style notation either by returning single name-value tuple or multiple tuples
* if a shorthand cannot be used. For instance for a margin shorthand a reducer might return:
*
* ```ts
* const marginShortHandTuple = [
* [ 'margin', '1px 1px 2px' ]
* ];
* ```
*
* or a longhand tuples for defined values:
*
* ```ts
* // Considering margin.bottom and margin.left are undefined.
* const marginLonghandsTuples = [
* [ 'margin-top', '1px' ],
* [ 'margin-right', '1px' ]
* ];
* ```
*
* A reducer obtains a normalized style value:
*
* ```ts
* // Simplified reducer that always outputs 4 values which are always present:
* stylesProcessor.setReducer( 'margin', margin => {
* return [
* [ 'margin', `${ margin.top } ${ margin.right } ${ margin.bottom } ${ margin.left }` ]
* ]
* } );
* ```
*/
public setReducer( name: string, callback: Reducer ): void {
this._reducers.set( name, callback );
}
/**
* Defines a style shorthand relation to other style notations.
*
* ```ts
* stylesProcessor.setStyleRelation( 'margin', [
* 'margin-top',
* 'margin-right',
* 'margin-bottom',
* 'margin-left'
* ] );
* ```
*
* This enables expanding of style names for shorthands. For instance, if defined,
* {@link module:engine/conversion/viewconsumable~ViewConsumable view consumable} items are automatically created
* for long-hand margin style notation alongside the `'margin'` item.
*
* This means that when an element being converted has a style `margin`, a converter for `margin-left` will work just
* fine since the view consumable will contain a consumable `margin-left` item (thanks to the relation) and
* `element.getStyle( 'margin-left' )` will work as well assuming that the style processor was correctly configured.
* However, once `margin-left` is consumed, `margin` will not be consumable anymore.
*/
public setStyleRelation( shorthandName: string, styleNames: Array<string> ): void {
this._mapStyleNames( shorthandName, styleNames );
for ( const alsoName of styleNames ) {
this._mapStyleNames( alsoName, [ shorthandName ] );
}
}
/**
* Set two-way binding of style names.
*/
private _mapStyleNames( name: string, styleNames: Array<string> ) {
if ( !this._consumables.has( name ) ) {
this._consumables.set( name, [] );
}
this._consumables.get( name )!.push( ...styleNames );
}
}
/**
* Parses inline styles and puts property - value pairs into styles map.
*
* @param stylesString Styles to parse.
* @returns Map of parsed properties and values.
*/
function parseInlineStyles( stylesString: string ): Map<string, string> {
// `null` if no quote was found in input string or last found quote was a closing quote. See below.
let quoteType = null;
let propertyNameStart = 0;
let propertyValueStart = 0;
let propertyName = null;
const stylesMap = new Map();
// Do not set anything if input string is empty.
if ( stylesString === '' ) {
return stylesMap;
}
// Fix inline styles that do not end with `;` so they are compatible with algorithm below.
if ( stylesString.charAt( stylesString.length - 1 ) != ';' ) {
stylesString = stylesString + ';';
}
// Seek the whole string for "special characters".
for ( let i = 0; i < stylesString.length; i++ ) {
const char = stylesString.charAt( i );
if ( quoteType === null ) {
// No quote found yet or last found quote was a closing quote.
switch ( char ) {
case ':':
// Most of time colon means that property name just ended.
// Sometimes however `:` is found inside property value (for example in background image url).
if ( !propertyName ) {
// Treat this as end of property only if property name is not already saved.
// Save property name.
propertyName = stylesString.substr( propertyNameStart, i - propertyNameStart );
// Save this point as the start of property value.
propertyValueStart = i + 1;
}
break;
case '"':
case '\'':
// Opening quote found (this is an opening quote, because `quoteType` is `null`).
quoteType = char;
break;
case ';': {
// Property value just ended.
// Use previously stored property value start to obtain property value.
const propertyValue = stylesString.substr( propertyValueStart, i - propertyValueStart );
if ( propertyName ) {
// Save parsed part.
stylesMap.set( propertyName.trim(), propertyValue.trim() );
}
propertyName = null;
// Save this point as property name start. Property name starts immediately after previous property value ends.
propertyNameStart = i + 1;
break;
}
}
} else if ( char === quoteType ) {
// If a quote char is found and it is a closing quote, mark this fact by `null`-ing `quoteType`.
quoteType = null;
}
}
return stylesMap;
}
/**
* Return lodash compatible path from style name.
*/
function toPath( name: string ): string {
return name.replace( '-', '.' );
}
/**
* Appends style definition to the styles object.
*/
function appendStyleValue( stylesObject: Styles, nameOrPath: string, valueOrObject: StyleValue ) {
let valueToSet = valueOrObject;
if ( isObject( valueOrObject ) ) {
valueToSet = merge( {}, get( stylesObject, nameOrPath ), valueOrObject );
}
set( stylesObject, nameOrPath, valueToSet );
}
/**
* A CSS style property descriptor that contains tuple of two strings:
*
* - first string describes property name
* - second string describes property value
*
* ```ts
* const marginDescriptor = [ 'margin', '2px 3em' ];
* const marginTopDescriptor = [ 'margin-top', '2px' ];
* ```
*/
export type PropertyDescriptor = [ name: string, value: string ];
/**
* An object describing values associated with the sides of a box, for instance margins, paddings,
* border widths, border colors, etc.
*
* ```ts
* const margin = {
* top: '1px',
* right: '3px',
* bottom: '3px',
* left: '7px'
* };
*
* const borderColor = {
* top: 'red',
* right: 'blue',
* bottom: 'blue',
* left: 'red'
* };
* ```
*/
export type BoxSides = {
/**
* Top side value.
*/
top: undefined | string;
/**
* Left side value.
*/
left: undefined | string;
/**
* Right side value.
*/
right: undefined | string;