Skip to content

Commit 24e2566

Browse files
committed
Add the useParent hook
1 parent 922883b commit 24e2566

File tree

4 files changed

+50
-2
lines changed

4 files changed

+50
-2
lines changed

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
{
22
"name": "@atomico/kit",
33
"description": "Series of utilities in hooks format to extend the operation of Atomico",
4-
"version": "2.1.0",
4+
"version": "2.2.0",
55
"type": "module",
66
"exports": {
77
"./use-child-nodes": "./src/use-child-nodes/use-child-nodes.js",
88
"./use-css-light-dom": "./src/use-css-light-dom/use-css-light-dom.js",
99
"./use-force-render": "./src/use-force-render/use-force-render.js",
1010
"./use-render": "./src/use-render/use-render.js",
1111
"./use-router": "./src/use-router/use-router.js",
12-
"./use-slot": "./src/use-slot/use-slot.js"
12+
"./use-slot": "./src/use-slot/use-slot.js",
13+
"./use-parent": "./src/use-parent/use-parent.js"
1314
},
1415
"typings": "*.d.ts",
1516
"editable": "https://github.com/atomicojs/atomico-kit/tree/master",

src/use-parent/use-parent.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { useHost, useMemo } from "atomico";
2+
/**
3+
* @param {string} matches
4+
* @returns {import("atomico").Ref<HTMLElement>}
5+
*/
6+
export function useParent(matches) {
7+
const host = useHost();
8+
return useMemo(() => {
9+
let { current } = host;
10+
while ((current = current.parentNode || current.host)) {
11+
if (current.matches && current.matches(matches)) {
12+
return { current };
13+
}
14+
}
15+
return {};
16+
}, [matches]);
17+
}

src/use-parent/use-parent.test.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { expect } from "@esm-bundle/chai";
2+
import { createHooks } from "atomico/test-hooks";
3+
import { useParent } from "./use-parent.js";
4+
5+
it("useParent", () => {
6+
const host = document.createElement("div");
7+
const hooks = createHooks(null, host);
8+
9+
document.body.appendChild(host);
10+
11+
hooks.load(() => {
12+
const ref = useParent("body");
13+
expect(ref.current).to.equal(document.body);
14+
});
15+
});
16+
17+
it("useParent shadowRoot", () => {
18+
const host = document.createElement("div");
19+
const child = new Image();
20+
host.attachShadow({ mode: "open" }).appendChild(child);
21+
const hooks = createHooks(null, child);
22+
23+
document.body.appendChild(host);
24+
25+
hooks.load(() => {
26+
const ref = useParent("body");
27+
expect(ref.current).to.equal(document.body);
28+
});
29+
});

use-parent.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { useParent } from "./src/use-parent/use-parent.js";

0 commit comments

Comments
 (0)