-
-
Notifications
You must be signed in to change notification settings - Fork 209
/
triangle.js
108 lines (99 loc) · 2.6 KB
/
triangle.js
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
// @flow
/** */
type PointingDirection = 'top' | 'right' | 'bottom' | 'left'
type TriangleArgs = {
backgroundColor?: string,
foregroundColor: string,
height: number | string,
width: number | string,
pointingDirection: PointingDirection,
}
const getBorderWidth = (
pointingDirection: PointingDirection,
height: number,
width: number,
) => {
switch (pointingDirection) {
case 'top':
return `0 ${width / 2}px ${height}px ${width / 2}px`
case 'left':
return `${height / 2}px ${width}px ${height / 2}px 0`
case 'bottom':
return `${height}px ${width / 2}px 0 ${width / 2}px`
case 'right':
return `${height / 2}px 0 ${height / 2}px ${width}px`
default:
throw new Error(
"Passed invalid argument to triangle, please pass correct poitingDirection e.g. 'right'.",
)
}
}
// needed for border-color
const reverseDirection = {
left: 'Right',
right: 'Left',
top: 'Bottom',
bottom: 'Top',
}
/**
* CSS to represent triangle with any pointing direction with an optional background color. Accepts number or px values for height and width.
*
* @example
* // Styles as object usage
*
* const styles = {
* ...triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })
* }
*
*
* // styled-components usage
* const div = styled.div`
* ${triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })}
*
*
* // CSS as JS Output
*
* div: {
* 'borderColor': 'transparent',
* 'borderLeftColor': 'red !important',
* 'borderStyle': 'solid',
* 'borderWidth': '50px 0 50px 100px',
* 'height': '0',
* 'width': '0',
* }
*/
function triangle({
pointingDirection,
height,
width,
foregroundColor,
backgroundColor = 'transparent',
}: TriangleArgs) {
const unitlessHeight = parseFloat(height)
const unitlessWidth = parseFloat(width)
if (isNaN(unitlessHeight) || isNaN(unitlessWidth)) {
throw new Error(
'Passed an invalid value to `height` or `width`. Please provide a pixel based unit',
)
}
return {
borderColor: backgroundColor,
width: '0',
height: '0',
borderWidth: getBorderWidth(
pointingDirection,
unitlessHeight,
unitlessWidth,
),
borderStyle: 'solid',
/*
* javascript Object sorting orders 'border-color' after 'border-bottom-color'
* (bottom-b) is before (bottom-c) - !important is needed
* { border-bottom-color: 'red', border-color: 'transparent' }
*/
[`border${reverseDirection[
pointingDirection
]}Color`]: `${foregroundColor} !important`,
}
}
export default triangle