-
-
Notifications
You must be signed in to change notification settings - Fork 209
/
triangle.js
83 lines (74 loc) · 2.51 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
// @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: {
* 'border-color': 'transparent',
* 'border-left-color': 'red !important',
* 'border-style': 'solid',
* 'border-width': '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 {
'border-color': backgroundColor,
'width': '0',
'height': '0',
'border-width': getBorderWidth(pointingDirection, unitlessHeight, unitlessWidth),
'border-style': '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