Skip to content

Commit 5e6032b

Browse files
author
Bob Fanger
committed
fix: Remove element based on component lifecycle
1 parent a468b37 commit 5e6032b

File tree

3 files changed

+54
-3
lines changed

3 files changed

+54
-3
lines changed

src/Portal.svelte

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@
3636
}
3737
3838
function destroy() {
39-
if (el.parent) {
40-
el.parent.removeChild(el);
39+
if (el.parentNode) {
40+
el.parentNode.removeChild(el);
4141
}
4242
}
4343

test/Portal.test.js

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { render } from "@testing-library/svelte";
22

33
import TestPortalWrapper from "./TestPortalWrapper.svelte";
4+
import TestLifecycle from "./TestLifecycle.svelte";
5+
import { tick } from "svelte";
46

5-
describe("<Portal />", () => {
7+
describe("<Portal /> target", () => {
68
let wrapper;
79

810
beforeEach(() => {
@@ -42,3 +44,34 @@ describe("<Portal />", () => {
4244
expect(isPortalContainerEmpty).toBe(true);
4345
});
4446
});
47+
48+
describe("<Portal /> lifecycle", () => {
49+
let targetEl;
50+
let lifecycleComponent;
51+
beforeEach(() => {
52+
let { container, component } = render(TestLifecycle);
53+
lifecycleComponent = component;
54+
targetEl = container.querySelector("#modals");
55+
});
56+
it("should be added and removed from dom", async () => {
57+
expect(targetEl.children).toHaveLength(1);
58+
lifecycleComponent.$set({ modalVisible: false });
59+
await tick();
60+
expect(targetEl.children).toHaveLength(0);
61+
lifecycleComponent.$set({ modalVisible: true });
62+
await tick();
63+
expect(targetEl.children).toHaveLength(1);
64+
});
65+
it("should be removed from dom after after outro", async () => {
66+
lifecycleComponent.$set({ containerVisible: false });
67+
await tick();
68+
expect(targetEl.children).toHaveLength(1);
69+
await new Promise((resolve) => {
70+
const unsubscribe = lifecycleComponent.$on("outroend", () => {
71+
resolve();
72+
unsubscribe();
73+
});
74+
});
75+
expect(targetEl.children).toHaveLength(0);
76+
});
77+
});

test/TestLifecycle.svelte

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<script>
2+
import { fade } from "svelte/transition";
3+
import Portal from "../src/Portal.svelte";
4+
5+
export let modalVisible = true;
6+
export let containerVisible = true;
7+
</script>
8+
9+
{#if containerVisible}
10+
<div out:fade={{ duration: 100 }} on:outroend>
11+
{#if modalVisible}
12+
<Portal target="#modals">
13+
<div id="modal" />
14+
</Portal>
15+
{/if}
16+
</div>
17+
{/if}
18+
<div id="modals" />

0 commit comments

Comments
 (0)