Skip to content

Commit c0ef45f

Browse files
authored
feat: add parseLength function to @superset-ui/dimension (apache-superset#171)
* feat: add parseLength function * feat: export * fix: address Kim's comment
1 parent 76c05b0 commit c0ef45f

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
export { default as getTextDimension } from './getTextDimension';
22
export { default as computeMaxFontSize } from './computeMaxFontSize';
33
export { default as mergeMargin } from './mergeMargin';
4+
export { default as parseLength } from './parseLength';
45

56
export * from './types';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const HUNDRED_PERCENT = { isDynamic: true, multiplier: 1 } as const;
2+
3+
export default function parseLength(
4+
input: string | number,
5+
): { isDynamic: true; multiplier: number } | { isDynamic: false; value: number } {
6+
if (input === 'auto' || input === '100%') {
7+
return HUNDRED_PERCENT;
8+
} else if (typeof input === 'string' && input.length > 0 && input[input.length - 1] === '%') {
9+
// eslint-disable-next-line no-magic-numbers
10+
return { isDynamic: true, multiplier: parseFloat(input) / 100 };
11+
}
12+
const value = typeof input === 'number' ? input : parseFloat(input);
13+
14+
return { isDynamic: false, value };
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import parseLength from '../src/parseLength';
2+
3+
describe('parseLength(input)', () => {
4+
it('handles string "auto"', () => {
5+
expect(parseLength('auto')).toEqual({ isDynamic: true, multiplier: 1 });
6+
});
7+
8+
it('handles strings with % at the end', () => {
9+
expect(parseLength('100%')).toEqual({ isDynamic: true, multiplier: 1 });
10+
expect(parseLength('50%')).toEqual({ isDynamic: true, multiplier: 0.5 });
11+
expect(parseLength('0%')).toEqual({ isDynamic: true, multiplier: 0 });
12+
});
13+
14+
it('handles strings that are numbers with px at the end', () => {
15+
expect(parseLength('100px')).toEqual({ isDynamic: false, value: 100 });
16+
expect(parseLength('20.5px')).toEqual({ isDynamic: false, value: 20.5 });
17+
});
18+
19+
it('handles strings that are numbers', () => {
20+
expect(parseLength('100')).toEqual({ isDynamic: false, value: 100 });
21+
expect(parseLength('40.5')).toEqual({ isDynamic: false, value: 40.5 });
22+
expect(parseLength('20.0')).toEqual({ isDynamic: false, value: 20 });
23+
});
24+
25+
it('handles numbers', () => {
26+
expect(parseLength(100)).toEqual({ isDynamic: false, value: 100 });
27+
expect(parseLength(0)).toEqual({ isDynamic: false, value: 0 });
28+
});
29+
});

0 commit comments

Comments
 (0)