@workday/canvas-kit-react
Version:
The parent module that contains all Workday Canvas Kit React components
47 lines (46 loc) • 2.24 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAlwaysCloseOnOutsideClick = void 0;
const react_1 = __importDefault(require("react"));
const canvas_kit_popup_stack_1 = require("@workday/canvas-kit-popup-stack");
const common_1 = require("@workday/canvas-kit-react/common");
const usePopupModel_1 = require("./usePopupModel");
/**
* Registers global listener for all clicks. It will only call the PopupModel's `hide` event if the
* click happened outside the `stackRef` element and its children regardless of the position in the
* stack. This is useful for Tooltips or hierarchical menus. Adds a
* `data-behavior-click-outside-close="always"` attribute to ensure proper functionality.
*
* This should be used with popup elements that should close no matter their position in the stack
* (i.e. Tooltips).
*/
exports.useAlwaysCloseOnOutsideClick = (0, common_1.createElemPropsHook)(usePopupModel_1.usePopupModel)(model => {
const onClick = react_1.default.useCallback((event) => {
if (!model.state.stackRef.current) {
return;
}
if (
// Use `PopupStack.contains` instead of `ref.current.contains` so that the application can
// decide if clicking the target should toggle the popup rather than it toggling implicitly
// because the target is outside `ref.current`
!canvas_kit_popup_stack_1.PopupStack.contains(model.state.stackRef.current, event.target)) {
model.events.hide();
}
}, [model.events, model.state.stackRef]);
const visible = model.state.visibility !== 'hidden';
react_1.default.useLayoutEffect(() => {
var _a;
if (!visible) {
return;
}
document.addEventListener('mousedown', onClick);
(_a = model.state.stackRef.current) === null || _a === void 0 ? void 0 : _a.setAttribute('data-behavior-click-outside-close', 'always');
return () => {
document.removeEventListener('mousedown', onClick);
};
}, [model.state.stackRef, visible, onClick]);
return {};
});
;