diff --git a/js/people.js b/js/people.js index 892d654..a661836 100644 --- a/js/people.js +++ b/js/people.js @@ -2,6 +2,7 @@ import Preact from "preact"; import { html } from "htm"; import { Consumer } from "./store.js"; import * as Tree from "./tree.js"; +import React from "preact"; /** @typedef {(e:SubmitEvent|Event)=>void|null} handler */ @@ -83,10 +84,17 @@ const PersonForm = () => { /** @type {()=>preact.VNode} */ export default () => { + let [countGet, countSet] = Preact.useState(0); + + let ref = Preact.useRef(null); + Tree.useAway(ref, () => { + countSet(countGet + 1); + }); + return html`
-

Person Records

-
+

Person Records ${countGet}

+
<${PersonForm}/> <${PersonTable}/> diff --git a/js/tree.js b/js/tree.js index cb2f9e6..3c637ae 100644 --- a/js/tree.js +++ b/js/tree.js @@ -117,3 +117,23 @@ const Collapser = (inElement) => { }; return show; }; + +/** @typedef {(e:Event)=>void} Handler */ +/** @type {(inRef:React.MutableRefObject, inHandler:Handler)=>void} */ +export const useAway = (inRef, inHandler) => { + /** @type React.MutableRefObject */ + const handlerUser = React.useRef(inHandler); + handlerUser.current = inHandler; + + /** @type React.MutableRefObject */ + const handlerClick = React.useRef((e) => { + const index = inRef.current ? e.composedPath().indexOf(inRef.current) : -1; + if (index < 0) { + handlerUser.current(e); + } + }); + React.useEffect(() => { + document.addEventListener("click", handlerClick.current); + return () => document.removeEventListener("click", handlerClick.current); + }, []); +};