File size: 1,482 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const BASE_FONT_SIZE = 16

const UNIT_PX = "px"
const UNIT_EM = "em"
const UNIT_REM = "rem"

export function getUnit(value = ""): string | undefined {
  const DIGIT_REGEX = new RegExp(String.raw`-?\d+(?:\.\d+|\d*)`)
  const UNIT_REGEX = new RegExp(`${UNIT_PX}|${UNIT_EM}|${UNIT_REM}`)

  const unit = value.match(
    new RegExp(`${DIGIT_REGEX.source}(${UNIT_REGEX.source})`),
  )
  return unit?.[1]
}

export function toPx(value: string | number = ""): string | undefined {
  if (typeof value === "number") {
    return `${value}px`
  }

  const unit = getUnit(value)

  if (!unit) return value

  if (unit === UNIT_PX) {
    return value
  }

  if (unit === UNIT_EM || unit === UNIT_REM) {
    return `${parseFloat(value) * BASE_FONT_SIZE}${UNIT_PX}`
  }
}

export function toEm(
  value = "",
  fontSize = BASE_FONT_SIZE,
): string | undefined {
  const unit = getUnit(value)

  if (!unit) return value

  if (unit === UNIT_EM) {
    return value
  }

  if (unit === UNIT_PX) {
    return `${parseFloat(value) / fontSize}${UNIT_EM}`
  }

  if (unit === UNIT_REM) {
    return `${(parseFloat(value) * BASE_FONT_SIZE) / fontSize}${UNIT_EM}`
  }
}

export function toRem(value = ""): string | undefined {
  const unit = getUnit(value)

  if (!unit) return value

  if (unit === UNIT_REM) {
    return value
  }

  if (unit === UNIT_EM) {
    return `${parseFloat(value)}${UNIT_REM}`
  }

  if (unit === UNIT_PX) {
    return `${parseFloat(value) / BASE_FONT_SIZE}${UNIT_REM}`
  }
}