UNPKG

@stimulus-library/controllers

Version:

A library of useful controllers for Stimulus

49 lines (48 loc) 1.79 kB
import { EphemeralController } from "@stimulus-library/utilities"; export class TeleportController extends EphemeralController { connect() { if (!this.hasInsertValue) { throw new Error("`insert` value was not specified"); } requestAnimationFrame(() => { if (this.hasImmediateValue && this.immediateValue) { this.execute(); } }); } execute(event) { event === null || event === void 0 ? void 0 : event.preventDefault(); const element = this.el; const destination = document.querySelector(this.targetValue); if (destination == null) { this.dispatchEvent(element, this.eventName("error")); return; } const copy = element.cloneNode(true); this.cleanup(copy); switch (this.insertValue) { case "beforebegin": case "beforeend": case "afterend": case "afterbegin": destination.insertAdjacentHTML(this.insertValue, copy.outerHTML); break; case "replaceOuter": destination.outerHTML = copy.outerHTML; break; case "replaceInner": destination.innerHTML = copy.outerHTML; break; case "prepend": destination.insertAdjacentHTML("afterbegin", copy.outerHTML); break; case "append": destination.insertAdjacentHTML("beforeend", copy.outerHTML); break; default: throw new Error("`insert` value was not specified"); } element.remove(); } } TeleportController.values = { target: String, insert: String, immediate: Boolean };