-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (55 loc) · 1.48 KB
/
index.js
File metadata and controls
62 lines (55 loc) · 1.48 KB
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
const React = require('react')
const PropTypes = require('prop-types')
const div = React.createElement.bind(React, 'div')
const iframe = React.createElement.bind(React, 'iframe')
const divStyle = {
position: 'relative',
height: 0,
overflow: 'hidden',
maxWidth: '100%'
}
let iframeStyle = {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
}
/*
* Turn `16:9` into `9 / 16` into `56.25%`
* Turn `4:3` into `3 / 4` into `75%`
*/
const ratioToPercent = (ratio) => {
const [w, h] = ratio.split(':').map((num) => Number(num))
return `${(h / w) * 100}%`
}
/*
* Usage: <ResponsiveEmbed src='ace youtube video' ratio='4:3' />
*/
const ResponsiveEmbed = (props) => {
const paddingBottom = ratioToPercent(props.ratio)
const style = Object.assign({}, divStyle, {paddingBottom})
if (props.style) {
iframeStyle = Object.assign(iframeStyle, props.style)
}
const iframeProps = Object.assign({frameBorder: 0}, props, {style: iframeStyle})
delete iframeProps.ratio
return div({style},
iframe(iframeProps)
)
}
ResponsiveEmbed.defaultProps = {
src: 'https://www.youtube.com/embed/dQw4w9WgXcQ',
ratio: '16:9'
}
ResponsiveEmbed.propTypes = {
src: PropTypes.string,
ratio: (props, propName, componentName) => {
if (!/\d+:\d+/.test(props[propName])) {
return new Error(
'Invalid ratio supplied to ResponsiveEmbed. Expected a string like "16:9" or any 2 numbers seperated by a colon'
)
}
}
}
module.exports = ResponsiveEmbed