From c58819d158a0a4e1a2ce7c2faf6c8780dd8760cc Mon Sep 17 00:00:00 2001 From: krmax44 Date: Mon, 31 Jan 2022 18:07:16 +0100 Subject: [PATCH] feat: add support for `rem` values in gap and peek --- src/components/gaps.js | 4 ++-- src/components/peek.js | 8 ++++---- src/utils/unit.js | 19 +++++++++++++++++++ tests/unit/unit.test.js | 8 ++++++++ 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/components/gaps.js b/src/components/gaps.js index 664dd16f..24727d2b 100644 --- a/src/components/gaps.js +++ b/src/components/gaps.js @@ -1,4 +1,4 @@ -import { toInt } from '../utils/unit' +import { toPx } from '../utils/unit' import { define } from '../utils/object' import { throttle } from '../utils/wait' @@ -58,7 +58,7 @@ export default function (Glide, Components, Events) { * @returns {Number} */ get () { - return toInt(Glide.settings.gap) + return toPx(Glide.settings.gap) } }) diff --git a/src/components/peek.js b/src/components/peek.js index e9760ef9..fdc9b333 100644 --- a/src/components/peek.js +++ b/src/components/peek.js @@ -1,5 +1,5 @@ import { define } from '../utils/object' -import { toInt, isObject } from '../utils/unit' +import { isObject, toPx } from '../utils/unit' export default function (Glide, Components, Events) { const Peek = { @@ -31,10 +31,10 @@ export default function (Glide, Components, Events) { */ set (value) { if (isObject(value)) { - value.before = toInt(value.before) - value.after = toInt(value.after) + value.before = toPx(value.before) + value.after = toPx(value.after) } else { - value = toInt(value) + value = toPx(value) } Peek._v = value diff --git a/src/utils/unit.js b/src/utils/unit.js index 3c90e70e..dcffb735 100644 --- a/src/utils/unit.js +++ b/src/utils/unit.js @@ -20,6 +20,25 @@ export function toFloat (value) { return parseFloat(value) } +/** + * Converts a number or string of format /\d+(px|rem|em)?/ + * to a number in pixel units + * @param {String|Number} value + * @param {Glide} glide + * @returns {Number} + */ +export function toPx (value) { + const int = toInt(value) + if (isNumber(value)) return int + + if (value.endsWith('rem')) { + const { fontSize } = window.getComputedStyle(document.documentElement) + return toInt(int * toFloat(fontSize)) + } + + return int +} + /** * Indicates whether the specified value is a string. * diff --git a/tests/unit/unit.test.js b/tests/unit/unit.test.js index db11129c..c2916485 100644 --- a/tests/unit/unit.test.js +++ b/tests/unit/unit.test.js @@ -1,5 +1,6 @@ import { toInt, + toPx, isArray, isString, isObject, @@ -15,6 +16,13 @@ describe('Function', () => { expect(toInt('1px', 100)).toBe(1) }) + test('`toPx` should convert number, rem and px to pixel unit', () => { + document.documentElement.style.fontSize = '16px' + expect(toPx(1)).toBe(1) + expect(toPx('1px')).toBe(1) + expect(toPx('1rem')).toBe(16) + }) + test('`isString` return `true` on valid string', () => { expect(isString('undefined')).toBe(true)