-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
tryparsedimensionwithunit.ts
71 lines (62 loc) · 1.81 KB
/
tryparsedimensionwithunit.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
/**
* @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 image/imageresize/utils/tryparsedimensionwithunit
*/
/**
* Parses provided string with dimension value and returns extracted numeric value and unit.
*
* * If non-string dimension is passed then `null` value is returned.
* * If unit is missing then `null` is returned.
* * If numeric value part of string is not a number then `null` is returned.
*
* Example:
* `"222px"` => `{ value: 222, unit: "px" }`
* `"99%"` => `{ value: 99, unit: "%" }`
* @param dimension Unsafe string with dimension.
* @returns Parsed dimension with extracted numeric value and units.
*/
export function tryParseDimensionWithUnit( dimension: string | null | undefined ): DimensionWithUnit | null {
if ( !dimension ) {
return null;
}
const [ , rawValue, unit ] = dimension.trim().match( /([.,\d]+)(%|px)$/ ) || [];
const parsedValue = Number.parseFloat( rawValue );
if ( Number.isNaN( parsedValue ) ) {
return null;
}
return {
value: parsedValue,
unit
};
}
/**
* Converts dimension between `px` -> `%` and `%` -> `px`.
*
* @param parentDimensionPx Dimension of parent element that contains measured element.
* @param dimension Measured element dimension.
* @returns Casted dimension.
*/
export function tryCastDimensionsToUnit( parentDimensionPx: number, dimension: DimensionWithUnit, targetUnit: string ): DimensionWithUnit {
// "%" -> "px" conversion
if ( targetUnit === 'px' ) {
return {
value: dimension.value,
unit: 'px'
};
}
// "px" -> "%" conversion
return {
value: dimension.value / parentDimensionPx * 100,
unit: '%'
};
}
/**
* @internal
*/
export type DimensionWithUnit = {
value: number;
unit: string;
};