useAway started

This commit is contained in:
Seth Trowbridge 2023-01-24 23:54:25 -05:00
parent dc601637a8
commit 1257baa190
2 changed files with 30 additions and 2 deletions

View File

@ -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`
<div>
<h2 class="pb-2 mb-2 border-b text-2xl font-sans border(">Person Records</h2>
<div class="px-2">
<h2 class="pb-2 mb-2 border-b text-2xl font-sans">Person Records ${countGet}</h2>
<div class="px-2" ref=${ref}>
<${PersonForm}/>
<${PersonTable}/>

View File

@ -117,3 +117,23 @@ const Collapser = (inElement) => {
};
return show;
};
/** @typedef {(e:Event)=>void} Handler */
/** @type {(inRef:React.MutableRefObject<HTMLElement|null>, inHandler:Handler)=>void} */
export const useAway = (inRef, inHandler) => {
/** @type React.MutableRefObject<Handler> */
const handlerUser = React.useRef(inHandler);
handlerUser.current = inHandler;
/** @type React.MutableRefObject<Handler> */
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);
}, []);
};