@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
88 lines • 3.13 kB
JavaScript
import React from 'react';
import HeadingContext from "./HeadingContext.js";
import { globalSyncCounter, globalHeadingCounter, correctInternalHeadingLevel, windupHeadings, teardownHeadings, debugCounter } from "./HeadingHelpers.js";
import { initCounter } from "./HeadingCounter.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
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: props.inherit,
reset: props.reset,
increase: props.increase || props.up,
decrease: props.decrease || props.down,
bypassChecks: state.newProps.skipCorrection,
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: props.skipCorrection || ((_state$context$headin = state.context.heading) === null || _state$context$headin === void 0 ? void 0 : _state$context$headin.skipCorrection),
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 _jsx(HeadingContext, {
value: {
heading: {
...state.newProps,
...state
}
},
children: state.newProps.debugCounter && _jsxs("span", {
className: "dnb-heading__context",
children: [_jsxs("span", {
className: "dnb-heading__debug",
children: ["Context:", ' ', _jsx("span", {
className: "dnb-code",
children: debugCounter(state.counter)
})]
}), props.children]
}) || props.children
});
}
//# sourceMappingURL=HeadingProvider.js.map