function reactCarousel(config) {
class Carousel extends React.Component {
constructor(props) {
super(props);
this.state = {
windowSize: config.windowSize,
moveAmount: config.windowSize - 1,
orderArr: createItems(config.carouselItems),
firstIndex: 0,
nextFirstIndex: 0,
};
this.go = this.go.bind(this);
}
go(direction) {
this.setState(
carouselState => ({
...prepareMove(direction, carouselState)
}),
() => {
setTimeout(() => {
this.setState(state => ({ ...move(state) }));
}, config.isDebugging ? 300 : 0);
}
);
}
render() {
const { firstIndex, nextFirstIndex, windowSize } = this.state;
const itemWidth = 1 / windowSize * 100;
// ------
const windowStyle = config.isDebugging
? {
boxSizing: 'border-box',
width: '40%',
margin: '20px auto',
position: 'relative',
}
: {
boxSizing: 'border-box',
overflow: 'hidden',
};
const windowBorderStyle = config.isDebugging ? {
content: '',
position: 'absolute',
left: 0,
top: 0,
width: '100%',
height: '100%',
outline: '8px solid gray',
} : null;
const itemsStyle = {
boxSizing: 'border-box',
display: 'flex',
width: '100%',
transform: `translateX(${-firstIndex * itemWidth}%)`,
transitionDuration: firstIndex === nextFirstIndex ? (config.isDebugging ? '600ms' : '400ms') : '0ms',
transitionProperty: 'all',
transitionTimingFunction: 'ease-in-out',
};
const itemStyle = index => {
return {
boxSizing: 'border-box',
fontFamily: 'system-ui',
fontSize: 40,
flexShrink: 0,
flexGrow: 1,
width: `${itemWidth}%`,
fontWeight: 'bold',
background: 'linear-gradient(to bottom right, #333, black)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
padding: 20,
};
};
const buttonStyle = direction => ({
opacity: canGo(direction, this.state) ? 1 : 0.5,
width: '50%',
fontSize: 40,
});
// SHORTHAND HELPERS
// ------
const div = (style, children) => React.createElement('div', { style }, children);
const button = (props, children) => React.createElement('button', props, children);
// DOM
// ---
return (
div(null, [
div(windowStyle, [
div(itemsStyle,
this.state.orderArr.map((item, i) =>
div(itemStyle(i), item)
)
),
div(windowBorderStyle, '')
]),
button({ onClick: () => this.go('left'), style: buttonStyle('left') }, '👈'),
button({ onClick: () => this.go('right'), style: buttonStyle('right') }, '👉'),
config.isDebugging && `transform: translateX(${-firstIndex * itemWidth}%)`,
])
);
}
}
// Instantiate the carousel and render it
// ---
let parent = html`<div>`;
ReactDOM.render(React.createElement(Carousel), parent);
return parent;
}