UNPKG

@lyra/form-builder

Version:
76 lines (61 loc) 2 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _convertPath = require('../utils/convertPath'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /*:: import type {Path} from '../../typedefs/path'*/ /** * An example of how to sync focus path through document.location.hash * */ /*:: type ChildArgs = { onFocus: (path: Path) => void, onBlur: () => void, focusPath: Path }*/ /*:: type Props = { focusPath: ?any, onFocus: () => {}, onBlur: () => {}, children: ChildArgs => any }*/ /*:: type State = { focusPath: Array<*> }*/ function getHash() { return decodeURIComponent(document.location.hash.substring(1)); } function getPathFromHash() { const hash = getHash(); return hash ? (0, _convertPath.toFormBuilder)(hash) : []; } class HashFocusManager extends _react2.default.Component /*:: <Props, State>*/ { constructor(...args) { var _temp; return _temp = super(...args), this.state = { focusPath: getPathFromHash() }, this.handleHashChange = () => { this.setState({ focusPath: getPathFromHash() }); }, this.handleFocus = (focusPath /*: Path*/) => { document.location.hash = (0, _convertPath.toSaga)(focusPath); }, this.handleBlur = () => { // this.setState({focusPath: []}) }, _temp; } componentDidMount() { window.addEventListener('hashchange', this.handleHashChange, false); } componentWillUnmount() { window.removeEventListener('hashchange', this.handleHashChange, false); } render() { return this.props.children({ onBlur: this.handleBlur, onFocus: this.handleFocus, focusPath: this.state.focusPath }); } } exports.default = HashFocusManager;