PluginProbe
Tableberg – Simple Gutenberg Table Block / 1.1.5
Tableberg – Simple Gutenberg Table Block v1.1.5
1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.5 1.0.4 1.0.3 1.0.2 1.0.1 trunk 0.0.2 0.2.1 0.3.2 0.3.3 0.4.1 0.5.0 0.5.1 0.5.2 0.5.3 0.5.4 0.5.5 0.5.6 0.5.7 All 42 releases
tableberg / src / hooks / useClickOutside.ts

useClickOutside.ts in Tableberg – Simple Gutenberg Table Block 1.1.5, at src/hooks/useClickOutside.ts

93 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { useEffect, RefObject } from "react";
2
3 const TOOLBAR_CLASS = ".block-editor-block-toolbar";
4 const TABLEBERG_TOOLBAR_CLASSES = [
5 ".tableberg-edit-toolbar",
6 ".tableberg-edit-toolbar-mount",
7 ].join(", ");
8
9 const POPOVER_CLASSES = [
10 ".block-editor-block-popover",
11 ".components-popover",
12 ].join(", ");
13 const SIDEBAR_CLASS = ".interface-interface-skeleton__sidebar";
14
15 const BLOCK_INSERTER_CLASSES = [
16 ".editor-inserter-sidebar",
17 ".block-editor-inserter__menu",
18 ].join(", ");
19 const INSERTER_BUTTON_CLASSES = [
20 ".editor-document-tools__inserter-toggle",
21 ".edit-post-header-toolbar__inserter-toggle",
22 ].join(", ");
23 const INSERTER_POPOVER_CLASS = ".block-editor-inserter__popover";
24
25 const TOPLEFT_BUTTONS_CLASSES = [
26 ".editor-document-tools",
27 ".edit-post-header-toolbar",
28 ].join(", ");
29
30 interface UseClickOutsideOptions {
31 ref: RefObject<HTMLElement>;
32 onClickOutside: () => void;
33 }
34
35 export function useClickOutside({
36 ref,
37 onClickOutside,
38 }: UseClickOutsideOptions): void {
39 useEffect(() => {
40 const ownerDocument = ref.current?.ownerDocument;
41
42 if (!ownerDocument) {
43 return;
44 }
45
46 function handleClickOutside(event: MouseEvent) {
47 if (!ref.current) {
48 return;
49 }
50
51 const targetNode = event.target as Node | null;
52
53 if (!targetNode || ref.current.contains(targetNode)) {
54 return;
55 }
56
57 const targetElement =
58 targetNode instanceof Element
59 ? targetNode
60 : targetNode.parentElement;
61
62 if (!targetElement) {
63 onClickOutside();
64 return;
65 }
66
67 const editorChrome = targetElement.closest(
68 [
69 TOOLBAR_CLASS,
70 TABLEBERG_TOOLBAR_CLASSES,
71 POPOVER_CLASSES,
72 SIDEBAR_CLASS,
73 BLOCK_INSERTER_CLASSES,
74 INSERTER_BUTTON_CLASSES,
75 INSERTER_POPOVER_CLASS,
76 TOPLEFT_BUTTONS_CLASSES,
77 ].join(", ")
78 );
79
80 if (editorChrome) {
81 return;
82 }
83
84 onClickOutside();
85 }
86
87 ownerDocument.addEventListener("mousedown", handleClickOutside);
88
89 return () =>
90 ownerDocument.removeEventListener("mousedown", handleClickOutside);
91 }, [onClickOutside, ref]);
92 }
93