Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/Portal.svelte
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
<svelte:options immutable />

<script context="module">
import { tick } from "svelte";

/**
* Usage: <div use:portal={'css selector'}> or <div use:portal={document.body}>
*
* @param {HTMLElement} el
* @param {HTMLElement|string} target DOM Element or CSS Selector
*/
export function portal(el, target = "body") {
const document = el.ownerDocument;
let targetEl;
async function update(newTarget) {
target = newTarget;
Expand Down Expand Up @@ -57,6 +59,6 @@
export let target = "body";
</script>

<div use:portal={target} hidden>
<div {...$$restProps} use:portal={target} hidden>
<slot />
</div>
12 changes: 12 additions & 0 deletions test/Portal.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ describe("<Portal /> target", () => {
expect(renderedDivInTargetClass).not.toBe(null);
});

it("should be rendererd in the default HTML element (document.body) with attributes on parent", () => {
const renderedInDefaultWithProps = wrapper.querySelector(
"body #renderedInDefaultWithAttributes"
);

expect(renderedInDefaultWithProps).not.toBe(null);
expect(renderedInDefaultWithProps.parentNode).not.toBe(null);
expect(renderedInDefaultWithProps.parentNode.style.position).toBe(
"absolute"
);
});

it("should not render a Portal at the origin", () => {
const portalContainer = wrapper.querySelector("#portalCtn");
const isPortalContainerEmpty =
Expand Down
5 changes: 5 additions & 0 deletions test/TestPortalWrapper.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
<Portal target="body > .target">
<div id="renderedInTargetClass"></div>
</Portal>
<Portal
style="position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);"
>
<div id="renderedInDefaultWithAttributes"></div>
</Portal>
</div>
</main>

Expand Down