Skip to content

Instantly share code, notes, and snippets.

@sompylasar
Last active February 28, 2018 23:44
Show Gist options
  • Save sompylasar/3282807e5044cf2d3c7676f18f67f470 to your computer and use it in GitHub Desktop.
Save sompylasar/3282807e5044cf2d3c7676f18f67f470 to your computer and use it in GitHub Desktop.
ZIndexManager – Stores and manages z-indexes in a stacking order. ZIndexManagerProvider – provides ZIndexManager functions via React context. Refs: https://hackernoon.com/my-approach-to-using-z-index-eca67feb079c
/**
* ZIndexManager
*
* Stores and manages z-indexes in a stacking order.
*/
export default class ZIndexManager {
constructor(onChange) {
this._zIndexMin = 99;
this._zIndexes = {};
this._zIndexMax = this._zIndexMin;
this._onChange = onChange;
}
allocateZIndex() {
const newZIndex = (this._zIndexMax + 1);
this._zIndexes[newZIndex] = newZIndex;
this._zIndexMax = newZIndex;
const onChange = this._onChange;
if (onChange) {
onChange();
}
return newZIndex;
}
releaseZIndex(zIndex) {
delete this._zIndexes[zIndex];
while (this._zIndexMax > this._zIndexMin && this._zIndexes[this._zIndexMax] === undefined) {
this._zIndexMax -= 1;
}
const onChange = this._onChange;
if (onChange) {
onChange();
}
}
getTopmostZIndex() {
return this._zIndexMax + 1;
}
}
import { Component } from 'react';
import PropTypes from 'prop-types';
import ZIndexManager from './ZIndexManager';
/**
* @see ZIndexManager
*/
class ZIndexManagerProvider extends Component {
static propTypes = {
children: PropTypes.node,
}
static childContextTypes = {
allocateZIndex: PropTypes.func,
releaseZIndex: PropTypes.func,
topmostZIndex: PropTypes.number,
}
constructor(props) {
super(props);
this._zIndexManager = new ZIndexManager(() => {
this.forceUpdate();
});
this._zIndexManagerAllocate = this._zIndexManager.allocateZIndex.bind(this._zIndexManager);
this._zIndexManagerRelease = this._zIndexManager.releaseZIndex.bind(this._zIndexManager);
}
getChildContext() {
return {
allocateZIndex: this._zIndexManagerAllocate,
releaseZIndex: this._zIndexManagerRelease,
topmostZIndex: this._zIndexManager.getTopmostZIndex(),
};
}
render() {
return this.props.children;
}
}
export default ZIndexManagerProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment