UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

84 lines 3.16 kB
import React from 'react'; import { isTrue } from "../../shared/component-helper.js"; import HeadingContext from "./HeadingContext.js"; import { globalSyncCounter, globalHeadingCounter, correctInternalHeadingLevel, windupHeadings, teardownHeadings, debugCounter } from "./HeadingHelpers.js"; import { initCounter } from "./HeadingCounter.js"; export default function HeadingProvider(props) { const context = React.useContext(HeadingContext); const [state, setState] = React.useState(() => { const state = { context, _listenForPropChanges: true }; const existingContext = context.heading; state.counter = initCounter(props); state.newProps = props; if (existingContext) { state.newProps = { ...existingContext, ...props }; } if (existingContext) { state.counter.setContextCounter(existingContext.counter); } else { state.counter.setContextCounter(globalHeadingCounter.current); } state.counter = correctInternalHeadingLevel({ counter: state.counter, ref: props, level: parseFloat(String(props.level)), inherit: isTrue(props.inherit), reset: props.reset, increase: isTrue(props.increase) || isTrue(props.up), decrease: isTrue(props.decrease) || isTrue(props.down), bypassChecks: isTrue(state.newProps.skip_correction), source: props.text || props.children, debug: state.newProps.debug }); globalSyncCounter.current = state.counter; state.level = state.counter.level; state.prevLevel = parseFloat(String(state.newProps.level)) || state.counter.level; return state; }); React.useEffect(() => { const level = parseFloat(String(props.level)); if (state.prevLevel !== props.level && level > 0 && level !== state.level) { var _state$context$headin, _state$context$headin2; const { level: newLevel } = correctInternalHeadingLevel({ counter: state.counter, level, bypassChecks: isTrue(props.skip_correction) || isTrue((_state$context$headin = state.context.heading) === null || _state$context$headin === void 0 ? void 0 : _state$context$headin.skip_correction), source: props.text || props.children, debug: props.debug || ((_state$context$headin2 = state.context.heading) === null || _state$context$headin2 === void 0 ? void 0 : _state$context$headin2.debug) }); state.level = state.prevLevel = newLevel; setState({ ...state }); } }, [props.level]); React.useEffect(() => { windupHeadings(); return () => { teardownHeadings(); }; }, []); return React.createElement(HeadingContext.Provider, { value: { heading: { ...state.newProps, ...state } } }, state.newProps.debug_counter && React.createElement("span", { className: "dnb-heading__context" }, React.createElement("span", { className: "dnb-heading__debug" }, "Context:", ' ', React.createElement("span", { className: "dnb-code" }, debugCounter(state.counter))), props.children) || props.children); } //# sourceMappingURL=HeadingProvider.js.map