@atlaskit/navigation-system
Version:
The latest navigation system for Atlassian apps.
83 lines (81 loc) • 3.18 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useCallback, useMemo, useState } from 'react';
import { SkipLinksContainer } from '../../components/skip-links/skip-links-container';
import { SkipLinksContext } from './skip-links-context';
var getByDomOrderSortFunction = function getByDomOrderSortFunction() {
var layoutSlots = Array.from(document.querySelectorAll("[data-layout-slot]"));
return function (a, b) {
var _a$listIndex, _b$listIndex;
var indexA = (_a$listIndex = a.listIndex) !== null && _a$listIndex !== void 0 ? _a$listIndex : layoutSlots.indexOf(document.getElementById(a.id));
var indexB = (_b$listIndex = b.listIndex) !== null && _b$listIndex !== void 0 ? _b$listIndex : layoutSlots.indexOf(document.getElementById(b.id));
/**
* If they are tied it is because one (or both) is
* a custom skiplink with a set index.
*
* Give the custom skiplink priority.
*/
if (indexA === indexB) {
if (a.listIndex !== undefined) {
return -1;
} else {
return 1;
}
}
return indexA - indexB;
};
};
/**
* Provider for skip links. Should be rendered at the top level of the application.
*
* - Provides the context to register/unregister skip links
* - Renders the skip links container
*/
export function SkipLinksProvider(_ref) {
var children = _ref.children,
label = _ref.label,
triggerLabel = _ref.triggerLabel,
testId = _ref.testId;
var _useState = useState([]),
_useState2 = _slicedToArray(_useState, 2),
links = _useState2[0],
setLinks = _useState2[1];
var registerSkipLink = useCallback(function (skipLinkData) {
// Don't add duplicate skip links
setLinks(function (oldLinks) {
if (oldLinks.some(function (_ref2) {
var id = _ref2.id;
return id === skipLinkData.id;
})) {
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn("Tried registering duplicate skip link for ID '".concat(skipLinkData.id, "'.\n\nIf you're trying to override a slot skip link label, then use the `skipLinkLabel` prop instead.\n\nThis error will not be shown in production, and the duplicate skip link will be ignored."));
}
return oldLinks;
}
return [].concat(_toConsumableArray(oldLinks), [skipLinkData]).sort(getByDomOrderSortFunction());
});
}, []);
var unregisterSkipLink = useCallback(function (id) {
setLinks(function (links) {
return links.filter(function (link) {
return link.id !== id;
});
});
}, []);
var contextValue = useMemo(function () {
var data = {
registerSkipLink: registerSkipLink,
unregisterSkipLink: unregisterSkipLink
};
return data;
}, [registerSkipLink, unregisterSkipLink]);
return /*#__PURE__*/React.createElement(SkipLinksContext.Provider, {
value: contextValue
}, /*#__PURE__*/React.createElement(SkipLinksContainer, {
label: label,
triggerLabel: triggerLabel,
testId: testId,
links: links
}), children);
}