has a single root element. `);
- }
- }
- function kebabCase(subject) {
- return subject.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]/, "-").toLowerCase();
- }
- function camelCase(subject) {
- return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase());
- }
- function walk(el, callback) {
- if (callback(el) === false)
- return;
- let node = el.firstElementChild;
- while (node) {
- walk(node, callback);
- node = node.nextElementSibling;
- }
- }
- function debounce(func, wait) {
- var timeout;
- return function() {
- var context = this, args = arguments;
- var later = function later2() {
- timeout = null;
- func.apply(context, args);
- };
- clearTimeout(timeout);
- timeout = setTimeout(later, wait);
- };
- }
- const handleError = (el, expression, error) => {
- console.warn(`Alpine Error: "${error}"
-
-Expression: "${expression}"
-Element:`, el);
- if (!isTesting()) {
- Object.assign(error, {
- el,
- expression
- });
- throw error;
- }
- };
- function tryCatch(cb, {
- el,
- expression
- }) {
- try {
- const value = cb();
- return value instanceof Promise ? value.catch((e2) => handleError(el, expression, e2)) : value;
- } catch (e2) {
- handleError(el, expression, e2);
- }
- }
- function saferEval(el, expression, dataContext, additionalHelperVariables = {}) {
- return tryCatch(() => {
- if (typeof expression === "function") {
- return expression.call(dataContext);
- }
- return new Function(["$data", ...Object.keys(additionalHelperVariables)], `var __alpine_result; with($data) { __alpine_result = ${expression} }; return __alpine_result`)(dataContext, ...Object.values(additionalHelperVariables));
- }, {
- el,
- expression
- });
- }
- function saferEvalNoReturn(el, expression, dataContext, additionalHelperVariables = {}) {
- return tryCatch(() => {
- if (typeof expression === "function") {
- return Promise.resolve(expression.call(dataContext, additionalHelperVariables["$event"]));
- }
- let AsyncFunction = Function;
- AsyncFunction = Object.getPrototypeOf(async function() {
- }).constructor;
- if (Object.keys(dataContext).includes(expression)) {
- let methodReference = new Function(["dataContext", ...Object.keys(additionalHelperVariables)], `with(dataContext) { return ${expression} }`)(dataContext, ...Object.values(additionalHelperVariables));
- if (typeof methodReference === "function") {
- return Promise.resolve(methodReference.call(dataContext, additionalHelperVariables["$event"]));
- } else {
- return Promise.resolve();
- }
- }
- return Promise.resolve(new AsyncFunction(["dataContext", ...Object.keys(additionalHelperVariables)], `with(dataContext) { ${expression} }`)(dataContext, ...Object.values(additionalHelperVariables)));
- }, {
- el,
- expression
- });
- }
- const xAttrRE = /^x-(on|bind|data|text|html|model|if|for|show|cloak|transition|ref|spread)\b/;
- function isXAttr(attr) {
- const name = replaceAtAndColonWithStandardSyntax(attr.name);
- return xAttrRE.test(name);
- }
- function getXAttrs(el, component, type) {
- let directives = Array.from(el.attributes).filter(isXAttr).map(parseHtmlAttribute);
- let spreadDirective = directives.filter((directive) => directive.type === "spread")[0];
- if (spreadDirective) {
- let spreadObject = saferEval(el, spreadDirective.expression, component.$data);
- directives = directives.concat(Object.entries(spreadObject).map(([name, value]) => parseHtmlAttribute({
- name,
- value
- })));
- }
- if (type)
- return directives.filter((i2) => i2.type === type);
- return sortDirectives(directives);
- }
- function sortDirectives(directives) {
- let directiveOrder = ["bind", "model", "show", "catch-all"];
- return directives.sort((a2, b2) => {
- let typeA = directiveOrder.indexOf(a2.type) === -1 ? "catch-all" : a2.type;
- let typeB = directiveOrder.indexOf(b2.type) === -1 ? "catch-all" : b2.type;
- return directiveOrder.indexOf(typeA) - directiveOrder.indexOf(typeB);
- });
- }
- function parseHtmlAttribute({
- name,
- value
- }) {
- const normalizedName = replaceAtAndColonWithStandardSyntax(name);
- const typeMatch = normalizedName.match(xAttrRE);
- const valueMatch = normalizedName.match(/:([a-zA-Z0-9\-:]+)/);
- const modifiers = normalizedName.match(/\.[^.\]]+(?=[^\]]*$)/g) || [];
- return {
- type: typeMatch ? typeMatch[1] : null,
- value: valueMatch ? valueMatch[1] : null,
- modifiers: modifiers.map((i2) => i2.replace(".", "")),
- expression: value
- };
- }
- function isBooleanAttr(attrName) {
- const booleanAttributes = ["disabled", "checked", "required", "readonly", "hidden", "open", "selected", "autofocus", "itemscope", "multiple", "novalidate", "allowfullscreen", "allowpaymentrequest", "formnovalidate", "autoplay", "controls", "loop", "muted", "playsinline", "default", "ismap", "reversed", "async", "defer", "nomodule"];
- return booleanAttributes.includes(attrName);
- }
- function replaceAtAndColonWithStandardSyntax(name) {
- if (name.startsWith("@")) {
- return name.replace("@", "x-on:");
- } else if (name.startsWith(":")) {
- return name.replace(":", "x-bind:");
- }
- return name;
- }
- function convertClassStringToArray(classList, filterFn = Boolean) {
- return classList.split(" ").filter(filterFn);
- }
- const TRANSITION_TYPE_IN = "in";
- const TRANSITION_TYPE_OUT = "out";
- const TRANSITION_CANCELLED = "cancelled";
- function transitionIn(el, show, reject, component, forceSkip = false) {
- if (forceSkip)
- return show();
- if (el.__x_transition && el.__x_transition.type === TRANSITION_TYPE_IN) {
- return;
- }
- const attrs = getXAttrs(el, component, "transition");
- const showAttr = getXAttrs(el, component, "show")[0];
- if (showAttr && showAttr.modifiers.includes("transition")) {
- let modifiers = showAttr.modifiers;
- if (modifiers.includes("out") && !modifiers.includes("in"))
- return show();
- const settingBothSidesOfTransition = modifiers.includes("in") && modifiers.includes("out");
- modifiers = settingBothSidesOfTransition ? modifiers.filter((i2, index) => index < modifiers.indexOf("out")) : modifiers;
- transitionHelperIn(el, modifiers, show, reject);
- } else if (attrs.some((attr) => ["enter", "enter-start", "enter-end"].includes(attr.value))) {
- transitionClassesIn(el, component, attrs, show, reject);
- } else {
- show();
- }
- }
- function transitionOut(el, hide, reject, component, forceSkip = false) {
- if (forceSkip)
- return hide();
- if (el.__x_transition && el.__x_transition.type === TRANSITION_TYPE_OUT) {
- return;
- }
- const attrs = getXAttrs(el, component, "transition");
- const showAttr = getXAttrs(el, component, "show")[0];
- if (showAttr && showAttr.modifiers.includes("transition")) {
- let modifiers = showAttr.modifiers;
- if (modifiers.includes("in") && !modifiers.includes("out"))
- return hide();
- const settingBothSidesOfTransition = modifiers.includes("in") && modifiers.includes("out");
- modifiers = settingBothSidesOfTransition ? modifiers.filter((i2, index) => index > modifiers.indexOf("out")) : modifiers;
- transitionHelperOut(el, modifiers, settingBothSidesOfTransition, hide, reject);
- } else if (attrs.some((attr) => ["leave", "leave-start", "leave-end"].includes(attr.value))) {
- transitionClassesOut(el, component, attrs, hide, reject);
- } else {
- hide();
- }
- }
- function transitionHelperIn(el, modifiers, showCallback, reject) {
- const styleValues = {
- duration: modifierValue(modifiers, "duration", 150),
- origin: modifierValue(modifiers, "origin", "center"),
- first: {
- opacity: 0,
- scale: modifierValue(modifiers, "scale", 95)
- },
- second: {
- opacity: 1,
- scale: 100
- }
- };
- transitionHelper(el, modifiers, showCallback, () => {
- }, reject, styleValues, TRANSITION_TYPE_IN);
- }
- function transitionHelperOut(el, modifiers, settingBothSidesOfTransition, hideCallback, reject) {
- const duration = settingBothSidesOfTransition ? modifierValue(modifiers, "duration", 150) : modifierValue(modifiers, "duration", 150) / 2;
- const styleValues = {
- duration,
- origin: modifierValue(modifiers, "origin", "center"),
- first: {
- opacity: 1,
- scale: 100
- },
- second: {
- opacity: 0,
- scale: modifierValue(modifiers, "scale", 95)
- }
- };
- transitionHelper(el, modifiers, () => {
- }, hideCallback, reject, styleValues, TRANSITION_TYPE_OUT);
- }
- function modifierValue(modifiers, key, fallback) {
- if (modifiers.indexOf(key) === -1)
- return fallback;
- const rawValue = modifiers[modifiers.indexOf(key) + 1];
- if (!rawValue)
- return fallback;
- if (key === "scale") {
- if (!isNumeric(rawValue))
- return fallback;
- }
- if (key === "duration") {
- let match = rawValue.match(/([0-9]+)ms/);
- if (match)
- return match[1];
- }
- if (key === "origin") {
- if (["top", "right", "left", "center", "bottom"].includes(modifiers[modifiers.indexOf(key) + 2])) {
- return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(" ");
- }
- }
- return rawValue;
- }
- function transitionHelper(el, modifiers, hook1, hook2, reject, styleValues, type) {
- if (el.__x_transition) {
- el.__x_transition.cancel && el.__x_transition.cancel();
- }
- const opacityCache = el.style.opacity;
- const transformCache = el.style.transform;
- const transformOriginCache = el.style.transformOrigin;
- const noModifiers = !modifiers.includes("opacity") && !modifiers.includes("scale");
- const transitionOpacity = noModifiers || modifiers.includes("opacity");
- const transitionScale = noModifiers || modifiers.includes("scale");
- const stages = {
- start() {
- if (transitionOpacity)
- el.style.opacity = styleValues.first.opacity;
- if (transitionScale)
- el.style.transform = `scale(${styleValues.first.scale / 100})`;
- },
- during() {
- if (transitionScale)
- el.style.transformOrigin = styleValues.origin;
- el.style.transitionProperty = [transitionOpacity ? `opacity` : ``, transitionScale ? `transform` : ``].join(" ").trim();
- el.style.transitionDuration = `${styleValues.duration / 1e3}s`;
- el.style.transitionTimingFunction = `cubic-bezier(0.4, 0.0, 0.2, 1)`;
- },
- show() {
- hook1();
- },
- end() {
- if (transitionOpacity)
- el.style.opacity = styleValues.second.opacity;
- if (transitionScale)
- el.style.transform = `scale(${styleValues.second.scale / 100})`;
- },
- hide() {
- hook2();
- },
- cleanup() {
- if (transitionOpacity)
- el.style.opacity = opacityCache;
- if (transitionScale)
- el.style.transform = transformCache;
- if (transitionScale)
- el.style.transformOrigin = transformOriginCache;
- el.style.transitionProperty = null;
- el.style.transitionDuration = null;
- el.style.transitionTimingFunction = null;
- }
- };
- transition(el, stages, type, reject);
- }
- const ensureStringExpression = (expression, el, component) => {
- return typeof expression === "function" ? component.evaluateReturnExpression(el, expression) : expression;
- };
- function transitionClassesIn(el, component, directives, showCallback, reject) {
- const enter = convertClassStringToArray(ensureStringExpression((directives.find((i2) => i2.value === "enter") || {
- expression: ""
- }).expression, el, component));
- const enterStart = convertClassStringToArray(ensureStringExpression((directives.find((i2) => i2.value === "enter-start") || {
- expression: ""
- }).expression, el, component));
- const enterEnd = convertClassStringToArray(ensureStringExpression((directives.find((i2) => i2.value === "enter-end") || {
- expression: ""
- }).expression, el, component));
- transitionClasses(el, enter, enterStart, enterEnd, showCallback, () => {
- }, TRANSITION_TYPE_IN, reject);
- }
- function transitionClassesOut(el, component, directives, hideCallback, reject) {
- const leave = convertClassStringToArray(ensureStringExpression((directives.find((i2) => i2.value === "leave") || {
- expression: ""
- }).expression, el, component));
- const leaveStart = convertClassStringToArray(ensureStringExpression((directives.find((i2) => i2.value === "leave-start") || {
- expression: ""
- }).expression, el, component));
- const leaveEnd = convertClassStringToArray(ensureStringExpression((directives.find((i2) => i2.value === "leave-end") || {
- expression: ""
- }).expression, el, component));
- transitionClasses(el, leave, leaveStart, leaveEnd, () => {
- }, hideCallback, TRANSITION_TYPE_OUT, reject);
- }
- function transitionClasses(el, classesDuring, classesStart, classesEnd, hook1, hook2, type, reject) {
- if (el.__x_transition) {
- el.__x_transition.cancel && el.__x_transition.cancel();
- }
- const originalClasses = el.__x_original_classes || [];
- const stages = {
- start() {
- el.classList.add(...classesStart);
- },
- during() {
- el.classList.add(...classesDuring);
- },
- show() {
- hook1();
- },
- end() {
- el.classList.remove(...classesStart.filter((i2) => !originalClasses.includes(i2)));
- el.classList.add(...classesEnd);
- },
- hide() {
- hook2();
- },
- cleanup() {
- el.classList.remove(...classesDuring.filter((i2) => !originalClasses.includes(i2)));
- el.classList.remove(...classesEnd.filter((i2) => !originalClasses.includes(i2)));
- }
- };
- transition(el, stages, type, reject);
- }
- function transition(el, stages, type, reject) {
- const finish = once(() => {
- stages.hide();
- if (el.isConnected) {
- stages.cleanup();
- }
- delete el.__x_transition;
- });
- el.__x_transition = {
- // Set transition type so we can avoid clearing transition if the direction is the same
- type,
- // create a callback for the last stages of the transition so we can call it
- // from different point and early terminate it. Once will ensure that function
- // is only called one time.
- cancel: once(() => {
- reject(TRANSITION_CANCELLED);
- finish();
- }),
- finish,
- // This store the next animation frame so we can cancel it
- nextFrame: null
- };
- stages.start();
- stages.during();
- el.__x_transition.nextFrame = requestAnimationFrame(() => {
- let duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, "").replace("s", "")) * 1e3;
- if (duration === 0) {
- duration = Number(getComputedStyle(el).animationDuration.replace("s", "")) * 1e3;
- }
- stages.show();
- el.__x_transition.nextFrame = requestAnimationFrame(() => {
- stages.end();
- setTimeout(el.__x_transition.finish, duration);
- });
- });
- }
- function isNumeric(subject) {
- return !Array.isArray(subject) && !isNaN(subject);
- }
- function once(callback) {
- let called = false;
- return function() {
- if (!called) {
- called = true;
- callback.apply(this, arguments);
- }
- };
- }
- function handleForDirective(component, templateEl, expression, initialUpdate, extraVars) {
- warnIfMalformedTemplate(templateEl, "x-for");
- let iteratorNames = typeof expression === "function" ? parseForExpression(component.evaluateReturnExpression(templateEl, expression)) : parseForExpression(expression);
- let items = evaluateItemsAndReturnEmptyIfXIfIsPresentAndFalseOnElement(component, templateEl, iteratorNames, extraVars);
- let currentEl = templateEl;
- items.forEach((item, index) => {
- let iterationScopeVariables = getIterationScopeVariables(iteratorNames, item, index, items, extraVars());
- let currentKey = generateKeyForIteration(component, templateEl, index, iterationScopeVariables);
- let nextEl = lookAheadForMatchingKeyedElementAndMoveItIfFound(currentEl.nextElementSibling, currentKey);
- if (!nextEl) {
- nextEl = addElementInLoopAfterCurrentEl(templateEl, currentEl);
- transitionIn(nextEl, () => {
- }, () => {
- }, component, initialUpdate);
- nextEl.__x_for = iterationScopeVariables;
- component.initializeElements(nextEl, () => nextEl.__x_for);
- } else {
- delete nextEl.__x_for_key;
- nextEl.__x_for = iterationScopeVariables;
- component.updateElements(nextEl, () => nextEl.__x_for);
- }
- currentEl = nextEl;
- currentEl.__x_for_key = currentKey;
- });
- removeAnyLeftOverElementsFromPreviousUpdate(currentEl, component);
- }
- function parseForExpression(expression) {
- let forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
- let stripParensRE = /^\(|\)$/g;
- let forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
- let inMatch = String(expression).match(forAliasRE);
- if (!inMatch)
- return;
- let res = {};
- res.items = inMatch[2].trim();
- let item = inMatch[1].trim().replace(stripParensRE, "");
- let iteratorMatch = item.match(forIteratorRE);
- if (iteratorMatch) {
- res.item = item.replace(forIteratorRE, "").trim();
- res.index = iteratorMatch[1].trim();
- if (iteratorMatch[2]) {
- res.collection = iteratorMatch[2].trim();
- }
- } else {
- res.item = item;
- }
- return res;
- }
- function getIterationScopeVariables(iteratorNames, item, index, items, extraVars) {
- let scopeVariables = extraVars ? _objectSpread2({}, extraVars) : {};
- scopeVariables[iteratorNames.item] = item;
- if (iteratorNames.index)
- scopeVariables[iteratorNames.index] = index;
- if (iteratorNames.collection)
- scopeVariables[iteratorNames.collection] = items;
- return scopeVariables;
- }
- function generateKeyForIteration(component, el, index, iterationScopeVariables) {
- let bindKeyAttribute = getXAttrs(el, component, "bind").filter((attr) => attr.value === "key")[0];
- if (!bindKeyAttribute)
- return index;
- return component.evaluateReturnExpression(el, bindKeyAttribute.expression, () => iterationScopeVariables);
- }
- function evaluateItemsAndReturnEmptyIfXIfIsPresentAndFalseOnElement(component, el, iteratorNames, extraVars) {
- let ifAttribute = getXAttrs(el, component, "if")[0];
- if (ifAttribute && !component.evaluateReturnExpression(el, ifAttribute.expression)) {
- return [];
- }
- let items = component.evaluateReturnExpression(el, iteratorNames.items, extraVars);
- if (isNumeric(items) && items >= 0) {
- items = Array.from(Array(items).keys(), (i2) => i2 + 1);
- }
- return items;
- }
- function addElementInLoopAfterCurrentEl(templateEl, currentEl) {
- let clone2 = document.importNode(templateEl.content, true);
- currentEl.parentElement.insertBefore(clone2, currentEl.nextElementSibling);
- return currentEl.nextElementSibling;
- }
- function lookAheadForMatchingKeyedElementAndMoveItIfFound(nextEl, currentKey) {
- if (!nextEl)
- return;
- if (nextEl.__x_for_key === void 0)
- return;
- if (nextEl.__x_for_key === currentKey)
- return nextEl;
- let tmpNextEl = nextEl;
- while (tmpNextEl) {
- if (tmpNextEl.__x_for_key === currentKey) {
- return tmpNextEl.parentElement.insertBefore(tmpNextEl, nextEl);
- }
- tmpNextEl = tmpNextEl.nextElementSibling && tmpNextEl.nextElementSibling.__x_for_key !== void 0 ? tmpNextEl.nextElementSibling : false;
- }
- }
- function removeAnyLeftOverElementsFromPreviousUpdate(currentEl, component) {
- var nextElementFromOldLoop = currentEl.nextElementSibling && currentEl.nextElementSibling.__x_for_key !== void 0 ? currentEl.nextElementSibling : false;
- while (nextElementFromOldLoop) {
- let nextElementFromOldLoopImmutable = nextElementFromOldLoop;
- let nextSibling = nextElementFromOldLoop.nextElementSibling;
- transitionOut(nextElementFromOldLoop, () => {
- nextElementFromOldLoopImmutable.remove();
- }, () => {
- }, component);
- nextElementFromOldLoop = nextSibling && nextSibling.__x_for_key !== void 0 ? nextSibling : false;
- }
- }
- function handleAttributeBindingDirective(component, el, attrName, expression, extraVars, attrType, modifiers) {
- var value = component.evaluateReturnExpression(el, expression, extraVars);
- if (attrName === "value") {
- if (Alpine3.ignoreFocusedForValueBinding && document.activeElement.isSameNode(el))
- return;
- if (value === void 0 && String(expression).match(/\./)) {
- value = "";
- }
- if (el.type === "radio") {
- if (el.attributes.value === void 0 && attrType === "bind") {
- el.value = value;
- } else if (attrType !== "bind") {
- el.checked = checkedAttrLooseCompare(el.value, value);
- }
- } else if (el.type === "checkbox") {
- if (typeof value !== "boolean" && ![null, void 0].includes(value) && attrType === "bind") {
- el.value = String(value);
- } else if (attrType !== "bind") {
- if (Array.isArray(value)) {
- el.checked = value.some((val) => checkedAttrLooseCompare(val, el.value));
- } else {
- el.checked = !!value;
- }
- }
- } else if (el.tagName === "SELECT") {
- updateSelect(el, value);
- } else {
- if (el.value === value)
- return;
- el.value = value;
- }
- } else if (attrName === "class") {
- if (Array.isArray(value)) {
- const originalClasses = el.__x_original_classes || [];
- el.setAttribute("class", arrayUnique(originalClasses.concat(value)).join(" "));
- } else if (typeof value === "object") {
- const keysSortedByBooleanValue = Object.keys(value).sort((a2, b2) => value[a2] - value[b2]);
- keysSortedByBooleanValue.forEach((classNames) => {
- if (value[classNames]) {
- convertClassStringToArray(classNames).forEach((className) => el.classList.add(className));
- } else {
- convertClassStringToArray(classNames).forEach((className) => el.classList.remove(className));
- }
- });
- } else {
- const originalClasses = el.__x_original_classes || [];
- const newClasses = value ? convertClassStringToArray(value) : [];
- el.setAttribute("class", arrayUnique(originalClasses.concat(newClasses)).join(" "));
- }
- } else {
- attrName = modifiers.includes("camel") ? camelCase(attrName) : attrName;
- if ([null, void 0, false].includes(value)) {
- el.removeAttribute(attrName);
- } else {
- isBooleanAttr(attrName) ? setIfChanged(el, attrName, attrName) : setIfChanged(el, attrName, value);
- }
- }
- }
- function setIfChanged(el, attrName, value) {
- if (el.getAttribute(attrName) != value) {
- el.setAttribute(attrName, value);
- }
- }
- function updateSelect(el, value) {
- const arrayWrappedValue = [].concat(value).map((value2) => {
- return value2 + "";
- });
- Array.from(el.options).forEach((option) => {
- option.selected = arrayWrappedValue.includes(option.value || option.text);
- });
- }
- function handleTextDirective(el, output, expression) {
- if (output === void 0 && String(expression).match(/\./)) {
- output = "";
- }
- el.textContent = output;
- }
- function handleHtmlDirective(component, el, expression, extraVars) {
- el.innerHTML = component.evaluateReturnExpression(el, expression, extraVars);
- }
- function handleShowDirective(component, el, value, modifiers, initialUpdate = false) {
- const hide = () => {
- el.style.display = "none";
- el.__x_is_shown = false;
- };
- const show = () => {
- if (el.style.length === 1 && el.style.display === "none") {
- el.removeAttribute("style");
- } else {
- el.style.removeProperty("display");
- }
- el.__x_is_shown = true;
- };
- if (initialUpdate === true) {
- if (value) {
- show();
- } else {
- hide();
- }
- return;
- }
- const handle = (resolve, reject) => {
- if (value) {
- if (el.style.display === "none" || el.__x_transition) {
- transitionIn(el, () => {
- show();
- }, reject, component);
- }
- resolve(() => {
- });
- } else {
- if (el.style.display !== "none") {
- transitionOut(el, () => {
- resolve(() => {
- hide();
- });
- }, reject, component);
- } else {
- resolve(() => {
- });
- }
- }
- };
- if (modifiers.includes("immediate")) {
- handle((finish) => finish(), () => {
- });
- return;
- }
- if (component.showDirectiveLastElement && !component.showDirectiveLastElement.contains(el)) {
- component.executeAndClearRemainingShowDirectiveStack();
- }
- component.showDirectiveStack.push(handle);
- component.showDirectiveLastElement = el;
- }
- function handleIfDirective(component, el, expressionResult, initialUpdate, extraVars) {
- warnIfMalformedTemplate(el, "x-if");
- const elementHasAlreadyBeenAdded = el.nextElementSibling && el.nextElementSibling.__x_inserted_me === true;
- if (expressionResult && (!elementHasAlreadyBeenAdded || el.__x_transition)) {
- const clone2 = document.importNode(el.content, true);
- el.parentElement.insertBefore(clone2, el.nextElementSibling);
- transitionIn(el.nextElementSibling, () => {
- }, () => {
- }, component, initialUpdate);
- component.initializeElements(el.nextElementSibling, extraVars);
- el.nextElementSibling.__x_inserted_me = true;
- } else if (!expressionResult && elementHasAlreadyBeenAdded) {
- transitionOut(el.nextElementSibling, () => {
- el.nextElementSibling.remove();
- }, () => {
- }, component, initialUpdate);
- }
- }
- function registerListener(component, el, event, modifiers, expression, extraVars = {}) {
- const options = {
- passive: modifiers.includes("passive")
- };
- if (modifiers.includes("camel")) {
- event = camelCase(event);
- }
- let handler, listenerTarget;
- if (modifiers.includes("away")) {
- listenerTarget = document;
- handler = (e2) => {
- if (el.contains(e2.target))
- return;
- if (el.offsetWidth < 1 && el.offsetHeight < 1)
- return;
- runListenerHandler(component, expression, e2, extraVars);
- if (modifiers.includes("once")) {
- document.removeEventListener(event, handler, options);
- }
- };
- } else {
- listenerTarget = modifiers.includes("window") ? window : modifiers.includes("document") ? document : el;
- handler = (e2) => {
- if (listenerTarget === window || listenerTarget === document) {
- if (!document.body.contains(el)) {
- listenerTarget.removeEventListener(event, handler, options);
- return;
- }
- }
- if (isKeyEvent(event)) {
- if (isListeningForASpecificKeyThatHasntBeenPressed(e2, modifiers)) {
- return;
- }
- }
- if (modifiers.includes("prevent"))
- e2.preventDefault();
- if (modifiers.includes("stop"))
- e2.stopPropagation();
- if (!modifiers.includes("self") || e2.target === el) {
- const returnValue = runListenerHandler(component, expression, e2, extraVars);
- returnValue.then((value) => {
- if (value === false) {
- e2.preventDefault();
- } else {
- if (modifiers.includes("once")) {
- listenerTarget.removeEventListener(event, handler, options);
- }
- }
- });
- }
- };
- }
- if (modifiers.includes("debounce")) {
- let nextModifier = modifiers[modifiers.indexOf("debounce") + 1] || "invalid-wait";
- let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250;
- handler = debounce(handler, wait);
- }
- listenerTarget.addEventListener(event, handler, options);
- }
- function runListenerHandler(component, expression, e2, extraVars) {
- return component.evaluateCommandExpression(e2.target, expression, () => {
- return _objectSpread2(_objectSpread2({}, extraVars()), {}, {
- "$event": e2
- });
- });
- }
- function isKeyEvent(event) {
- return ["keydown", "keyup"].includes(event);
- }
- function isListeningForASpecificKeyThatHasntBeenPressed(e2, modifiers) {
- let keyModifiers = modifiers.filter((i2) => {
- return !["window", "document", "prevent", "stop"].includes(i2);
- });
- if (keyModifiers.includes("debounce")) {
- let debounceIndex = keyModifiers.indexOf("debounce");
- keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || "invalid-wait").split("ms")[0]) ? 2 : 1);
- }
- if (keyModifiers.length === 0)
- return false;
- if (keyModifiers.length === 1 && keyModifiers[0] === keyToModifier(e2.key))
- return false;
- const systemKeyModifiers = ["ctrl", "shift", "alt", "meta", "cmd", "super"];
- const selectedSystemKeyModifiers = systemKeyModifiers.filter((modifier) => keyModifiers.includes(modifier));
- keyModifiers = keyModifiers.filter((i2) => !selectedSystemKeyModifiers.includes(i2));
- if (selectedSystemKeyModifiers.length > 0) {
- const activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter((modifier) => {
- if (modifier === "cmd" || modifier === "super")
- modifier = "meta";
- return e2[`${modifier}Key`];
- });
- if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) {
- if (keyModifiers[0] === keyToModifier(e2.key))
- return false;
- }
- }
- return true;
- }
- function keyToModifier(key) {
- switch (key) {
- case "/":
- return "slash";
- case " ":
- case "Spacebar":
- return "space";
- default:
- return key && kebabCase(key);
- }
- }
- function registerModelListener(component, el, modifiers, expression, extraVars) {
- var event = el.tagName.toLowerCase() === "select" || ["checkbox", "radio"].includes(el.type) || modifiers.includes("lazy") ? "change" : "input";
- const listenerExpression = `${expression} = rightSideOfExpression($event, ${expression})`;
- registerListener(component, el, event, modifiers, listenerExpression, () => {
- return _objectSpread2(_objectSpread2({}, extraVars()), {}, {
- rightSideOfExpression: generateModelAssignmentFunction(el, modifiers, expression)
- });
- });
- }
- function generateModelAssignmentFunction(el, modifiers, expression) {
- if (el.type === "radio") {
- if (!el.hasAttribute("name"))
- el.setAttribute("name", expression);
- }
- return (event, currentValue) => {
- if (event instanceof CustomEvent && event.detail) {
- return event.detail;
- } else if (el.type === "checkbox") {
- if (Array.isArray(currentValue)) {
- const newValue = modifiers.includes("number") ? safeParseNumber(event.target.value) : event.target.value;
- return event.target.checked ? currentValue.concat([newValue]) : currentValue.filter((el2) => !checkedAttrLooseCompare(el2, newValue));
- } else {
- return event.target.checked;
- }
- } else if (el.tagName.toLowerCase() === "select" && el.multiple) {
- return modifiers.includes("number") ? Array.from(event.target.selectedOptions).map((option) => {
- const rawValue = option.value || option.text;
- return safeParseNumber(rawValue);
- }) : Array.from(event.target.selectedOptions).map((option) => {
- return option.value || option.text;
- });
- } else {
- const rawValue = event.target.value;
- return modifiers.includes("number") ? safeParseNumber(rawValue) : modifiers.includes("trim") ? rawValue.trim() : rawValue;
- }
- };
- }
- function safeParseNumber(rawValue) {
- const number = rawValue ? parseFloat(rawValue) : null;
- return isNumeric(number) ? number : rawValue;
- }
- const { isArray } = Array;
- const { getPrototypeOf, create: ObjectCreate, defineProperty: ObjectDefineProperty, defineProperties: ObjectDefineProperties, isExtensible, getOwnPropertyDescriptor, getOwnPropertyNames, getOwnPropertySymbols, preventExtensions, hasOwnProperty } = Object;
- const { push: ArrayPush, concat: ArrayConcat, map: ArrayMap } = Array.prototype;
- function isUndefined(obj) {
- return obj === void 0;
- }
- function isFunction(obj) {
- return typeof obj === "function";
- }
- function isObject2(obj) {
- return typeof obj === "object";
- }
- const proxyToValueMap = /* @__PURE__ */ new WeakMap();
- function registerProxy(proxy, value) {
- proxyToValueMap.set(proxy, value);
- }
- const unwrap = (replicaOrAny) => proxyToValueMap.get(replicaOrAny) || replicaOrAny;
- function wrapValue(membrane, value) {
- return membrane.valueIsObservable(value) ? membrane.getProxy(value) : value;
- }
- function unwrapDescriptor(descriptor) {
- if (hasOwnProperty.call(descriptor, "value")) {
- descriptor.value = unwrap(descriptor.value);
- }
- return descriptor;
- }
- function lockShadowTarget(membrane, shadowTarget, originalTarget) {
- const targetKeys = ArrayConcat.call(getOwnPropertyNames(originalTarget), getOwnPropertySymbols(originalTarget));
- targetKeys.forEach((key) => {
- let descriptor = getOwnPropertyDescriptor(originalTarget, key);
- if (!descriptor.configurable) {
- descriptor = wrapDescriptor(membrane, descriptor, wrapValue);
- }
- ObjectDefineProperty(shadowTarget, key, descriptor);
- });
- preventExtensions(shadowTarget);
- }
- class ReactiveProxyHandler {
- constructor(membrane, value) {
- this.originalTarget = value;
- this.membrane = membrane;
- }
- get(shadowTarget, key) {
- const { originalTarget, membrane } = this;
- const value = originalTarget[key];
- const { valueObserved } = membrane;
- valueObserved(originalTarget, key);
- return membrane.getProxy(value);
- }
- set(shadowTarget, key, value) {
- const { originalTarget, membrane: { valueMutated } } = this;
- const oldValue = originalTarget[key];
- if (oldValue !== value) {
- originalTarget[key] = value;
- valueMutated(originalTarget, key);
- } else if (key === "length" && isArray(originalTarget)) {
- valueMutated(originalTarget, key);
- }
- return true;
- }
- deleteProperty(shadowTarget, key) {
- const { originalTarget, membrane: { valueMutated } } = this;
- delete originalTarget[key];
- valueMutated(originalTarget, key);
- return true;
- }
- apply(shadowTarget, thisArg, argArray) {
- }
- construct(target, argArray, newTarget) {
- }
- has(shadowTarget, key) {
- const { originalTarget, membrane: { valueObserved } } = this;
- valueObserved(originalTarget, key);
- return key in originalTarget;
- }
- ownKeys(shadowTarget) {
- const { originalTarget } = this;
- return ArrayConcat.call(getOwnPropertyNames(originalTarget), getOwnPropertySymbols(originalTarget));
- }
- isExtensible(shadowTarget) {
- const shadowIsExtensible = isExtensible(shadowTarget);
- if (!shadowIsExtensible) {
- return shadowIsExtensible;
- }
- const { originalTarget, membrane } = this;
- const targetIsExtensible = isExtensible(originalTarget);
- if (!targetIsExtensible) {
- lockShadowTarget(membrane, shadowTarget, originalTarget);
- }
- return targetIsExtensible;
- }
- setPrototypeOf(shadowTarget, prototype) {
- }
- getPrototypeOf(shadowTarget) {
- const { originalTarget } = this;
- return getPrototypeOf(originalTarget);
- }
- getOwnPropertyDescriptor(shadowTarget, key) {
- const { originalTarget, membrane } = this;
- const { valueObserved } = this.membrane;
- valueObserved(originalTarget, key);
- let desc = getOwnPropertyDescriptor(originalTarget, key);
- if (isUndefined(desc)) {
- return desc;
- }
- const shadowDescriptor = getOwnPropertyDescriptor(shadowTarget, key);
- if (!isUndefined(shadowDescriptor)) {
- return shadowDescriptor;
- }
- desc = wrapDescriptor(membrane, desc, wrapValue);
- if (!desc.configurable) {
- ObjectDefineProperty(shadowTarget, key, desc);
- }
- return desc;
- }
- preventExtensions(shadowTarget) {
- const { originalTarget, membrane } = this;
- lockShadowTarget(membrane, shadowTarget, originalTarget);
- preventExtensions(originalTarget);
- return true;
- }
- defineProperty(shadowTarget, key, descriptor) {
- const { originalTarget, membrane } = this;
- const { valueMutated } = membrane;
- const { configurable } = descriptor;
- if (hasOwnProperty.call(descriptor, "writable") && !hasOwnProperty.call(descriptor, "value")) {
- const originalDescriptor = getOwnPropertyDescriptor(originalTarget, key);
- descriptor.value = originalDescriptor.value;
- }
- ObjectDefineProperty(originalTarget, key, unwrapDescriptor(descriptor));
- if (configurable === false) {
- ObjectDefineProperty(shadowTarget, key, wrapDescriptor(membrane, descriptor, wrapValue));
- }
- valueMutated(originalTarget, key);
- return true;
- }
- }
- function wrapReadOnlyValue(membrane, value) {
- return membrane.valueIsObservable(value) ? membrane.getReadOnlyProxy(value) : value;
- }
- class ReadOnlyHandler {
- constructor(membrane, value) {
- this.originalTarget = value;
- this.membrane = membrane;
- }
- get(shadowTarget, key) {
- const { membrane, originalTarget } = this;
- const value = originalTarget[key];
- const { valueObserved } = membrane;
- valueObserved(originalTarget, key);
- return membrane.getReadOnlyProxy(value);
- }
- set(shadowTarget, key, value) {
- return false;
- }
- deleteProperty(shadowTarget, key) {
- return false;
- }
- apply(shadowTarget, thisArg, argArray) {
- }
- construct(target, argArray, newTarget) {
- }
- has(shadowTarget, key) {
- const { originalTarget, membrane: { valueObserved } } = this;
- valueObserved(originalTarget, key);
- return key in originalTarget;
- }
- ownKeys(shadowTarget) {
- const { originalTarget } = this;
- return ArrayConcat.call(getOwnPropertyNames(originalTarget), getOwnPropertySymbols(originalTarget));
- }
- setPrototypeOf(shadowTarget, prototype) {
- }
- getOwnPropertyDescriptor(shadowTarget, key) {
- const { originalTarget, membrane } = this;
- const { valueObserved } = membrane;
- valueObserved(originalTarget, key);
- let desc = getOwnPropertyDescriptor(originalTarget, key);
- if (isUndefined(desc)) {
- return desc;
- }
- const shadowDescriptor = getOwnPropertyDescriptor(shadowTarget, key);
- if (!isUndefined(shadowDescriptor)) {
- return shadowDescriptor;
- }
- desc = wrapDescriptor(membrane, desc, wrapReadOnlyValue);
- if (hasOwnProperty.call(desc, "set")) {
- desc.set = void 0;
- }
- if (!desc.configurable) {
- ObjectDefineProperty(shadowTarget, key, desc);
- }
- return desc;
- }
- preventExtensions(shadowTarget) {
- return false;
- }
- defineProperty(shadowTarget, key, descriptor) {
- return false;
- }
- }
- function createShadowTarget(value) {
- let shadowTarget = void 0;
- if (isArray(value)) {
- shadowTarget = [];
- } else if (isObject2(value)) {
- shadowTarget = {};
- }
- return shadowTarget;
- }
- const ObjectDotPrototype = Object.prototype;
- function defaultValueIsObservable(value) {
- if (value === null) {
- return false;
- }
- if (typeof value !== "object") {
- return false;
- }
- if (isArray(value)) {
- return true;
- }
- const proto = getPrototypeOf(value);
- return proto === ObjectDotPrototype || proto === null || getPrototypeOf(proto) === null;
- }
- const defaultValueObserved = (obj, key) => {
- };
- const defaultValueMutated = (obj, key) => {
- };
- const defaultValueDistortion = (value) => value;
- function wrapDescriptor(membrane, descriptor, getValue) {
- const { set, get } = descriptor;
- if (hasOwnProperty.call(descriptor, "value")) {
- descriptor.value = getValue(membrane, descriptor.value);
- } else {
- if (!isUndefined(get)) {
- descriptor.get = function() {
- return getValue(membrane, get.call(unwrap(this)));
- };
- }
- if (!isUndefined(set)) {
- descriptor.set = function(value) {
- set.call(unwrap(this), membrane.unwrapProxy(value));
- };
- }
- }
- return descriptor;
- }
- class ReactiveMembrane {
- constructor(options) {
- this.valueDistortion = defaultValueDistortion;
- this.valueMutated = defaultValueMutated;
- this.valueObserved = defaultValueObserved;
- this.valueIsObservable = defaultValueIsObservable;
- this.objectGraph = /* @__PURE__ */ new WeakMap();
- if (!isUndefined(options)) {
- const { valueDistortion, valueMutated, valueObserved, valueIsObservable } = options;
- this.valueDistortion = isFunction(valueDistortion) ? valueDistortion : defaultValueDistortion;
- this.valueMutated = isFunction(valueMutated) ? valueMutated : defaultValueMutated;
- this.valueObserved = isFunction(valueObserved) ? valueObserved : defaultValueObserved;
- this.valueIsObservable = isFunction(valueIsObservable) ? valueIsObservable : defaultValueIsObservable;
- }
- }
- getProxy(value) {
- const unwrappedValue = unwrap(value);
- const distorted = this.valueDistortion(unwrappedValue);
- if (this.valueIsObservable(distorted)) {
- const o2 = this.getReactiveState(unwrappedValue, distorted);
- return o2.readOnly === value ? value : o2.reactive;
- }
- return distorted;
- }
- getReadOnlyProxy(value) {
- value = unwrap(value);
- const distorted = this.valueDistortion(value);
- if (this.valueIsObservable(distorted)) {
- return this.getReactiveState(value, distorted).readOnly;
- }
- return distorted;
- }
- unwrapProxy(p2) {
- return unwrap(p2);
- }
- getReactiveState(value, distortedValue) {
- const { objectGraph } = this;
- let reactiveState = objectGraph.get(distortedValue);
- if (reactiveState) {
- return reactiveState;
- }
- const membrane = this;
- reactiveState = {
- get reactive() {
- const reactiveHandler = new ReactiveProxyHandler(membrane, distortedValue);
- const proxy = new Proxy(createShadowTarget(distortedValue), reactiveHandler);
- registerProxy(proxy, value);
- ObjectDefineProperty(this, "reactive", { value: proxy });
- return proxy;
- },
- get readOnly() {
- const readOnlyHandler = new ReadOnlyHandler(membrane, distortedValue);
- const proxy = new Proxy(createShadowTarget(distortedValue), readOnlyHandler);
- registerProxy(proxy, value);
- ObjectDefineProperty(this, "readOnly", { value: proxy });
- return proxy;
- }
- };
- objectGraph.set(distortedValue, reactiveState);
- return reactiveState;
- }
- }
- function wrap(data, mutationCallback) {
- let membrane = new ReactiveMembrane({
- valueMutated(target, key) {
- mutationCallback(target, key);
- }
- });
- return {
- data: membrane.getProxy(data),
- membrane
- };
- }
- function unwrap$1(membrane, observable) {
- let unwrappedData = membrane.unwrapProxy(observable);
- let copy = {};
- Object.keys(unwrappedData).forEach((key) => {
- if (["$el", "$refs", "$nextTick", "$watch"].includes(key))
- return;
- copy[key] = unwrappedData[key];
- });
- return copy;
- }
- class Component {
- constructor(el, componentForClone = null) {
- this.$el = el;
- const dataAttr = this.$el.getAttribute("x-data");
- const dataExpression = dataAttr === "" ? "{}" : dataAttr;
- const initExpression = this.$el.getAttribute("x-init");
- let dataExtras = {
- $el: this.$el
- };
- let canonicalComponentElementReference = componentForClone ? componentForClone.$el : this.$el;
- Object.entries(Alpine3.magicProperties).forEach(([name, callback]) => {
- Object.defineProperty(dataExtras, `$${name}`, {
- get: function get() {
- return callback(canonicalComponentElementReference);
- }
- });
- });
- this.unobservedData = componentForClone ? componentForClone.getUnobservedData() : saferEval(el, dataExpression, dataExtras);
- let {
- membrane,
- data
- } = this.wrapDataInObservable(this.unobservedData);
- this.$data = data;
- this.membrane = membrane;
- this.unobservedData.$el = this.$el;
- this.unobservedData.$refs = this.getRefsProxy();
- this.nextTickStack = [];
- this.unobservedData.$nextTick = (callback) => {
- this.nextTickStack.push(callback);
- };
- this.watchers = {};
- this.unobservedData.$watch = (property, callback) => {
- if (!this.watchers[property])
- this.watchers[property] = [];
- this.watchers[property].push(callback);
- };
- Object.entries(Alpine3.magicProperties).forEach(([name, callback]) => {
- Object.defineProperty(this.unobservedData, `$${name}`, {
- get: function get() {
- return callback(canonicalComponentElementReference, this.$el);
- }
- });
- });
- this.showDirectiveStack = [];
- this.showDirectiveLastElement;
- componentForClone || Alpine3.onBeforeComponentInitializeds.forEach((callback) => callback(this));
- var initReturnedCallback;
- if (initExpression && !componentForClone) {
- this.pauseReactivity = true;
- initReturnedCallback = this.evaluateReturnExpression(this.$el, initExpression);
- this.pauseReactivity = false;
- }
- this.initializeElements(this.$el, () => {
- }, componentForClone);
- this.listenForNewElementsToInitialize();
- if (typeof initReturnedCallback === "function") {
- initReturnedCallback.call(this.$data);
- }
- componentForClone || setTimeout(() => {
- Alpine3.onComponentInitializeds.forEach((callback) => callback(this));
- }, 0);
- }
- getUnobservedData() {
- return unwrap$1(this.membrane, this.$data);
- }
- wrapDataInObservable(data) {
- var self2 = this;
- let updateDom = debounce(function() {
- self2.updateElements(self2.$el);
- }, 0);
- return wrap(data, (target, key) => {
- if (self2.watchers[key]) {
- self2.watchers[key].forEach((callback) => callback(target[key]));
- } else if (Array.isArray(target)) {
- Object.keys(self2.watchers).forEach((fullDotNotationKey) => {
- let dotNotationParts = fullDotNotationKey.split(".");
- if (key === "length")
- return;
- dotNotationParts.reduce((comparisonData, part) => {
- if (Object.is(target, comparisonData[part])) {
- self2.watchers[fullDotNotationKey].forEach((callback) => callback(target));
- }
- return comparisonData[part];
- }, self2.unobservedData);
- });
- } else {
- Object.keys(self2.watchers).filter((i2) => i2.includes(".")).forEach((fullDotNotationKey) => {
- let dotNotationParts = fullDotNotationKey.split(".");
- if (key !== dotNotationParts[dotNotationParts.length - 1])
- return;
- dotNotationParts.reduce((comparisonData, part) => {
- if (Object.is(target, comparisonData)) {
- self2.watchers[fullDotNotationKey].forEach((callback) => callback(target[key]));
- }
- return comparisonData[part];
- }, self2.unobservedData);
- });
- }
- if (self2.pauseReactivity)
- return;
- updateDom();
- });
- }
- walkAndSkipNestedComponents(el, callback, initializeComponentCallback = () => {
- }) {
- walk(el, (el2) => {
- if (el2.hasAttribute("x-data")) {
- if (!el2.isSameNode(this.$el)) {
- if (!el2.__x)
- initializeComponentCallback(el2);
- return false;
- }
- }
- return callback(el2);
- });
- }
- initializeElements(rootEl, extraVars = () => {
- }, componentForClone = false) {
- this.walkAndSkipNestedComponents(rootEl, (el) => {
- if (el.__x_for_key !== void 0)
- return false;
- if (el.__x_inserted_me !== void 0)
- return false;
- this.initializeElement(el, extraVars, componentForClone ? false : true);
- }, (el) => {
- if (!componentForClone)
- el.__x = new Component(el);
- });
- this.executeAndClearRemainingShowDirectiveStack();
- this.executeAndClearNextTickStack(rootEl);
- }
- initializeElement(el, extraVars, shouldRegisterListeners = true) {
- if (el.hasAttribute("class") && getXAttrs(el, this).length > 0) {
- el.__x_original_classes = convertClassStringToArray(el.getAttribute("class"));
- }
- shouldRegisterListeners && this.registerListeners(el, extraVars);
- this.resolveBoundAttributes(el, true, extraVars);
- }
- updateElements(rootEl, extraVars = () => {
- }) {
- this.walkAndSkipNestedComponents(rootEl, (el) => {
- if (el.__x_for_key !== void 0 && !el.isSameNode(this.$el))
- return false;
- this.updateElement(el, extraVars);
- }, (el) => {
- el.__x = new Component(el);
- });
- this.executeAndClearRemainingShowDirectiveStack();
- this.executeAndClearNextTickStack(rootEl);
- }
- executeAndClearNextTickStack(el) {
- if (el === this.$el && this.nextTickStack.length > 0) {
- requestAnimationFrame(() => {
- while (this.nextTickStack.length > 0) {
- this.nextTickStack.shift()();
- }
- });
- }
- }
- executeAndClearRemainingShowDirectiveStack() {
- this.showDirectiveStack.reverse().map((handler) => {
- return new Promise((resolve, reject) => {
- handler(resolve, reject);
- });
- }).reduce((promiseChain, promise) => {
- return promiseChain.then(() => {
- return promise.then((finishElement) => {
- finishElement();
- });
- });
- }, Promise.resolve(() => {
- })).catch((e2) => {
- if (e2 !== TRANSITION_CANCELLED)
- throw e2;
- });
- this.showDirectiveStack = [];
- this.showDirectiveLastElement = void 0;
- }
- updateElement(el, extraVars) {
- this.resolveBoundAttributes(el, false, extraVars);
- }
- registerListeners(el, extraVars) {
- getXAttrs(el, this).forEach(({
- type,
- value,
- modifiers,
- expression
- }) => {
- switch (type) {
- case "on":
- registerListener(this, el, value, modifiers, expression, extraVars);
- break;
- case "model":
- registerModelListener(this, el, modifiers, expression, extraVars);
- break;
- }
- });
- }
- resolveBoundAttributes(el, initialUpdate = false, extraVars) {
- let attrs = getXAttrs(el, this);
- attrs.forEach(({
- type,
- value,
- modifiers,
- expression
- }) => {
- switch (type) {
- case "model":
- handleAttributeBindingDirective(this, el, "value", expression, extraVars, type, modifiers);
- break;
- case "bind":
- if (el.tagName.toLowerCase() === "template" && value === "key")
- return;
- handleAttributeBindingDirective(this, el, value, expression, extraVars, type, modifiers);
- break;
- case "text":
- var output = this.evaluateReturnExpression(el, expression, extraVars);
- handleTextDirective(el, output, expression);
- break;
- case "html":
- handleHtmlDirective(this, el, expression, extraVars);
- break;
- case "show":
- var output = this.evaluateReturnExpression(el, expression, extraVars);
- handleShowDirective(this, el, output, modifiers, initialUpdate);
- break;
- case "if":
- if (attrs.some((i2) => i2.type === "for"))
- return;
- var output = this.evaluateReturnExpression(el, expression, extraVars);
- handleIfDirective(this, el, output, initialUpdate, extraVars);
- break;
- case "for":
- handleForDirective(this, el, expression, initialUpdate, extraVars);
- break;
- case "cloak":
- el.removeAttribute("x-cloak");
- break;
- }
- });
- }
- evaluateReturnExpression(el, expression, extraVars = () => {
- }) {
- return saferEval(el, expression, this.$data, _objectSpread2(_objectSpread2({}, extraVars()), {}, {
- $dispatch: this.getDispatchFunction(el)
- }));
- }
- evaluateCommandExpression(el, expression, extraVars = () => {
- }) {
- return saferEvalNoReturn(el, expression, this.$data, _objectSpread2(_objectSpread2({}, extraVars()), {}, {
- $dispatch: this.getDispatchFunction(el)
- }));
- }
- getDispatchFunction(el) {
- return (event, detail = {}) => {
- el.dispatchEvent(new CustomEvent(event, {
- detail,
- bubbles: true
- }));
- };
- }
- listenForNewElementsToInitialize() {
- const targetNode = this.$el;
- const observerOptions = {
- childList: true,
- attributes: true,
- subtree: true
- };
- const observer = new MutationObserver((mutations) => {
- for (let i2 = 0; i2 < mutations.length; i2++) {
- const closestParentComponent = mutations[i2].target.closest("[x-data]");
- if (!(closestParentComponent && closestParentComponent.isSameNode(this.$el)))
- continue;
- if (mutations[i2].type === "attributes" && mutations[i2].attributeName === "x-data") {
- const xAttr = mutations[i2].target.getAttribute("x-data") || "{}";
- const rawData = saferEval(this.$el, xAttr, {
- $el: this.$el
- });
- Object.keys(rawData).forEach((key) => {
- if (this.$data[key] !== rawData[key]) {
- this.$data[key] = rawData[key];
- }
- });
- }
- if (mutations[i2].addedNodes.length > 0) {
- mutations[i2].addedNodes.forEach((node) => {
- if (node.nodeType !== 1 || node.__x_inserted_me)
- return;
- if (node.matches("[x-data]") && !node.__x) {
- node.__x = new Component(node);
- return;
- }
- this.initializeElements(node);
- });
- }
- }
- });
- observer.observe(targetNode, observerOptions);
- }
- getRefsProxy() {
- var self2 = this;
- var refObj = {};
- return new Proxy(refObj, {
- get(object, property) {
- if (property === "$isAlpineProxy")
- return true;
- var ref;
- self2.walkAndSkipNestedComponents(self2.$el, (el) => {
- if (el.hasAttribute("x-ref") && el.getAttribute("x-ref") === property) {
- ref = el;
- }
- });
- return ref;
- }
- });
- }
- }
- const Alpine3 = {
- version: "2.8.2",
- pauseMutationObserver: false,
- magicProperties: {},
- onComponentInitializeds: [],
- onBeforeComponentInitializeds: [],
- ignoreFocusedForValueBinding: false,
- start: async function start() {
- if (!isTesting()) {
- await domReady();
- }
- this.discoverComponents((el) => {
- this.initializeComponent(el);
- });
- document.addEventListener("turbolinks:load", () => {
- this.discoverUninitializedComponents((el) => {
- this.initializeComponent(el);
- });
- });
- this.listenForNewUninitializedComponentsAtRunTime();
- },
- discoverComponents: function discoverComponents(callback) {
- const rootEls = document.querySelectorAll("[x-data]");
- rootEls.forEach((rootEl) => {
- callback(rootEl);
- });
- },
- discoverUninitializedComponents: function discoverUninitializedComponents(callback, el = null) {
- const rootEls = (el || document).querySelectorAll("[x-data]");
- Array.from(rootEls).filter((el2) => el2.__x === void 0).forEach((rootEl) => {
- callback(rootEl);
- });
- },
- listenForNewUninitializedComponentsAtRunTime: function listenForNewUninitializedComponentsAtRunTime() {
- const targetNode = document.querySelector("body");
- const observerOptions = {
- childList: true,
- attributes: true,
- subtree: true
- };
- const observer = new MutationObserver((mutations) => {
- if (this.pauseMutationObserver)
- return;
- for (let i2 = 0; i2 < mutations.length; i2++) {
- if (mutations[i2].addedNodes.length > 0) {
- mutations[i2].addedNodes.forEach((node) => {
- if (node.nodeType !== 1)
- return;
- if (node.parentElement && node.parentElement.closest("[x-data]"))
- return;
- this.discoverUninitializedComponents((el) => {
- this.initializeComponent(el);
- }, node.parentElement);
- });
- }
- }
- });
- observer.observe(targetNode, observerOptions);
- },
- initializeComponent: function initializeComponent(el) {
- if (!el.__x) {
- try {
- el.__x = new Component(el);
- } catch (error) {
- setTimeout(() => {
- throw error;
- }, 0);
- }
- }
- },
- clone: function clone2(component, newEl) {
- if (!newEl.__x) {
- newEl.__x = new Component(newEl, component);
- }
- },
- addMagicProperty: function addMagicProperty(name, callback) {
- this.magicProperties[name] = callback;
- },
- onComponentInitialized: function onComponentInitialized(callback) {
- this.onComponentInitializeds.push(callback);
- },
- onBeforeComponentInitialized: function onBeforeComponentInitialized(callback) {
- this.onBeforeComponentInitializeds.push(callback);
- }
- };
- if (!isTesting()) {
- window.Alpine = Alpine3;
- if (window.deferLoadingAlpine) {
- window.deferLoadingAlpine(function() {
- window.Alpine.start();
- });
- } else {
- window.Alpine.start();
- }
- }
- return Alpine3;
- });
- }
- });
-
- // js/pdf_viewer.js
- var import_lodash = __toESM(require_lodash());
- var pdfjsVersion = "3.11.174";
- var pdfjs = require_pdf();
- var worker2 = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsVersion}/pdf.worker.min.js`;
- function renderPages(hook) {
- hook.renderPagesIfNeed();
- }
- var PDFViewer = {
- mounted() {
- console.log("[PDFViewer] Mounted: state", this.el.dataset.state);
- this.src = this.el.dataset.src;
- this.loadDocument().then((pdf) => {
- this.pdf = pdf;
- console.log("[PDFViewer] Document loaded, push event 'tool_initialized'");
- this.pushEvent("tool_initialized");
- this.renderPagesIfNeed();
- var throttledRenderPages = import_lodash.default.throttle(import_lodash.default.partial(renderPages, this), 10, {
- trailing: true
- });
- window.addEventListener("resize", throttledRenderPages);
- });
- },
- updated() {
- console.log("[PDFViewer] Updated: state", this.el.dataset.state);
- this.renderPagesIfNeed();
- },
- loadDocument() {
- pdfjs.GlobalWorkerOptions.workerSrc = worker2;
- const loadingTask = pdfjs.getDocument({ url: this.src });
- return loadingTask.promise;
- },
- renderPagesIfNeed() {
- if (this.el.dataset.state == "visible") {
- this.renderPages();
- }
- },
- renderPages() {
- console.log("[PDFViewer] Render pages");
- this.createContainer();
- const width = this.el.getBoundingClientRect().width;
- this.renderPage(width, 1);
- },
- renderPage(width, pageNum) {
- console.log("[PDFViewer] Render page", pageNum);
- this.pdf.getPage(pageNum).then(
- async (page) => {
- var scale = window.devicePixelRatio;
- var viewport = page.getViewport({ scale });
- if (width < viewport.width) {
- scale = width / viewport.width * scale;
- }
- viewport = page.getViewport({ scale });
- const canvas = this.createCanvas(viewport);
- const context = canvas.getContext("2d");
- page.render({ canvasContext: context, viewport });
- const annotations = await page.getAnnotations();
- function translateEventCoordinatesToPdfViewport(canvas2, x2, y2) {
- const rect = canvas2.getBoundingClientRect();
- const newx = (x2 - rect.left) / scale;
- const newy = -1 * (y2 - rect.bottom) / scale;
- return { x: newx, y: newy };
- }
- canvas.addEventListener("click", (event) => {
- const { x: x2, y: y2 } = translateEventCoordinatesToPdfViewport(canvas, event.clientX, event.clientY);
- for (let annotation of annotations) {
- const rect = annotation.rect;
- if (x2 > rect[0] && x2 < rect[2] && y2 > rect[1] && y2 < rect[3]) {
- if (annotation.url) {
- window.open(annotation.url, "_blank");
- }
- }
- }
- });
- canvas.addEventListener("mousemove", (event) => {
- const { x: x2, y: y2 } = translateEventCoordinatesToPdfViewport(canvas, event.clientX, event.clientY);
- for (let annotation of annotations) {
- const rect = annotation.rect;
- if (x2 > rect[0] && x2 < rect[2] && y2 > rect[1] && y2 < rect[3]) {
- canvas.style.cursor = "pointer";
- break;
- } else {
- canvas.style.cursor = "default";
- }
- }
- });
- this.renderPage(width, pageNum + 1);
- },
- () => {
- console.log("[PDFViewer] end of document");
- }
- );
- },
- createContainer() {
- if (this.container != void 0) {
- this.container.remove();
- this.container = void 0;
- }
- this.container = document.createElement("div");
- this.container.style.display = "block";
- this.el.appendChild(this.container);
- },
- createCanvas(viewport) {
- var canvas = document.createElement("canvas");
- canvas.style.display = "block";
- canvas.height = viewport.height;
- canvas.width = viewport.width;
- this.container.appendChild(canvas);
- return canvas;
- }
- };
-
- // js/app.js
- var import_component = __toESM(require_component());
- var import_alpinejs = __toESM(require_alpine());
-
- // ../deps/phoenix_html/priv/static/phoenix_html.js
- (function() {
- var PolyfillEvent = eventConstructor();
- function eventConstructor() {
- if (typeof window.CustomEvent === "function")
- return window.CustomEvent;
- function CustomEvent2(event, params) {
- params = params || { bubbles: false, cancelable: false, detail: void 0 };
- var evt = document.createEvent("CustomEvent");
- evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
- return evt;
- }
- CustomEvent2.prototype = window.Event.prototype;
- return CustomEvent2;
- }
- function buildHiddenInput(name, value) {
- var input = document.createElement("input");
- input.type = "hidden";
- input.name = name;
- input.value = value;
- return input;
- }
- function handleClick(element, targetModifierKey) {
- var to = element.getAttribute("data-to"), method = buildHiddenInput("_method", element.getAttribute("data-method")), csrf = buildHiddenInput("_csrf_token", element.getAttribute("data-csrf")), form = document.createElement("form"), submit = document.createElement("input"), target = element.getAttribute("target");
- form.method = element.getAttribute("data-method") === "get" ? "get" : "post";
- form.action = to;
- form.style.display = "none";
- if (target)
- form.target = target;
- else if (targetModifierKey)
- form.target = "_blank";
- form.appendChild(csrf);
- form.appendChild(method);
- document.body.appendChild(form);
- submit.type = "submit";
- form.appendChild(submit);
- submit.click();
- }
- window.addEventListener("click", function(e2) {
- var element = e2.target;
- if (e2.defaultPrevented)
- return;
- while (element && element.getAttribute) {
- var phoenixLinkEvent = new PolyfillEvent("phoenix.link.click", {
- "bubbles": true,
- "cancelable": true
- });
- if (!element.dispatchEvent(phoenixLinkEvent)) {
- e2.preventDefault();
- e2.stopImmediatePropagation();
- return false;
- }
- if (element.getAttribute("data-method")) {
- handleClick(element, e2.metaKey || e2.shiftKey);
- e2.preventDefault();
- return false;
- } else {
- element = element.parentNode;
- }
- }
- }, false);
- window.addEventListener("phoenix.link.click", function(e2) {
- var message = e2.target.getAttribute("data-confirm");
- if (message && !window.confirm(message)) {
- e2.preventDefault();
- }
- }, false);
- })();
-
- // ../deps/phoenix/priv/static/phoenix.mjs
- var closure = (value) => {
- if (typeof value === "function") {
- return value;
- } else {
- let closure22 = function() {
- return value;
- };
- return closure22;
- }
- };
- var globalSelf = typeof self !== "undefined" ? self : null;
- var phxWindow = typeof window !== "undefined" ? window : null;
- var global2 = globalSelf || phxWindow || global2;
- var DEFAULT_VSN = "2.0.0";
- var SOCKET_STATES = { connecting: 0, open: 1, closing: 2, closed: 3 };
- var DEFAULT_TIMEOUT = 1e4;
- var WS_CLOSE_NORMAL = 1e3;
- var CHANNEL_STATES = {
- closed: "closed",
- errored: "errored",
- joined: "joined",
- joining: "joining",
- leaving: "leaving"
- };
- var CHANNEL_EVENTS = {
- close: "phx_close",
- error: "phx_error",
- join: "phx_join",
- reply: "phx_reply",
- leave: "phx_leave"
- };
- var TRANSPORTS = {
- longpoll: "longpoll",
- websocket: "websocket"
- };
- var XHR_STATES = {
- complete: 4
- };
- var Push = class {
- constructor(channel, event, payload, timeout) {
- this.channel = channel;
- this.event = event;
- this.payload = payload || function() {
- return {};
- };
- this.receivedResp = null;
- this.timeout = timeout;
- this.timeoutTimer = null;
- this.recHooks = [];
- this.sent = false;
- }
- resend(timeout) {
- this.timeout = timeout;
- this.reset();
- this.send();
- }
- send() {
- if (this.hasReceived("timeout")) {
- return;
- }
- this.startTimeout();
- this.sent = true;
- this.channel.socket.push({
- topic: this.channel.topic,
- event: this.event,
- payload: this.payload(),
- ref: this.ref,
- join_ref: this.channel.joinRef()
- });
- }
- receive(status, callback) {
- if (this.hasReceived(status)) {
- callback(this.receivedResp.response);
- }
- this.recHooks.push({ status, callback });
- return this;
- }
- reset() {
- this.cancelRefEvent();
- this.ref = null;
- this.refEvent = null;
- this.receivedResp = null;
- this.sent = false;
- }
- matchReceive({ status, response, _ref }) {
- this.recHooks.filter((h2) => h2.status === status).forEach((h2) => h2.callback(response));
- }
- cancelRefEvent() {
- if (!this.refEvent) {
- return;
- }
- this.channel.off(this.refEvent);
- }
- cancelTimeout() {
- clearTimeout(this.timeoutTimer);
- this.timeoutTimer = null;
- }
- startTimeout() {
- if (this.timeoutTimer) {
- this.cancelTimeout();
- }
- this.ref = this.channel.socket.makeRef();
- this.refEvent = this.channel.replyEventName(this.ref);
- this.channel.on(this.refEvent, (payload) => {
- this.cancelRefEvent();
- this.cancelTimeout();
- this.receivedResp = payload;
- this.matchReceive(payload);
- });
- this.timeoutTimer = setTimeout(() => {
- this.trigger("timeout", {});
- }, this.timeout);
- }
- hasReceived(status) {
- return this.receivedResp && this.receivedResp.status === status;
- }
- trigger(status, response) {
- this.channel.trigger(this.refEvent, { status, response });
- }
- };
- var Timer = class {
- constructor(callback, timerCalc) {
- this.callback = callback;
- this.timerCalc = timerCalc;
- this.timer = null;
- this.tries = 0;
- }
- reset() {
- this.tries = 0;
- clearTimeout(this.timer);
- }
- scheduleTimeout() {
- clearTimeout(this.timer);
- this.timer = setTimeout(() => {
- this.tries = this.tries + 1;
- this.callback();
- }, this.timerCalc(this.tries + 1));
- }
- };
- var Channel = class {
- constructor(topic, params, socket) {
- this.state = CHANNEL_STATES.closed;
- this.topic = topic;
- this.params = closure(params || {});
- this.socket = socket;
- this.bindings = [];
- this.bindingRef = 0;
- this.timeout = this.socket.timeout;
- this.joinedOnce = false;
- this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);
- this.pushBuffer = [];
- this.stateChangeRefs = [];
- this.rejoinTimer = new Timer(() => {
- if (this.socket.isConnected()) {
- this.rejoin();
- }
- }, this.socket.rejoinAfterMs);
- this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset()));
- this.stateChangeRefs.push(this.socket.onOpen(() => {
- this.rejoinTimer.reset();
- if (this.isErrored()) {
- this.rejoin();
- }
- }));
- this.joinPush.receive("ok", () => {
- this.state = CHANNEL_STATES.joined;
- this.rejoinTimer.reset();
- this.pushBuffer.forEach((pushEvent) => pushEvent.send());
- this.pushBuffer = [];
- });
- this.joinPush.receive("error", () => {
- this.state = CHANNEL_STATES.errored;
- if (this.socket.isConnected()) {
- this.rejoinTimer.scheduleTimeout();
- }
- });
- this.onClose(() => {
- this.rejoinTimer.reset();
- if (this.socket.hasLogger())
- this.socket.log("channel", `close ${this.topic} ${this.joinRef()}`);
- this.state = CHANNEL_STATES.closed;
- this.socket.remove(this);
- });
- this.onError((reason) => {
- if (this.socket.hasLogger())
- this.socket.log("channel", `error ${this.topic}`, reason);
- if (this.isJoining()) {
- this.joinPush.reset();
- }
- this.state = CHANNEL_STATES.errored;
- if (this.socket.isConnected()) {
- this.rejoinTimer.scheduleTimeout();
- }
- });
- this.joinPush.receive("timeout", () => {
- if (this.socket.hasLogger())
- this.socket.log("channel", `timeout ${this.topic} (${this.joinRef()})`, this.joinPush.timeout);
- let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout);
- leavePush.send();
- this.state = CHANNEL_STATES.errored;
- this.joinPush.reset();
- if (this.socket.isConnected()) {
- this.rejoinTimer.scheduleTimeout();
- }
- });
- this.on(CHANNEL_EVENTS.reply, (payload, ref) => {
- this.trigger(this.replyEventName(ref), payload);
- });
- }
- join(timeout = this.timeout) {
- if (this.joinedOnce) {
- throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");
- } else {
- this.timeout = timeout;
- this.joinedOnce = true;
- this.rejoin();
- return this.joinPush;
- }
- }
- onClose(callback) {
- this.on(CHANNEL_EVENTS.close, callback);
- }
- onError(callback) {
- return this.on(CHANNEL_EVENTS.error, (reason) => callback(reason));
- }
- on(event, callback) {
- let ref = this.bindingRef++;
- this.bindings.push({ event, ref, callback });
- return ref;
- }
- off(event, ref) {
- this.bindings = this.bindings.filter((bind) => {
- return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref));
- });
- }
- canPush() {
- return this.socket.isConnected() && this.isJoined();
- }
- push(event, payload, timeout = this.timeout) {
- payload = payload || {};
- if (!this.joinedOnce) {
- throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`);
- }
- let pushEvent = new Push(this, event, function() {
- return payload;
- }, timeout);
- if (this.canPush()) {
- pushEvent.send();
- } else {
- pushEvent.startTimeout();
- this.pushBuffer.push(pushEvent);
- }
- return pushEvent;
- }
- leave(timeout = this.timeout) {
- this.rejoinTimer.reset();
- this.joinPush.cancelTimeout();
- this.state = CHANNEL_STATES.leaving;
- let onClose = () => {
- if (this.socket.hasLogger())
- this.socket.log("channel", `leave ${this.topic}`);
- this.trigger(CHANNEL_EVENTS.close, "leave");
- };
- let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout);
- leavePush.receive("ok", () => onClose()).receive("timeout", () => onClose());
- leavePush.send();
- if (!this.canPush()) {
- leavePush.trigger("ok", {});
- }
- return leavePush;
- }
- onMessage(_event, payload, _ref) {
- return payload;
- }
- isMember(topic, event, payload, joinRef) {
- if (this.topic !== topic) {
- return false;
- }
- if (joinRef && joinRef !== this.joinRef()) {
- if (this.socket.hasLogger())
- this.socket.log("channel", "dropping outdated message", { topic, event, payload, joinRef });
- return false;
- } else {
- return true;
- }
- }
- joinRef() {
- return this.joinPush.ref;
- }
- rejoin(timeout = this.timeout) {
- if (this.isLeaving()) {
- return;
- }
- this.socket.leaveOpenTopic(this.topic);
- this.state = CHANNEL_STATES.joining;
- this.joinPush.resend(timeout);
- }
- trigger(event, payload, ref, joinRef) {
- let handledPayload = this.onMessage(event, payload, ref, joinRef);
- if (payload && !handledPayload) {
- throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");
- }
- let eventBindings = this.bindings.filter((bind) => bind.event === event);
- for (let i2 = 0; i2 < eventBindings.length; i2++) {
- let bind = eventBindings[i2];
- bind.callback(handledPayload, ref, joinRef || this.joinRef());
- }
- }
- replyEventName(ref) {
- return `chan_reply_${ref}`;
- }
- isClosed() {
- return this.state === CHANNEL_STATES.closed;
- }
- isErrored() {
- return this.state === CHANNEL_STATES.errored;
- }
- isJoined() {
- return this.state === CHANNEL_STATES.joined;
- }
- isJoining() {
- return this.state === CHANNEL_STATES.joining;
- }
- isLeaving() {
- return this.state === CHANNEL_STATES.leaving;
- }
- };
- var Ajax = class {
- static request(method, endPoint, accept, body, timeout, ontimeout, callback) {
- if (global2.XDomainRequest) {
- let req = new global2.XDomainRequest();
- return this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback);
- } else {
- let req = new global2.XMLHttpRequest();
- return this.xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback);
- }
- }
- static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) {
- req.timeout = timeout;
- req.open(method, endPoint);
- req.onload = () => {
- let response = this.parseJSON(req.responseText);
- callback && callback(response);
- };
- if (ontimeout) {
- req.ontimeout = ontimeout;
- }
- req.onprogress = () => {
- };
- req.send(body);
- return req;
- }
- static xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback) {
- req.open(method, endPoint, true);
- req.timeout = timeout;
- req.setRequestHeader("Content-Type", accept);
- req.onerror = () => callback && callback(null);
- req.onreadystatechange = () => {
- if (req.readyState === XHR_STATES.complete && callback) {
- let response = this.parseJSON(req.responseText);
- callback(response);
- }
- };
- if (ontimeout) {
- req.ontimeout = ontimeout;
- }
- req.send(body);
- return req;
- }
- static parseJSON(resp) {
- if (!resp || resp === "") {
- return null;
- }
- try {
- return JSON.parse(resp);
- } catch (e2) {
- console && console.log("failed to parse JSON response", resp);
- return null;
- }
- }
- static serialize(obj, parentKey) {
- let queryStr = [];
- for (var key in obj) {
- if (!Object.prototype.hasOwnProperty.call(obj, key)) {
- continue;
- }
- let paramKey = parentKey ? `${parentKey}[${key}]` : key;
- let paramVal = obj[key];
- if (typeof paramVal === "object") {
- queryStr.push(this.serialize(paramVal, paramKey));
- } else {
- queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal));
- }
- }
- return queryStr.join("&");
- }
- static appendParams(url, params) {
- if (Object.keys(params).length === 0) {
- return url;
- }
- let prefix = url.match(/\?/) ? "&" : "?";
- return `${url}${prefix}${this.serialize(params)}`;
- }
- };
- var LongPoll = class {
- constructor(endPoint) {
- this.endPoint = null;
- this.token = null;
- this.skipHeartbeat = true;
- this.reqs = /* @__PURE__ */ new Set();
- this.awaitingBatchAck = false;
- this.currentBatch = null;
- this.currentBatchTimer = null;
- this.batchBuffer = [];
- this.onopen = function() {
- };
- this.onerror = function() {
- };
- this.onmessage = function() {
- };
- this.onclose = function() {
- };
- this.pollEndpoint = this.normalizeEndpoint(endPoint);
- this.readyState = SOCKET_STATES.connecting;
- this.poll();
- }
- normalizeEndpoint(endPoint) {
- return endPoint.replace("ws://", "http://").replace("wss://", "https://").replace(new RegExp("(.*)/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll);
- }
- endpointURL() {
- return Ajax.appendParams(this.pollEndpoint, { token: this.token });
- }
- closeAndRetry(code, reason, wasClean) {
- this.close(code, reason, wasClean);
- this.readyState = SOCKET_STATES.connecting;
- }
- ontimeout() {
- this.onerror("timeout");
- this.closeAndRetry(1005, "timeout", false);
- }
- isActive() {
- return this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting;
- }
- poll() {
- this.ajax("GET", "application/json", null, () => this.ontimeout(), (resp) => {
- if (resp) {
- var { status, token, messages } = resp;
- this.token = token;
- } else {
- status = 0;
- }
- switch (status) {
- case 200:
- messages.forEach((msg) => {
- setTimeout(() => this.onmessage({ data: msg }), 0);
- });
- this.poll();
- break;
- case 204:
- this.poll();
- break;
- case 410:
- this.readyState = SOCKET_STATES.open;
- this.onopen({});
- this.poll();
- break;
- case 403:
- this.onerror(403);
- this.close(1008, "forbidden", false);
- break;
- case 0:
- case 500:
- this.onerror(500);
- this.closeAndRetry(1011, "internal server error", 500);
- break;
- default:
- throw new Error(`unhandled poll status ${status}`);
- }
- });
- }
- send(body) {
- if (this.currentBatch) {
- this.currentBatch.push(body);
- } else if (this.awaitingBatchAck) {
- this.batchBuffer.push(body);
- } else {
- this.currentBatch = [body];
- this.currentBatchTimer = setTimeout(() => {
- this.batchSend(this.currentBatch);
- this.currentBatch = null;
- }, 0);
- }
- }
- batchSend(messages) {
- this.awaitingBatchAck = true;
- this.ajax("POST", "application/x-ndjson", messages.join("\n"), () => this.onerror("timeout"), (resp) => {
- this.awaitingBatchAck = false;
- if (!resp || resp.status !== 200) {
- this.onerror(resp && resp.status);
- this.closeAndRetry(1011, "internal server error", false);
- } else if (this.batchBuffer.length > 0) {
- this.batchSend(this.batchBuffer);
- this.batchBuffer = [];
- }
- });
- }
- close(code, reason, wasClean) {
- for (let req of this.reqs) {
- req.abort();
- }
- this.readyState = SOCKET_STATES.closed;
- let opts = Object.assign({ code: 1e3, reason: void 0, wasClean: true }, { code, reason, wasClean });
- this.batchBuffer = [];
- clearTimeout(this.currentBatchTimer);
- this.currentBatchTimer = null;
- if (typeof CloseEvent !== "undefined") {
- this.onclose(new CloseEvent("close", opts));
- } else {
- this.onclose(opts);
- }
- }
- ajax(method, contentType, body, onCallerTimeout, callback) {
- let req;
- let ontimeout = () => {
- this.reqs.delete(req);
- onCallerTimeout();
- };
- req = Ajax.request(method, this.endpointURL(), contentType, body, this.timeout, ontimeout, (resp) => {
- this.reqs.delete(req);
- if (this.isActive()) {
- callback(resp);
- }
- });
- this.reqs.add(req);
- }
- };
- var serializer_default = {
- HEADER_LENGTH: 1,
- META_LENGTH: 4,
- KINDS: { push: 0, reply: 1, broadcast: 2 },
- encode(msg, callback) {
- if (msg.payload.constructor === ArrayBuffer) {
- return callback(this.binaryEncode(msg));
- } else {
- let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];
- return callback(JSON.stringify(payload));
- }
- },
- decode(rawPayload, callback) {
- if (rawPayload.constructor === ArrayBuffer) {
- return callback(this.binaryDecode(rawPayload));
- } else {
- let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload);
- return callback({ join_ref, ref, topic, event, payload });
- }
- },
- binaryEncode(message) {
- let { join_ref, ref, event, topic, payload } = message;
- let metaLength = this.META_LENGTH + join_ref.length + ref.length + topic.length + event.length;
- let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
- let view = new DataView(header);
- let offset = 0;
- view.setUint8(offset++, this.KINDS.push);
- view.setUint8(offset++, join_ref.length);
- view.setUint8(offset++, ref.length);
- view.setUint8(offset++, topic.length);
- view.setUint8(offset++, event.length);
- Array.from(join_ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
- Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
- Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)));
- Array.from(event, (char) => view.setUint8(offset++, char.charCodeAt(0)));
- var combined = new Uint8Array(header.byteLength + payload.byteLength);
- combined.set(new Uint8Array(header), 0);
- combined.set(new Uint8Array(payload), header.byteLength);
- return combined.buffer;
- },
- binaryDecode(buffer) {
- let view = new DataView(buffer);
- let kind = view.getUint8(0);
- let decoder = new TextDecoder();
- switch (kind) {
- case this.KINDS.push:
- return this.decodePush(buffer, view, decoder);
- case this.KINDS.reply:
- return this.decodeReply(buffer, view, decoder);
- case this.KINDS.broadcast:
- return this.decodeBroadcast(buffer, view, decoder);
- }
- },
- decodePush(buffer, view, decoder) {
- let joinRefSize = view.getUint8(1);
- let topicSize = view.getUint8(2);
- let eventSize = view.getUint8(3);
- let offset = this.HEADER_LENGTH + this.META_LENGTH - 1;
- let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
- offset = offset + joinRefSize;
- let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
- offset = offset + topicSize;
- let event = decoder.decode(buffer.slice(offset, offset + eventSize));
- offset = offset + eventSize;
- let data = buffer.slice(offset, buffer.byteLength);
- return { join_ref: joinRef, ref: null, topic, event, payload: data };
- },
- decodeReply(buffer, view, decoder) {
- let joinRefSize = view.getUint8(1);
- let refSize = view.getUint8(2);
- let topicSize = view.getUint8(3);
- let eventSize = view.getUint8(4);
- let offset = this.HEADER_LENGTH + this.META_LENGTH;
- let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
- offset = offset + joinRefSize;
- let ref = decoder.decode(buffer.slice(offset, offset + refSize));
- offset = offset + refSize;
- let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
- offset = offset + topicSize;
- let event = decoder.decode(buffer.slice(offset, offset + eventSize));
- offset = offset + eventSize;
- let data = buffer.slice(offset, buffer.byteLength);
- let payload = { status: event, response: data };
- return { join_ref: joinRef, ref, topic, event: CHANNEL_EVENTS.reply, payload };
- },
- decodeBroadcast(buffer, view, decoder) {
- let topicSize = view.getUint8(1);
- let eventSize = view.getUint8(2);
- let offset = this.HEADER_LENGTH + 2;
- let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
- offset = offset + topicSize;
- let event = decoder.decode(buffer.slice(offset, offset + eventSize));
- offset = offset + eventSize;
- let data = buffer.slice(offset, buffer.byteLength);
- return { join_ref: null, ref: null, topic, event, payload: data };
- }
- };
- var Socket = class {
- constructor(endPoint, opts = {}) {
- this.stateChangeCallbacks = { open: [], close: [], error: [], message: [] };
- this.channels = [];
- this.sendBuffer = [];
- this.ref = 0;
- this.timeout = opts.timeout || DEFAULT_TIMEOUT;
- this.transport = opts.transport || global2.WebSocket || LongPoll;
- this.establishedConnections = 0;
- this.defaultEncoder = serializer_default.encode.bind(serializer_default);
- this.defaultDecoder = serializer_default.decode.bind(serializer_default);
- this.closeWasClean = false;
- this.binaryType = opts.binaryType || "arraybuffer";
- this.connectClock = 1;
- if (this.transport !== LongPoll) {
- this.encode = opts.encode || this.defaultEncoder;
- this.decode = opts.decode || this.defaultDecoder;
- } else {
- this.encode = this.defaultEncoder;
- this.decode = this.defaultDecoder;
- }
- let awaitingConnectionOnPageShow = null;
- if (phxWindow && phxWindow.addEventListener) {
- phxWindow.addEventListener("pagehide", (_e2) => {
- if (this.conn) {
- this.disconnect();
- awaitingConnectionOnPageShow = this.connectClock;
- }
- });
- phxWindow.addEventListener("pageshow", (_e2) => {
- if (awaitingConnectionOnPageShow === this.connectClock) {
- awaitingConnectionOnPageShow = null;
- this.connect();
- }
- });
- }
- this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 3e4;
- this.rejoinAfterMs = (tries) => {
- if (opts.rejoinAfterMs) {
- return opts.rejoinAfterMs(tries);
- } else {
- return [1e3, 2e3, 5e3][tries - 1] || 1e4;
- }
- };
- this.reconnectAfterMs = (tries) => {
- if (opts.reconnectAfterMs) {
- return opts.reconnectAfterMs(tries);
- } else {
- return [10, 50, 100, 150, 200, 250, 500, 1e3, 2e3][tries - 1] || 5e3;
- }
- };
- this.logger = opts.logger || null;
- this.longpollerTimeout = opts.longpollerTimeout || 2e4;
- this.params = closure(opts.params || {});
- this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`;
- this.vsn = opts.vsn || DEFAULT_VSN;
- this.heartbeatTimeoutTimer = null;
- this.heartbeatTimer = null;
- this.pendingHeartbeatRef = null;
- this.reconnectTimer = new Timer(() => {
- this.teardown(() => this.connect());
- }, this.reconnectAfterMs);
- }
- getLongPollTransport() {
- return LongPoll;
- }
- replaceTransport(newTransport) {
- this.connectClock++;
- this.closeWasClean = true;
- this.reconnectTimer.reset();
- this.sendBuffer = [];
- if (this.conn) {
- this.conn.close();
- this.conn = null;
- }
- this.transport = newTransport;
- }
- protocol() {
- return location.protocol.match(/^https/) ? "wss" : "ws";
- }
- endPointURL() {
- let uri = Ajax.appendParams(Ajax.appendParams(this.endPoint, this.params()), { vsn: this.vsn });
- if (uri.charAt(0) !== "/") {
- return uri;
- }
- if (uri.charAt(1) === "/") {
- return `${this.protocol()}:${uri}`;
- }
- return `${this.protocol()}://${location.host}${uri}`;
- }
- disconnect(callback, code, reason) {
- this.connectClock++;
- this.closeWasClean = true;
- this.reconnectTimer.reset();
- this.teardown(callback, code, reason);
- }
- connect(params) {
- if (params) {
- console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor");
- this.params = closure(params);
- }
- if (this.conn) {
- return;
- }
- this.connectClock++;
- this.closeWasClean = false;
- this.conn = new this.transport(this.endPointURL());
- this.conn.binaryType = this.binaryType;
- this.conn.timeout = this.longpollerTimeout;
- this.conn.onopen = () => this.onConnOpen();
- this.conn.onerror = (error) => this.onConnError(error);
- this.conn.onmessage = (event) => this.onConnMessage(event);
- this.conn.onclose = (event) => this.onConnClose(event);
- }
- log(kind, msg, data) {
- this.logger(kind, msg, data);
- }
- hasLogger() {
- return this.logger !== null;
- }
- onOpen(callback) {
- let ref = this.makeRef();
- this.stateChangeCallbacks.open.push([ref, callback]);
- return ref;
- }
- onClose(callback) {
- let ref = this.makeRef();
- this.stateChangeCallbacks.close.push([ref, callback]);
- return ref;
- }
- onError(callback) {
- let ref = this.makeRef();
- this.stateChangeCallbacks.error.push([ref, callback]);
- return ref;
- }
- onMessage(callback) {
- let ref = this.makeRef();
- this.stateChangeCallbacks.message.push([ref, callback]);
- return ref;
- }
- ping(callback) {
- if (!this.isConnected()) {
- return false;
- }
- let ref = this.makeRef();
- let startTime = Date.now();
- this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref });
- let onMsgRef = this.onMessage((msg) => {
- if (msg.ref === ref) {
- this.off([onMsgRef]);
- callback(Date.now() - startTime);
- }
- });
- return true;
- }
- clearHeartbeats() {
- clearTimeout(this.heartbeatTimer);
- clearTimeout(this.heartbeatTimeoutTimer);
- }
- onConnOpen() {
- if (this.hasLogger())
- this.log("transport", `connected to ${this.endPointURL()}`);
- this.closeWasClean = false;
- this.establishedConnections++;
- this.flushSendBuffer();
- this.reconnectTimer.reset();
- this.resetHeartbeat();
- this.stateChangeCallbacks.open.forEach(([, callback]) => callback());
- }
- heartbeatTimeout() {
- if (this.pendingHeartbeatRef) {
- this.pendingHeartbeatRef = null;
- if (this.hasLogger()) {
- this.log("transport", "heartbeat timeout. Attempting to re-establish connection");
- }
- this.triggerChanError();
- this.closeWasClean = false;
- this.teardown(() => this.reconnectTimer.scheduleTimeout(), WS_CLOSE_NORMAL, "heartbeat timeout");
- }
- }
- resetHeartbeat() {
- if (this.conn && this.conn.skipHeartbeat) {
- return;
- }
- this.pendingHeartbeatRef = null;
- this.clearHeartbeats();
- this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);
- }
- teardown(callback, code, reason) {
- if (!this.conn) {
- return callback && callback();
- }
- this.waitForBufferDone(() => {
- if (this.conn) {
- if (code) {
- this.conn.close(code, reason || "");
- } else {
- this.conn.close();
- }
- }
- this.waitForSocketClosed(() => {
- if (this.conn) {
- this.conn.onopen = function() {
- };
- this.conn.onerror = function() {
- };
- this.conn.onmessage = function() {
- };
- this.conn.onclose = function() {
- };
- this.conn = null;
- }
- callback && callback();
- });
- });
- }
- waitForBufferDone(callback, tries = 1) {
- if (tries === 5 || !this.conn || !this.conn.bufferedAmount) {
- callback();
- return;
- }
- setTimeout(() => {
- this.waitForBufferDone(callback, tries + 1);
- }, 150 * tries);
- }
- waitForSocketClosed(callback, tries = 1) {
- if (tries === 5 || !this.conn || this.conn.readyState === SOCKET_STATES.closed) {
- callback();
- return;
- }
- setTimeout(() => {
- this.waitForSocketClosed(callback, tries + 1);
- }, 150 * tries);
- }
- onConnClose(event) {
- let closeCode = event && event.code;
- if (this.hasLogger())
- this.log("transport", "close", event);
- this.triggerChanError();
- this.clearHeartbeats();
- if (!this.closeWasClean && closeCode !== 1e3) {
- this.reconnectTimer.scheduleTimeout();
- }
- this.stateChangeCallbacks.close.forEach(([, callback]) => callback(event));
- }
- onConnError(error) {
- if (this.hasLogger())
- this.log("transport", error);
- let transportBefore = this.transport;
- let establishedBefore = this.establishedConnections;
- this.stateChangeCallbacks.error.forEach(([, callback]) => {
- callback(error, transportBefore, establishedBefore);
- });
- if (transportBefore === this.transport || establishedBefore > 0) {
- this.triggerChanError();
- }
- }
- triggerChanError() {
- this.channels.forEach((channel) => {
- if (!(channel.isErrored() || channel.isLeaving() || channel.isClosed())) {
- channel.trigger(CHANNEL_EVENTS.error);
- }
- });
- }
- connectionState() {
- switch (this.conn && this.conn.readyState) {
- case SOCKET_STATES.connecting:
- return "connecting";
- case SOCKET_STATES.open:
- return "open";
- case SOCKET_STATES.closing:
- return "closing";
- default:
- return "closed";
- }
- }
- isConnected() {
- return this.connectionState() === "open";
- }
- remove(channel) {
- this.off(channel.stateChangeRefs);
- this.channels = this.channels.filter((c2) => c2.joinRef() !== channel.joinRef());
- }
- off(refs) {
- for (let key in this.stateChangeCallbacks) {
- this.stateChangeCallbacks[key] = this.stateChangeCallbacks[key].filter(([ref]) => {
- return refs.indexOf(ref) === -1;
- });
- }
- }
- channel(topic, chanParams = {}) {
- let chan = new Channel(topic, chanParams, this);
- this.channels.push(chan);
- return chan;
- }
- push(data) {
- if (this.hasLogger()) {
- let { topic, event, payload, ref, join_ref } = data;
- this.log("push", `${topic} ${event} (${join_ref}, ${ref})`, payload);
- }
- if (this.isConnected()) {
- this.encode(data, (result) => this.conn.send(result));
- } else {
- this.sendBuffer.push(() => this.encode(data, (result) => this.conn.send(result)));
- }
- }
- makeRef() {
- let newRef = this.ref + 1;
- if (newRef === this.ref) {
- this.ref = 0;
- } else {
- this.ref = newRef;
- }
- return this.ref.toString();
- }
- sendHeartbeat() {
- if (this.pendingHeartbeatRef && !this.isConnected()) {
- return;
- }
- this.pendingHeartbeatRef = this.makeRef();
- this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref: this.pendingHeartbeatRef });
- this.heartbeatTimeoutTimer = setTimeout(() => this.heartbeatTimeout(), this.heartbeatIntervalMs);
- }
- flushSendBuffer() {
- if (this.isConnected() && this.sendBuffer.length > 0) {
- this.sendBuffer.forEach((callback) => callback());
- this.sendBuffer = [];
- }
- }
- onConnMessage(rawMessage) {
- this.decode(rawMessage.data, (msg) => {
- let { topic, event, payload, ref, join_ref } = msg;
- if (ref && ref === this.pendingHeartbeatRef) {
- this.clearHeartbeats();
- this.pendingHeartbeatRef = null;
- this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);
- }
- if (this.hasLogger())
- this.log("receive", `${payload.status || ""} ${topic} ${event} ${ref && "(" + ref + ")" || ""}`, payload);
- for (let i2 = 0; i2 < this.channels.length; i2++) {
- const channel = this.channels[i2];
- if (!channel.isMember(topic, event, payload, join_ref)) {
- continue;
- }
- channel.trigger(event, payload, ref, join_ref);
- }
- for (let i2 = 0; i2 < this.stateChangeCallbacks.message.length; i2++) {
- let [, callback] = this.stateChangeCallbacks.message[i2];
- callback(msg);
- }
- });
- }
- leaveOpenTopic(topic) {
- let dupChannel = this.channels.find((c2) => c2.topic === topic && (c2.isJoined() || c2.isJoining()));
- if (dupChannel) {
- if (this.hasLogger())
- this.log("transport", `leaving duplicate topic "${topic}"`);
- dupChannel.leave();
- }
- }
- };
-
- // ../deps/phoenix_live_view/priv/static/phoenix_live_view.esm.js
- var CONSECUTIVE_RELOADS = "consecutive-reloads";
- var MAX_RELOADS = 10;
- var RELOAD_JITTER_MIN = 5e3;
- var RELOAD_JITTER_MAX = 1e4;
- var FAILSAFE_JITTER = 3e4;
- var PHX_EVENT_CLASSES = [
- "phx-click-loading",
- "phx-change-loading",
- "phx-submit-loading",
- "phx-keydown-loading",
- "phx-keyup-loading",
- "phx-blur-loading",
- "phx-focus-loading"
- ];
- var PHX_COMPONENT = "data-phx-component";
- var PHX_LIVE_LINK = "data-phx-link";
- var PHX_TRACK_STATIC = "track-static";
- var PHX_LINK_STATE = "data-phx-link-state";
- var PHX_REF = "data-phx-ref";
- var PHX_REF_SRC = "data-phx-ref-src";
- var PHX_TRACK_UPLOADS = "track-uploads";
- var PHX_UPLOAD_REF = "data-phx-upload-ref";
- var PHX_PREFLIGHTED_REFS = "data-phx-preflighted-refs";
- var PHX_DONE_REFS = "data-phx-done-refs";
- var PHX_DROP_TARGET = "drop-target";
- var PHX_ACTIVE_ENTRY_REFS = "data-phx-active-refs";
- var PHX_LIVE_FILE_UPDATED = "phx:live-file:updated";
- var PHX_SKIP = "data-phx-skip";
- var PHX_PRUNE = "data-phx-prune";
- var PHX_PAGE_LOADING = "page-loading";
- var PHX_CONNECTED_CLASS = "phx-connected";
- var PHX_LOADING_CLASS = "phx-loading";
- var PHX_NO_FEEDBACK_CLASS = "phx-no-feedback";
- var PHX_ERROR_CLASS = "phx-error";
- var PHX_CLIENT_ERROR_CLASS = "phx-client-error";
- var PHX_SERVER_ERROR_CLASS = "phx-server-error";
- var PHX_PARENT_ID = "data-phx-parent-id";
- var PHX_MAIN = "data-phx-main";
- var PHX_ROOT_ID = "data-phx-root-id";
- var PHX_VIEWPORT_TOP = "viewport-top";
- var PHX_VIEWPORT_BOTTOM = "viewport-bottom";
- var PHX_TRIGGER_ACTION = "trigger-action";
- var PHX_FEEDBACK_FOR = "feedback-for";
- var PHX_HAS_FOCUSED = "phx-has-focused";
- var FOCUSABLE_INPUTS = ["text", "textarea", "number", "email", "password", "search", "tel", "url", "date", "time", "datetime-local", "color", "range"];
- var CHECKABLE_INPUTS = ["checkbox", "radio"];
- var PHX_HAS_SUBMITTED = "phx-has-submitted";
- var PHX_SESSION = "data-phx-session";
- var PHX_VIEW_SELECTOR = `[${PHX_SESSION}]`;
- var PHX_STICKY = "data-phx-sticky";
- var PHX_STATIC = "data-phx-static";
- var PHX_READONLY = "data-phx-readonly";
- var PHX_DISABLED = "data-phx-disabled";
- var PHX_DISABLE_WITH = "disable-with";
- var PHX_DISABLE_WITH_RESTORE = "data-phx-disable-with-restore";
- var PHX_HOOK = "hook";
- var PHX_DEBOUNCE = "debounce";
- var PHX_THROTTLE = "throttle";
- var PHX_UPDATE = "update";
- var PHX_STREAM = "stream";
- var PHX_STREAM_REF = "data-phx-stream";
- var PHX_KEY = "key";
- var PHX_PRIVATE = "phxPrivate";
- var PHX_AUTO_RECOVER = "auto-recover";
- var PHX_LV_DEBUG = "phx:live-socket:debug";
- var PHX_LV_PROFILE = "phx:live-socket:profiling";
- var PHX_LV_LATENCY_SIM = "phx:live-socket:latency-sim";
- var PHX_PROGRESS = "progress";
- var PHX_MOUNTED = "mounted";
- var LOADER_TIMEOUT = 1;
- var BEFORE_UNLOAD_LOADER_TIMEOUT = 200;
- var BINDING_PREFIX = "phx-";
- var PUSH_TIMEOUT = 3e4;
- var DEBOUNCE_TRIGGER = "debounce-trigger";
- var THROTTLED = "throttled";
- var DEBOUNCE_PREV_KEY = "debounce-prev-key";
- var DEFAULTS = {
- debounce: 300,
- throttle: 300
- };
- var DYNAMICS = "d";
- var STATIC = "s";
- var COMPONENTS = "c";
- var EVENTS = "e";
- var REPLY = "r";
- var TITLE = "t";
- var TEMPLATES = "p";
- var STREAM = "stream";
- var EntryUploader = class {
- constructor(entry, chunkSize, liveSocket2) {
- this.liveSocket = liveSocket2;
- this.entry = entry;
- this.offset = 0;
- this.chunkSize = chunkSize;
- this.chunkTimer = null;
- this.errored = false;
- this.uploadChannel = liveSocket2.channel(`lvu:${entry.ref}`, { token: entry.metadata() });
- }
- error(reason) {
- if (this.errored) {
- return;
- }
- this.errored = true;
- clearTimeout(this.chunkTimer);
- this.entry.error(reason);
- }
- upload() {
- this.uploadChannel.onError((reason) => this.error(reason));
- this.uploadChannel.join().receive("ok", (_data) => this.readNextChunk()).receive("error", (reason) => this.error(reason));
- }
- isDone() {
- return this.offset >= this.entry.file.size;
- }
- readNextChunk() {
- let reader = new window.FileReader();
- let blob = this.entry.file.slice(this.offset, this.chunkSize + this.offset);
- reader.onload = (e2) => {
- if (e2.target.error === null) {
- this.offset += e2.target.result.byteLength;
- this.pushChunk(e2.target.result);
- } else {
- return logError("Read error: " + e2.target.error);
- }
- };
- reader.readAsArrayBuffer(blob);
- }
- pushChunk(chunk) {
- if (!this.uploadChannel.isJoined()) {
- return;
- }
- this.uploadChannel.push("chunk", chunk).receive("ok", () => {
- this.entry.progress(this.offset / this.entry.file.size * 100);
- if (!this.isDone()) {
- this.chunkTimer = setTimeout(() => this.readNextChunk(), this.liveSocket.getLatencySim() || 0);
- }
- }).receive("error", ({ reason }) => this.error(reason));
- }
- };
- var logError = (msg, obj) => console.error && console.error(msg, obj);
- var isCid = (cid) => {
- let type = typeof cid;
- return type === "number" || type === "string" && /^(0|[1-9]\d*)$/.test(cid);
- };
- function detectDuplicateIds() {
- let ids = /* @__PURE__ */ new Set();
- let elems = document.querySelectorAll("*[id]");
- for (let i2 = 0, len = elems.length; i2 < len; i2++) {
- if (ids.has(elems[i2].id)) {
- console.error(`Multiple IDs detected: ${elems[i2].id}. Ensure unique element ids.`);
- } else {
- ids.add(elems[i2].id);
- }
- }
- }
- var debug = (view, kind, msg, obj) => {
- if (view.liveSocket.isDebugEnabled()) {
- console.log(`${view.id} ${kind}: ${msg} - `, obj);
- }
- };
- var closure2 = (val) => typeof val === "function" ? val : function() {
- return val;
- };
- var clone = (obj) => {
- return JSON.parse(JSON.stringify(obj));
- };
- var closestPhxBinding = (el, binding, borderEl) => {
- do {
- if (el.matches(`[${binding}]`) && !el.disabled) {
- return el;
- }
- el = el.parentElement || el.parentNode;
- } while (el !== null && el.nodeType === 1 && !(borderEl && borderEl.isSameNode(el) || el.matches(PHX_VIEW_SELECTOR)));
- return null;
- };
- var isObject = (obj) => {
- return obj !== null && typeof obj === "object" && !(obj instanceof Array);
- };
- var isEqualObj = (obj1, obj2) => JSON.stringify(obj1) === JSON.stringify(obj2);
- var isEmpty = (obj) => {
- for (let x2 in obj) {
- return false;
- }
- return true;
- };
- var maybe = (el, callback) => el && callback(el);
- var channelUploader = function(entries, onError, resp, liveSocket2) {
- entries.forEach((entry) => {
- let entryUploader = new EntryUploader(entry, resp.config.chunk_size, liveSocket2);
- entryUploader.upload();
- });
- };
- var Browser = {
- canPushState() {
- return typeof history.pushState !== "undefined";
- },
- dropLocal(localStorage, namespace, subkey) {
- return localStorage.removeItem(this.localKey(namespace, subkey));
- },
- updateLocal(localStorage, namespace, subkey, initial, func) {
- let current = this.getLocal(localStorage, namespace, subkey);
- let key = this.localKey(namespace, subkey);
- let newVal = current === null ? initial : func(current);
- localStorage.setItem(key, JSON.stringify(newVal));
- return newVal;
- },
- getLocal(localStorage, namespace, subkey) {
- return JSON.parse(localStorage.getItem(this.localKey(namespace, subkey)));
- },
- updateCurrentState(callback) {
- if (!this.canPushState()) {
- return;
- }
- history.replaceState(callback(history.state || {}), "", window.location.href);
- },
- pushState(kind, meta, to) {
- if (this.canPushState()) {
- if (to !== window.location.href) {
- if (meta.type == "redirect" && meta.scroll) {
- let currentState = history.state || {};
- currentState.scroll = meta.scroll;
- history.replaceState(currentState, "", window.location.href);
- }
- delete meta.scroll;
- history[kind + "State"](meta, "", to || null);
- let hashEl = this.getHashTargetEl(window.location.hash);
- if (hashEl) {
- hashEl.scrollIntoView();
- } else if (meta.type === "redirect") {
- window.scroll(0, 0);
- }
- }
- } else {
- this.redirect(to);
- }
- },
- setCookie(name, value) {
- document.cookie = `${name}=${value}`;
- },
- getCookie(name) {
- return document.cookie.replace(new RegExp(`(?:(?:^|.*;s*)${name}s*=s*([^;]*).*$)|^.*$`), "$1");
- },
- redirect(toURL, flash) {
- if (flash) {
- Browser.setCookie("__phoenix_flash__", flash + "; max-age=60000; path=/");
- }
- window.location = toURL;
- },
- localKey(namespace, subkey) {
- return `${namespace}-${subkey}`;
- },
- getHashTargetEl(maybeHash) {
- let hash = maybeHash.toString().substring(1);
- if (hash === "") {
- return;
- }
- return document.getElementById(hash) || document.querySelector(`a[name="${hash}"]`);
- }
- };
- var browser_default = Browser;
- var DOM = {
- byId(id) {
- return document.getElementById(id) || logError(`no id found for ${id}`);
- },
- removeClass(el, className) {
- el.classList.remove(className);
- if (el.classList.length === 0) {
- el.removeAttribute("class");
- }
- },
- all(node, query, callback) {
- if (!node) {
- return [];
- }
- let array = Array.from(node.querySelectorAll(query));
- return callback ? array.forEach(callback) : array;
- },
- childNodeLength(html) {
- let template = document.createElement("template");
- template.innerHTML = html;
- return template.content.childElementCount;
- },
- isUploadInput(el) {
- return el.type === "file" && el.getAttribute(PHX_UPLOAD_REF) !== null;
- },
- isAutoUpload(inputEl) {
- return inputEl.hasAttribute("data-phx-auto-upload");
- },
- findUploadInputs(node) {
- return this.all(node, `input[type="file"][${PHX_UPLOAD_REF}]`);
- },
- findComponentNodeList(node, cid) {
- return this.filterWithinSameLiveView(this.all(node, `[${PHX_COMPONENT}="${cid}"]`), node);
- },
- isPhxDestroyed(node) {
- return node.id && DOM.private(node, "destroyed") ? true : false;
- },
- wantsNewTab(e2) {
- let wantsNewTab = e2.ctrlKey || e2.shiftKey || e2.metaKey || e2.button && e2.button === 1;
- let isDownload = e2.target instanceof HTMLAnchorElement && e2.target.hasAttribute("download");
- let isTargetBlank = e2.target.hasAttribute("target") && e2.target.getAttribute("target").toLowerCase() === "_blank";
- return wantsNewTab || isTargetBlank || isDownload;
- },
- isUnloadableFormSubmit(e2) {
- let isDialogSubmit = e2.target && e2.target.getAttribute("method") === "dialog" || e2.submitter && e2.submitter.getAttribute("formmethod") === "dialog";
- if (isDialogSubmit) {
- return false;
- } else {
- return !e2.defaultPrevented && !this.wantsNewTab(e2);
- }
- },
- isNewPageClick(e2, currentLocation) {
- let href = e2.target instanceof HTMLAnchorElement ? e2.target.getAttribute("href") : null;
- let url;
- if (e2.defaultPrevented || href === null || this.wantsNewTab(e2)) {
- return false;
- }
- if (href.startsWith("mailto:") || href.startsWith("tel:")) {
- return false;
- }
- if (e2.target.isContentEditable) {
- return false;
- }
- try {
- url = new URL(href);
- } catch (e22) {
- try {
- url = new URL(href, currentLocation);
- } catch (e3) {
- return true;
- }
- }
- if (url.host === currentLocation.host && url.protocol === currentLocation.protocol) {
- if (url.pathname === currentLocation.pathname && url.search === currentLocation.search) {
- return url.hash === "" && !url.href.endsWith("#");
- }
- }
- return url.protocol.startsWith("http");
- },
- markPhxChildDestroyed(el) {
- if (this.isPhxChild(el)) {
- el.setAttribute(PHX_SESSION, "");
- }
- this.putPrivate(el, "destroyed", true);
- },
- findPhxChildrenInFragment(html, parentId) {
- let template = document.createElement("template");
- template.innerHTML = html;
- return this.findPhxChildren(template.content, parentId);
- },
- isIgnored(el, phxUpdate) {
- return (el.getAttribute(phxUpdate) || el.getAttribute("data-phx-update")) === "ignore";
- },
- isPhxUpdate(el, phxUpdate, updateTypes) {
- return el.getAttribute && updateTypes.indexOf(el.getAttribute(phxUpdate)) >= 0;
- },
- findPhxSticky(el) {
- return this.all(el, `[${PHX_STICKY}]`);
- },
- findPhxChildren(el, parentId) {
- return this.all(el, `${PHX_VIEW_SELECTOR}[${PHX_PARENT_ID}="${parentId}"]`);
- },
- findParentCIDs(node, cids) {
- let initial = new Set(cids);
- let parentCids = cids.reduce((acc, cid) => {
- let selector = `[${PHX_COMPONENT}="${cid}"] [${PHX_COMPONENT}]`;
- this.filterWithinSameLiveView(this.all(node, selector), node).map((el) => parseInt(el.getAttribute(PHX_COMPONENT))).forEach((childCID) => acc.delete(childCID));
- return acc;
- }, initial);
- return parentCids.size === 0 ? new Set(cids) : parentCids;
- },
- filterWithinSameLiveView(nodes, parent) {
- if (parent.querySelector(PHX_VIEW_SELECTOR)) {
- return nodes.filter((el) => this.withinSameLiveView(el, parent));
- } else {
- return nodes;
- }
- },
- withinSameLiveView(node, parent) {
- while (node = node.parentNode) {
- if (node.isSameNode(parent)) {
- return true;
- }
- if (node.getAttribute(PHX_SESSION) !== null) {
- return false;
- }
- }
- },
- private(el, key) {
- return el[PHX_PRIVATE] && el[PHX_PRIVATE][key];
- },
- deletePrivate(el, key) {
- el[PHX_PRIVATE] && delete el[PHX_PRIVATE][key];
- },
- putPrivate(el, key, value) {
- if (!el[PHX_PRIVATE]) {
- el[PHX_PRIVATE] = {};
- }
- el[PHX_PRIVATE][key] = value;
- },
- updatePrivate(el, key, defaultVal, updateFunc) {
- let existing = this.private(el, key);
- if (existing === void 0) {
- this.putPrivate(el, key, updateFunc(defaultVal));
- } else {
- this.putPrivate(el, key, updateFunc(existing));
- }
- },
- copyPrivates(target, source) {
- if (source[PHX_PRIVATE]) {
- target[PHX_PRIVATE] = source[PHX_PRIVATE];
- }
- },
- putTitle(str) {
- let titleEl = document.querySelector("title");
- if (titleEl) {
- let { prefix, suffix } = titleEl.dataset;
- document.title = `${prefix || ""}${str}${suffix || ""}`;
- } else {
- document.title = str;
- }
- },
- debounce(el, event, phxDebounce, defaultDebounce, phxThrottle, defaultThrottle, asyncFilter, callback) {
- let debounce = el.getAttribute(phxDebounce);
- let throttle = el.getAttribute(phxThrottle);
- if (debounce === "") {
- debounce = defaultDebounce;
- }
- if (throttle === "") {
- throttle = defaultThrottle;
- }
- let value = debounce || throttle;
- switch (value) {
- case null:
- return callback();
- case "blur":
- if (this.once(el, "debounce-blur")) {
- el.addEventListener("blur", () => callback());
- }
- return;
- default:
- let timeout = parseInt(value);
- let trigger = () => throttle ? this.deletePrivate(el, THROTTLED) : callback();
- let currentCycle = this.incCycle(el, DEBOUNCE_TRIGGER, trigger);
- if (isNaN(timeout)) {
- return logError(`invalid throttle/debounce value: ${value}`);
- }
- if (throttle) {
- let newKeyDown = false;
- if (event.type === "keydown") {
- let prevKey = this.private(el, DEBOUNCE_PREV_KEY);
- this.putPrivate(el, DEBOUNCE_PREV_KEY, event.key);
- newKeyDown = prevKey !== event.key;
- }
- if (!newKeyDown && this.private(el, THROTTLED)) {
- return false;
- } else {
- callback();
- this.putPrivate(el, THROTTLED, true);
- setTimeout(() => {
- if (asyncFilter()) {
- this.triggerCycle(el, DEBOUNCE_TRIGGER);
- }
- }, timeout);
- }
- } else {
- setTimeout(() => {
- if (asyncFilter()) {
- this.triggerCycle(el, DEBOUNCE_TRIGGER, currentCycle);
- }
- }, timeout);
- }
- let form = el.form;
- if (form && this.once(form, "bind-debounce")) {
- form.addEventListener("submit", () => {
- Array.from(new FormData(form).entries(), ([name]) => {
- let input = form.querySelector(`[name="${name}"]`);
- this.incCycle(input, DEBOUNCE_TRIGGER);
- this.deletePrivate(input, THROTTLED);
- });
- });
- }
- if (this.once(el, "bind-debounce")) {
- el.addEventListener("blur", () => this.triggerCycle(el, DEBOUNCE_TRIGGER));
- }
- }
- },
- triggerCycle(el, key, currentCycle) {
- let [cycle, trigger] = this.private(el, key);
- if (!currentCycle) {
- currentCycle = cycle;
- }
- if (currentCycle === cycle) {
- this.incCycle(el, key);
- trigger();
- }
- },
- once(el, key) {
- if (this.private(el, key) === true) {
- return false;
- }
- this.putPrivate(el, key, true);
- return true;
- },
- incCycle(el, key, trigger = function() {
- }) {
- let [currentCycle] = this.private(el, key) || [0, trigger];
- currentCycle++;
- this.putPrivate(el, key, [currentCycle, trigger]);
- return currentCycle;
- },
- maybeAddPrivateHooks(el, phxViewportTop, phxViewportBottom) {
- if (el.hasAttribute && (el.hasAttribute(phxViewportTop) || el.hasAttribute(phxViewportBottom))) {
- el.setAttribute("data-phx-hook", "Phoenix.InfiniteScroll");
- }
- },
- maybeHideFeedback(container, input, phxFeedbackFor) {
- if (!(this.private(input, PHX_HAS_FOCUSED) || this.private(input, PHX_HAS_SUBMITTED))) {
- let feedbacks = [input.name];
- if (input.name.endsWith("[]")) {
- feedbacks.push(input.name.slice(0, -2));
- }
- let selector = feedbacks.map((f2) => `[${phxFeedbackFor}="${f2}"]`).join(", ");
- DOM.all(container, selector, (el) => el.classList.add(PHX_NO_FEEDBACK_CLASS));
- }
- },
- resetForm(form, phxFeedbackFor) {
- Array.from(form.elements).forEach((input) => {
- let query = `[${phxFeedbackFor}="${input.id}"],
- [${phxFeedbackFor}="${input.name}"],
- [${phxFeedbackFor}="${input.name.replace(/\[\]$/, "")}"]`;
- this.deletePrivate(input, PHX_HAS_FOCUSED);
- this.deletePrivate(input, PHX_HAS_SUBMITTED);
- this.all(document, query, (feedbackEl) => {
- feedbackEl.classList.add(PHX_NO_FEEDBACK_CLASS);
- });
- });
- },
- showError(inputEl, phxFeedbackFor) {
- if (inputEl.id || inputEl.name) {
- this.all(inputEl.form, `[${phxFeedbackFor}="${inputEl.id}"], [${phxFeedbackFor}="${inputEl.name}"]`, (el) => {
- this.removeClass(el, PHX_NO_FEEDBACK_CLASS);
- });
- }
- },
- isPhxChild(node) {
- return node.getAttribute && node.getAttribute(PHX_PARENT_ID);
- },
- isPhxSticky(node) {
- return node.getAttribute && node.getAttribute(PHX_STICKY) !== null;
- },
- firstPhxChild(el) {
- return this.isPhxChild(el) ? el : this.all(el, `[${PHX_PARENT_ID}]`)[0];
- },
- dispatchEvent(target, name, opts = {}) {
- let bubbles = opts.bubbles === void 0 ? true : !!opts.bubbles;
- let eventOpts = { bubbles, cancelable: true, detail: opts.detail || {} };
- let event = name === "click" ? new MouseEvent("click", eventOpts) : new CustomEvent(name, eventOpts);
- target.dispatchEvent(event);
- },
- cloneNode(node, html) {
- if (typeof html === "undefined") {
- return node.cloneNode(true);
- } else {
- let cloned = node.cloneNode(false);
- cloned.innerHTML = html;
- return cloned;
- }
- },
- mergeAttrs(target, source, opts = {}) {
- let exclude = opts.exclude || [];
- let isIgnored = opts.isIgnored;
- let sourceAttrs = source.attributes;
- for (let i2 = sourceAttrs.length - 1; i2 >= 0; i2--) {
- let name = sourceAttrs[i2].name;
- if (exclude.indexOf(name) < 0) {
- target.setAttribute(name, source.getAttribute(name));
- }
- }
- let targetAttrs = target.attributes;
- for (let i2 = targetAttrs.length - 1; i2 >= 0; i2--) {
- let name = targetAttrs[i2].name;
- if (isIgnored) {
- if (name.startsWith("data-") && !source.hasAttribute(name)) {
- target.removeAttribute(name);
- }
- } else {
- if (!source.hasAttribute(name)) {
- target.removeAttribute(name);
- }
- }
- }
- },
- mergeFocusedInput(target, source) {
- if (!(target instanceof HTMLSelectElement)) {
- DOM.mergeAttrs(target, source, { exclude: ["value"] });
- }
- if (source.readOnly) {
- target.setAttribute("readonly", true);
- } else {
- target.removeAttribute("readonly");
- }
- },
- hasSelectionRange(el) {
- return el.setSelectionRange && (el.type === "text" || el.type === "textarea");
- },
- restoreFocus(focused, selectionStart, selectionEnd) {
- if (!DOM.isTextualInput(focused)) {
- return;
- }
- let wasFocused = focused.matches(":focus");
- if (focused.readOnly) {
- focused.blur();
- }
- if (!wasFocused) {
- focused.focus();
- }
- if (this.hasSelectionRange(focused)) {
- focused.setSelectionRange(selectionStart, selectionEnd);
- }
- },
- isFormInput(el) {
- return /^(?:input|select|textarea)$/i.test(el.tagName) && el.type !== "button";
- },
- syncAttrsToProps(el) {
- if (el instanceof HTMLInputElement && CHECKABLE_INPUTS.indexOf(el.type.toLocaleLowerCase()) >= 0) {
- el.checked = el.getAttribute("checked") !== null;
- }
- },
- isTextualInput(el) {
- return FOCUSABLE_INPUTS.indexOf(el.type) >= 0;
- },
- isNowTriggerFormExternal(el, phxTriggerExternal) {
- return el.getAttribute && el.getAttribute(phxTriggerExternal) !== null;
- },
- syncPendingRef(fromEl, toEl, disableWith) {
- let ref = fromEl.getAttribute(PHX_REF);
- if (ref === null) {
- return true;
- }
- let refSrc = fromEl.getAttribute(PHX_REF_SRC);
- if (DOM.isFormInput(fromEl) || fromEl.getAttribute(disableWith) !== null) {
- if (DOM.isUploadInput(fromEl)) {
- DOM.mergeAttrs(fromEl, toEl, { isIgnored: true });
- }
- DOM.putPrivate(fromEl, PHX_REF, toEl);
- return false;
- } else {
- PHX_EVENT_CLASSES.forEach((className) => {
- fromEl.classList.contains(className) && toEl.classList.add(className);
- });
- toEl.setAttribute(PHX_REF, ref);
- toEl.setAttribute(PHX_REF_SRC, refSrc);
- return true;
- }
- },
- cleanChildNodes(container, phxUpdate) {
- if (DOM.isPhxUpdate(container, phxUpdate, ["append", "prepend"])) {
- let toRemove = [];
- container.childNodes.forEach((childNode) => {
- if (!childNode.id) {
- let isEmptyTextNode = childNode.nodeType === Node.TEXT_NODE && childNode.nodeValue.trim() === "";
- if (!isEmptyTextNode) {
- logError(`only HTML element tags with an id are allowed inside containers with phx-update.
-
-removing illegal node: "${(childNode.outerHTML || childNode.nodeValue).trim()}"
-
-`);
- }
- toRemove.push(childNode);
- }
- });
- toRemove.forEach((childNode) => childNode.remove());
- }
- },
- replaceRootContainer(container, tagName, attrs) {
- let retainedAttrs = /* @__PURE__ */ new Set(["id", PHX_SESSION, PHX_STATIC, PHX_MAIN, PHX_ROOT_ID]);
- if (container.tagName.toLowerCase() === tagName.toLowerCase()) {
- Array.from(container.attributes).filter((attr) => !retainedAttrs.has(attr.name.toLowerCase())).forEach((attr) => container.removeAttribute(attr.name));
- Object.keys(attrs).filter((name) => !retainedAttrs.has(name.toLowerCase())).forEach((attr) => container.setAttribute(attr, attrs[attr]));
- return container;
- } else {
- let newContainer = document.createElement(tagName);
- Object.keys(attrs).forEach((attr) => newContainer.setAttribute(attr, attrs[attr]));
- retainedAttrs.forEach((attr) => newContainer.setAttribute(attr, container.getAttribute(attr)));
- newContainer.innerHTML = container.innerHTML;
- container.replaceWith(newContainer);
- return newContainer;
- }
- },
- getSticky(el, name, defaultVal) {
- let op = (DOM.private(el, "sticky") || []).find(([existingName]) => name === existingName);
- if (op) {
- let [_name, _op, stashedResult] = op;
- return stashedResult;
- } else {
- return typeof defaultVal === "function" ? defaultVal() : defaultVal;
- }
- },
- deleteSticky(el, name) {
- this.updatePrivate(el, "sticky", [], (ops) => {
- return ops.filter(([existingName, _5]) => existingName !== name);
- });
- },
- putSticky(el, name, op) {
- let stashedResult = op(el);
- this.updatePrivate(el, "sticky", [], (ops) => {
- let existingIndex = ops.findIndex(([existingName]) => name === existingName);
- if (existingIndex >= 0) {
- ops[existingIndex] = [name, op, stashedResult];
- } else {
- ops.push([name, op, stashedResult]);
- }
- return ops;
- });
- },
- applyStickyOperations(el) {
- let ops = DOM.private(el, "sticky");
- if (!ops) {
- return;
- }
- ops.forEach(([name, op, _stashed]) => this.putSticky(el, name, op));
- }
- };
- var dom_default = DOM;
- var UploadEntry = class {
- static isActive(fileEl, file) {
- let isNew = file._phxRef === void 0;
- let activeRefs = fileEl.getAttribute(PHX_ACTIVE_ENTRY_REFS).split(",");
- let isActive = activeRefs.indexOf(LiveUploader.genFileRef(file)) >= 0;
- return file.size > 0 && (isNew || isActive);
- }
- static isPreflighted(fileEl, file) {
- let preflightedRefs = fileEl.getAttribute(PHX_PREFLIGHTED_REFS).split(",");
- let isPreflighted = preflightedRefs.indexOf(LiveUploader.genFileRef(file)) >= 0;
- return isPreflighted && this.isActive(fileEl, file);
- }
- constructor(fileEl, file, view) {
- this.ref = LiveUploader.genFileRef(file);
- this.fileEl = fileEl;
- this.file = file;
- this.view = view;
- this.meta = null;
- this._isCancelled = false;
- this._isDone = false;
- this._progress = 0;
- this._lastProgressSent = -1;
- this._onDone = function() {
- };
- this._onElUpdated = this.onElUpdated.bind(this);
- this.fileEl.addEventListener(PHX_LIVE_FILE_UPDATED, this._onElUpdated);
- }
- metadata() {
- return this.meta;
- }
- progress(progress) {
- this._progress = Math.floor(progress);
- if (this._progress > this._lastProgressSent) {
- if (this._progress >= 100) {
- this._progress = 100;
- this._lastProgressSent = 100;
- this._isDone = true;
- this.view.pushFileProgress(this.fileEl, this.ref, 100, () => {
- LiveUploader.untrackFile(this.fileEl, this.file);
- this._onDone();
- });
- } else {
- this._lastProgressSent = this._progress;
- this.view.pushFileProgress(this.fileEl, this.ref, this._progress);
- }
- }
- }
- cancel() {
- this._isCancelled = true;
- this._isDone = true;
- this._onDone();
- }
- isDone() {
- return this._isDone;
- }
- error(reason = "failed") {
- this.fileEl.removeEventListener(PHX_LIVE_FILE_UPDATED, this._onElUpdated);
- this.view.pushFileProgress(this.fileEl, this.ref, { error: reason });
- if (!dom_default.isAutoUpload(this.fileEl)) {
- LiveUploader.clearFiles(this.fileEl);
- }
- }
- onDone(callback) {
- this._onDone = () => {
- this.fileEl.removeEventListener(PHX_LIVE_FILE_UPDATED, this._onElUpdated);
- callback();
- };
- }
- onElUpdated() {
- let activeRefs = this.fileEl.getAttribute(PHX_ACTIVE_ENTRY_REFS).split(",");
- if (activeRefs.indexOf(this.ref) === -1) {
- this.cancel();
- }
- }
- toPreflightPayload() {
- return {
- last_modified: this.file.lastModified,
- name: this.file.name,
- relative_path: this.file.webkitRelativePath,
- size: this.file.size,
- type: this.file.type,
- ref: this.ref,
- meta: typeof this.file.meta === "function" ? this.file.meta() : void 0
- };
- }
- uploader(uploaders) {
- if (this.meta.uploader) {
- let callback = uploaders[this.meta.uploader] || logError(`no uploader configured for ${this.meta.uploader}`);
- return { name: this.meta.uploader, callback };
- } else {
- return { name: "channel", callback: channelUploader };
- }
- }
- zipPostFlight(resp) {
- this.meta = resp.entries[this.ref];
- if (!this.meta) {
- logError(`no preflight upload response returned with ref ${this.ref}`, { input: this.fileEl, response: resp });
- }
- }
- };
- var liveUploaderFileRef = 0;
- var LiveUploader = class {
- static genFileRef(file) {
- let ref = file._phxRef;
- if (ref !== void 0) {
- return ref;
- } else {
- file._phxRef = (liveUploaderFileRef++).toString();
- return file._phxRef;
- }
- }
- static getEntryDataURL(inputEl, ref, callback) {
- let file = this.activeFiles(inputEl).find((file2) => this.genFileRef(file2) === ref);
- callback(URL.createObjectURL(file));
- }
- static hasUploadsInProgress(formEl) {
- let active = 0;
- dom_default.findUploadInputs(formEl).forEach((input) => {
- if (input.getAttribute(PHX_PREFLIGHTED_REFS) !== input.getAttribute(PHX_DONE_REFS)) {
- active++;
- }
- });
- return active > 0;
- }
- static serializeUploads(inputEl) {
- let files = this.activeFiles(inputEl);
- let fileData = {};
- files.forEach((file) => {
- let entry = { path: inputEl.name };
- let uploadRef = inputEl.getAttribute(PHX_UPLOAD_REF);
- fileData[uploadRef] = fileData[uploadRef] || [];
- entry.ref = this.genFileRef(file);
- entry.last_modified = file.lastModified;
- entry.name = file.name || entry.ref;
- entry.relative_path = file.webkitRelativePath;
- entry.type = file.type;
- entry.size = file.size;
- if (typeof file.meta === "function") {
- entry.meta = file.meta();
- }
- fileData[uploadRef].push(entry);
- });
- return fileData;
- }
- static clearFiles(inputEl) {
- inputEl.value = null;
- inputEl.removeAttribute(PHX_UPLOAD_REF);
- dom_default.putPrivate(inputEl, "files", []);
- }
- static untrackFile(inputEl, file) {
- dom_default.putPrivate(inputEl, "files", dom_default.private(inputEl, "files").filter((f2) => !Object.is(f2, file)));
- }
- static trackFiles(inputEl, files, dataTransfer) {
- if (inputEl.getAttribute("multiple") !== null) {
- let newFiles = files.filter((file) => !this.activeFiles(inputEl).find((f2) => Object.is(f2, file)));
- dom_default.putPrivate(inputEl, "files", this.activeFiles(inputEl).concat(newFiles));
- inputEl.value = null;
- } else {
- if (dataTransfer && dataTransfer.files.length > 0) {
- inputEl.files = dataTransfer.files;
- }
- dom_default.putPrivate(inputEl, "files", files);
- }
- }
- static activeFileInputs(formEl) {
- let fileInputs = dom_default.findUploadInputs(formEl);
- return Array.from(fileInputs).filter((el) => el.files && this.activeFiles(el).length > 0);
- }
- static activeFiles(input) {
- return (dom_default.private(input, "files") || []).filter((f2) => UploadEntry.isActive(input, f2));
- }
- static inputsAwaitingPreflight(formEl) {
- let fileInputs = dom_default.findUploadInputs(formEl);
- return Array.from(fileInputs).filter((input) => this.filesAwaitingPreflight(input).length > 0);
- }
- static filesAwaitingPreflight(input) {
- return this.activeFiles(input).filter((f2) => !UploadEntry.isPreflighted(input, f2));
- }
- constructor(inputEl, view, onComplete) {
- this.view = view;
- this.onComplete = onComplete;
- this._entries = Array.from(LiveUploader.filesAwaitingPreflight(inputEl) || []).map((file) => new UploadEntry(inputEl, file, view));
- this.numEntriesInProgress = this._entries.length;
- }
- entries() {
- return this._entries;
- }
- initAdapterUpload(resp, onError, liveSocket2) {
- this._entries = this._entries.map((entry) => {
- entry.zipPostFlight(resp);
- entry.onDone(() => {
- this.numEntriesInProgress--;
- if (this.numEntriesInProgress === 0) {
- this.onComplete();
- }
- });
- return entry;
- });
- let groupedEntries = this._entries.reduce((acc, entry) => {
- if (!entry.meta) {
- return acc;
- }
- let { name, callback } = entry.uploader(liveSocket2.uploaders);
- acc[name] = acc[name] || { callback, entries: [] };
- acc[name].entries.push(entry);
- return acc;
- }, {});
- for (let name in groupedEntries) {
- let { callback, entries } = groupedEntries[name];
- callback(entries, onError, resp, liveSocket2);
- }
- }
- };
- var ARIA = {
- focusMain() {
- let target = document.querySelector("main h1, main, h1");
- if (target) {
- let origTabIndex = target.tabIndex;
- target.tabIndex = -1;
- target.focus();
- target.tabIndex = origTabIndex;
- }
- },
- anyOf(instance, classes) {
- return classes.find((name) => instance instanceof name);
- },
- isFocusable(el, interactiveOnly) {
- return el instanceof HTMLAnchorElement && el.rel !== "ignore" || el instanceof HTMLAreaElement && el.href !== void 0 || !el.disabled && this.anyOf(el, [HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement, HTMLButtonElement]) || el instanceof HTMLIFrameElement || (el.tabIndex > 0 || !interactiveOnly && el.tabIndex === 0 && el.getAttribute("tabindex") !== null && el.getAttribute("aria-hidden") !== "true");
- },
- attemptFocus(el, interactiveOnly) {
- if (this.isFocusable(el, interactiveOnly)) {
- try {
- el.focus();
- } catch (e2) {
- }
- }
- return !!document.activeElement && document.activeElement.isSameNode(el);
- },
- focusFirstInteractive(el) {
- let child = el.firstElementChild;
- while (child) {
- if (this.attemptFocus(child, true) || this.focusFirstInteractive(child, true)) {
- return true;
- }
- child = child.nextElementSibling;
- }
- },
- focusFirst(el) {
- let child = el.firstElementChild;
- while (child) {
- if (this.attemptFocus(child) || this.focusFirst(child)) {
- return true;
- }
- child = child.nextElementSibling;
- }
- },
- focusLast(el) {
- let child = el.lastElementChild;
- while (child) {
- if (this.attemptFocus(child) || this.focusLast(child)) {
- return true;
- }
- child = child.previousElementSibling;
- }
- }
- };
- var aria_default = ARIA;
- var Hooks = {
- LiveFileUpload: {
- activeRefs() {
- return this.el.getAttribute(PHX_ACTIVE_ENTRY_REFS);
- },
- preflightedRefs() {
- return this.el.getAttribute(PHX_PREFLIGHTED_REFS);
- },
- mounted() {
- this.preflightedWas = this.preflightedRefs();
- },
- updated() {
- let newPreflights = this.preflightedRefs();
- if (this.preflightedWas !== newPreflights) {
- this.preflightedWas = newPreflights;
- if (newPreflights === "") {
- this.__view.cancelSubmit(this.el.form);
- }
- }
- if (this.activeRefs() === "") {
- this.el.value = null;
- }
- this.el.dispatchEvent(new CustomEvent(PHX_LIVE_FILE_UPDATED));
- }
- },
- LiveImgPreview: {
- mounted() {
- this.ref = this.el.getAttribute("data-phx-entry-ref");
- this.inputEl = document.getElementById(this.el.getAttribute(PHX_UPLOAD_REF));
- LiveUploader.getEntryDataURL(this.inputEl, this.ref, (url) => {
- this.url = url;
- this.el.src = url;
- });
- },
- destroyed() {
- URL.revokeObjectURL(this.url);
- }
- },
- FocusWrap: {
- mounted() {
- this.focusStart = this.el.firstElementChild;
- this.focusEnd = this.el.lastElementChild;
- this.focusStart.addEventListener("focus", () => aria_default.focusLast(this.el));
- this.focusEnd.addEventListener("focus", () => aria_default.focusFirst(this.el));
- this.el.addEventListener("phx:show-end", () => this.el.focus());
- if (window.getComputedStyle(this.el).display !== "none") {
- aria_default.focusFirst(this.el);
- }
- }
- }
- };
- var scrollTop = () => document.documentElement.scrollTop || document.body.scrollTop;
- var winHeight = () => window.innerHeight || document.documentElement.clientHeight;
- var isAtViewportTop = (el) => {
- let rect = el.getBoundingClientRect();
- return rect.top >= 0 && rect.left >= 0 && rect.top <= winHeight();
- };
- var isAtViewportBottom = (el) => {
- let rect = el.getBoundingClientRect();
- return rect.right >= 0 && rect.left >= 0 && rect.bottom <= winHeight();
- };
- var isWithinViewport = (el) => {
- let rect = el.getBoundingClientRect();
- return rect.top >= 0 && rect.left >= 0 && rect.top <= winHeight();
- };
- Hooks.InfiniteScroll = {
- mounted() {
- let scrollBefore = scrollTop();
- let topOverran = false;
- let throttleInterval = 500;
- let pendingOp = null;
- let onTopOverrun = this.throttle(throttleInterval, (topEvent, firstChild) => {
- pendingOp = () => true;
- this.liveSocket.execJSHookPush(this.el, topEvent, { id: firstChild.id, _overran: true }, () => {
- pendingOp = null;
- });
- });
- let onFirstChildAtTop = this.throttle(throttleInterval, (topEvent, firstChild) => {
- pendingOp = () => firstChild.scrollIntoView({ block: "start" });
- this.liveSocket.execJSHookPush(this.el, topEvent, { id: firstChild.id }, () => {
- pendingOp = null;
- if (!isWithinViewport(firstChild)) {
- firstChild.scrollIntoView({ block: "start" });
- }
- });
- });
- let onLastChildAtBottom = this.throttle(throttleInterval, (bottomEvent, lastChild) => {
- pendingOp = () => lastChild.scrollIntoView({ block: "end" });
- this.liveSocket.execJSHookPush(this.el, bottomEvent, { id: lastChild.id }, () => {
- pendingOp = null;
- if (!isWithinViewport(lastChild)) {
- lastChild.scrollIntoView({ block: "end" });
- }
- });
- });
- this.onScroll = (e2) => {
- let scrollNow = scrollTop();
- if (pendingOp) {
- scrollBefore = scrollNow;
- return pendingOp();
- }
- let rect = this.el.getBoundingClientRect();
- let topEvent = this.el.getAttribute(this.liveSocket.binding("viewport-top"));
- let bottomEvent = this.el.getAttribute(this.liveSocket.binding("viewport-bottom"));
- let lastChild = this.el.lastElementChild;
- let firstChild = this.el.firstElementChild;
- let isScrollingUp = scrollNow < scrollBefore;
- let isScrollingDown = scrollNow > scrollBefore;
- if (isScrollingUp && topEvent && !topOverran && rect.top >= 0) {
- topOverran = true;
- onTopOverrun(topEvent, firstChild);
- } else if (isScrollingDown && topOverran && rect.top <= 0) {
- topOverran = false;
- }
- if (topEvent && isScrollingUp && isAtViewportTop(firstChild)) {
- onFirstChildAtTop(topEvent, firstChild);
- } else if (bottomEvent && isScrollingDown && isAtViewportBottom(lastChild)) {
- onLastChildAtBottom(bottomEvent, lastChild);
- }
- scrollBefore = scrollNow;
- };
- window.addEventListener("scroll", this.onScroll);
- },
- destroyed() {
- window.removeEventListener("scroll", this.onScroll);
- },
- throttle(interval, callback) {
- let lastCallAt = 0;
- let timer;
- return (...args) => {
- let now = Date.now();
- let remainingTime = interval - (now - lastCallAt);
- if (remainingTime <= 0 || remainingTime > interval) {
- if (timer) {
- clearTimeout(timer);
- timer = null;
- }
- lastCallAt = now;
- callback(...args);
- } else if (!timer) {
- timer = setTimeout(() => {
- lastCallAt = Date.now();
- timer = null;
- callback(...args);
- }, remainingTime);
- }
- };
- }
- };
- var hooks_default = Hooks;
- var DOMPostMorphRestorer = class {
- constructor(containerBefore, containerAfter, updateType) {
- let idsBefore = /* @__PURE__ */ new Set();
- let idsAfter = new Set([...containerAfter.children].map((child) => child.id));
- let elementsToModify = [];
- Array.from(containerBefore.children).forEach((child) => {
- if (child.id) {
- idsBefore.add(child.id);
- if (idsAfter.has(child.id)) {
- let previousElementId = child.previousElementSibling && child.previousElementSibling.id;
- elementsToModify.push({ elementId: child.id, previousElementId });
- }
- }
- });
- this.containerId = containerAfter.id;
- this.updateType = updateType;
- this.elementsToModify = elementsToModify;
- this.elementIdsToAdd = [...idsAfter].filter((id) => !idsBefore.has(id));
- }
- perform() {
- let container = dom_default.byId(this.containerId);
- this.elementsToModify.forEach((elementToModify) => {
- if (elementToModify.previousElementId) {
- maybe(document.getElementById(elementToModify.previousElementId), (previousElem) => {
- maybe(document.getElementById(elementToModify.elementId), (elem) => {
- let isInRightPlace = elem.previousElementSibling && elem.previousElementSibling.id == previousElem.id;
- if (!isInRightPlace) {
- previousElem.insertAdjacentElement("afterend", elem);
- }
- });
- });
- } else {
- maybe(document.getElementById(elementToModify.elementId), (elem) => {
- let isInRightPlace = elem.previousElementSibling == null;
- if (!isInRightPlace) {
- container.insertAdjacentElement("afterbegin", elem);
- }
- });
- }
- });
- if (this.updateType == "prepend") {
- this.elementIdsToAdd.reverse().forEach((elemId) => {
- maybe(document.getElementById(elemId), (elem) => container.insertAdjacentElement("afterbegin", elem));
- });
- }
- }
- };
- var DOCUMENT_FRAGMENT_NODE = 11;
- function morphAttrs(fromNode, toNode) {
- var toNodeAttrs = toNode.attributes;
- var attr;
- var attrName;
- var attrNamespaceURI;
- var attrValue;
- var fromValue;
- if (toNode.nodeType === DOCUMENT_FRAGMENT_NODE || fromNode.nodeType === DOCUMENT_FRAGMENT_NODE) {
- return;
- }
- for (var i2 = toNodeAttrs.length - 1; i2 >= 0; i2--) {
- attr = toNodeAttrs[i2];
- attrName = attr.name;
- attrNamespaceURI = attr.namespaceURI;
- attrValue = attr.value;
- if (attrNamespaceURI) {
- attrName = attr.localName || attrName;
- fromValue = fromNode.getAttributeNS(attrNamespaceURI, attrName);
- if (fromValue !== attrValue) {
- if (attr.prefix === "xmlns") {
- attrName = attr.name;
- }
- fromNode.setAttributeNS(attrNamespaceURI, attrName, attrValue);
- }
- } else {
- fromValue = fromNode.getAttribute(attrName);
- if (fromValue !== attrValue) {
- fromNode.setAttribute(attrName, attrValue);
- }
- }
- }
- var fromNodeAttrs = fromNode.attributes;
- for (var d2 = fromNodeAttrs.length - 1; d2 >= 0; d2--) {
- attr = fromNodeAttrs[d2];
- attrName = attr.name;
- attrNamespaceURI = attr.namespaceURI;
- if (attrNamespaceURI) {
- attrName = attr.localName || attrName;
- if (!toNode.hasAttributeNS(attrNamespaceURI, attrName)) {
- fromNode.removeAttributeNS(attrNamespaceURI, attrName);
- }
- } else {
- if (!toNode.hasAttribute(attrName)) {
- fromNode.removeAttribute(attrName);
- }
- }
- }
- }
- var range;
- var NS_XHTML = "http://www.w3.org/1999/xhtml";
- var doc = typeof document === "undefined" ? void 0 : document;
- var HAS_TEMPLATE_SUPPORT = !!doc && "content" in doc.createElement("template");
- var HAS_RANGE_SUPPORT = !!doc && doc.createRange && "createContextualFragment" in doc.createRange();
- function createFragmentFromTemplate(str) {
- var template = doc.createElement("template");
- template.innerHTML = str;
- return template.content.childNodes[0];
- }
- function createFragmentFromRange(str) {
- if (!range) {
- range = doc.createRange();
- range.selectNode(doc.body);
- }
- var fragment = range.createContextualFragment(str);
- return fragment.childNodes[0];
- }
- function createFragmentFromWrap(str) {
- var fragment = doc.createElement("body");
- fragment.innerHTML = str;
- return fragment.childNodes[0];
- }
- function toElement(str) {
- str = str.trim();
- if (HAS_TEMPLATE_SUPPORT) {
- return createFragmentFromTemplate(str);
- } else if (HAS_RANGE_SUPPORT) {
- return createFragmentFromRange(str);
- }
- return createFragmentFromWrap(str);
- }
- function compareNodeNames(fromEl, toEl) {
- var fromNodeName = fromEl.nodeName;
- var toNodeName = toEl.nodeName;
- var fromCodeStart, toCodeStart;
- if (fromNodeName === toNodeName) {
- return true;
- }
- fromCodeStart = fromNodeName.charCodeAt(0);
- toCodeStart = toNodeName.charCodeAt(0);
- if (fromCodeStart <= 90 && toCodeStart >= 97) {
- return fromNodeName === toNodeName.toUpperCase();
- } else if (toCodeStart <= 90 && fromCodeStart >= 97) {
- return toNodeName === fromNodeName.toUpperCase();
- } else {
- return false;
- }
- }
- function createElementNS(name, namespaceURI) {
- return !namespaceURI || namespaceURI === NS_XHTML ? doc.createElement(name) : doc.createElementNS(namespaceURI, name);
- }
- function moveChildren(fromEl, toEl) {
- var curChild = fromEl.firstChild;
- while (curChild) {
- var nextChild = curChild.nextSibling;
- toEl.appendChild(curChild);
- curChild = nextChild;
- }
- return toEl;
- }
- function syncBooleanAttrProp(fromEl, toEl, name) {
- if (fromEl[name] !== toEl[name]) {
- fromEl[name] = toEl[name];
- if (fromEl[name]) {
- fromEl.setAttribute(name, "");
- } else {
- fromEl.removeAttribute(name);
- }
- }
- }
- var specialElHandlers = {
- OPTION: function(fromEl, toEl) {
- var parentNode = fromEl.parentNode;
- if (parentNode) {
- var parentName = parentNode.nodeName.toUpperCase();
- if (parentName === "OPTGROUP") {
- parentNode = parentNode.parentNode;
- parentName = parentNode && parentNode.nodeName.toUpperCase();
- }
- if (parentName === "SELECT" && !parentNode.hasAttribute("multiple")) {
- if (fromEl.hasAttribute("selected") && !toEl.selected) {
- fromEl.setAttribute("selected", "selected");
- fromEl.removeAttribute("selected");
- }
- parentNode.selectedIndex = -1;
- }
- }
- syncBooleanAttrProp(fromEl, toEl, "selected");
- },
- INPUT: function(fromEl, toEl) {
- syncBooleanAttrProp(fromEl, toEl, "checked");
- syncBooleanAttrProp(fromEl, toEl, "disabled");
- if (fromEl.value !== toEl.value) {
- fromEl.value = toEl.value;
- }
- if (!toEl.hasAttribute("value")) {
- fromEl.removeAttribute("value");
- }
- },
- TEXTAREA: function(fromEl, toEl) {
- var newValue = toEl.value;
- if (fromEl.value !== newValue) {
- fromEl.value = newValue;
- }
- var firstChild = fromEl.firstChild;
- if (firstChild) {
- var oldValue = firstChild.nodeValue;
- if (oldValue == newValue || !newValue && oldValue == fromEl.placeholder) {
- return;
- }
- firstChild.nodeValue = newValue;
- }
- },
- SELECT: function(fromEl, toEl) {
- if (!toEl.hasAttribute("multiple")) {
- var selectedIndex = -1;
- var i2 = 0;
- var curChild = fromEl.firstChild;
- var optgroup;
- var nodeName;
- while (curChild) {
- nodeName = curChild.nodeName && curChild.nodeName.toUpperCase();
- if (nodeName === "OPTGROUP") {
- optgroup = curChild;
- curChild = optgroup.firstChild;
- } else {
- if (nodeName === "OPTION") {
- if (curChild.hasAttribute("selected")) {
- selectedIndex = i2;
- break;
- }
- i2++;
- }
- curChild = curChild.nextSibling;
- if (!curChild && optgroup) {
- curChild = optgroup.nextSibling;
- optgroup = null;
- }
- }
- }
- fromEl.selectedIndex = selectedIndex;
- }
- }
- };
- var ELEMENT_NODE = 1;
- var DOCUMENT_FRAGMENT_NODE$1 = 11;
- var TEXT_NODE = 3;
- var COMMENT_NODE = 8;
- function noop() {
- }
- function defaultGetNodeKey(node) {
- if (node) {
- return node.getAttribute && node.getAttribute("id") || node.id;
- }
- }
- function morphdomFactory(morphAttrs2) {
- return function morphdom2(fromNode, toNode, options) {
- if (!options) {
- options = {};
- }
- if (typeof toNode === "string") {
- if (fromNode.nodeName === "#document" || fromNode.nodeName === "HTML" || fromNode.nodeName === "BODY") {
- var toNodeHtml = toNode;
- toNode = doc.createElement("html");
- toNode.innerHTML = toNodeHtml;
- } else {
- toNode = toElement(toNode);
- }
- } else if (toNode.nodeType === DOCUMENT_FRAGMENT_NODE$1) {
- toNode = toNode.firstElementChild;
- }
- var getNodeKey = options.getNodeKey || defaultGetNodeKey;
- var onBeforeNodeAdded = options.onBeforeNodeAdded || noop;
- var onNodeAdded = options.onNodeAdded || noop;
- var onBeforeElUpdated = options.onBeforeElUpdated || noop;
- var onElUpdated = options.onElUpdated || noop;
- var onBeforeNodeDiscarded = options.onBeforeNodeDiscarded || noop;
- var onNodeDiscarded = options.onNodeDiscarded || noop;
- var onBeforeElChildrenUpdated = options.onBeforeElChildrenUpdated || noop;
- var skipFromChildren = options.skipFromChildren || noop;
- var addChild = options.addChild || function(parent, child) {
- return parent.appendChild(child);
- };
- var childrenOnly = options.childrenOnly === true;
- var fromNodesLookup = /* @__PURE__ */ Object.create(null);
- var keyedRemovalList = [];
- function addKeyedRemoval(key) {
- keyedRemovalList.push(key);
- }
- function walkDiscardedChildNodes(node, skipKeyedNodes) {
- if (node.nodeType === ELEMENT_NODE) {
- var curChild = node.firstChild;
- while (curChild) {
- var key = void 0;
- if (skipKeyedNodes && (key = getNodeKey(curChild))) {
- addKeyedRemoval(key);
- } else {
- onNodeDiscarded(curChild);
- if (curChild.firstChild) {
- walkDiscardedChildNodes(curChild, skipKeyedNodes);
- }
- }
- curChild = curChild.nextSibling;
- }
- }
- }
- function removeNode(node, parentNode, skipKeyedNodes) {
- if (onBeforeNodeDiscarded(node) === false) {
- return;
- }
- if (parentNode) {
- parentNode.removeChild(node);
- }
- onNodeDiscarded(node);
- walkDiscardedChildNodes(node, skipKeyedNodes);
- }
- function indexTree(node) {
- if (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE$1) {
- var curChild = node.firstChild;
- while (curChild) {
- var key = getNodeKey(curChild);
- if (key) {
- fromNodesLookup[key] = curChild;
- }
- indexTree(curChild);
- curChild = curChild.nextSibling;
- }
- }
- }
- indexTree(fromNode);
- function handleNodeAdded(el) {
- onNodeAdded(el);
- var curChild = el.firstChild;
- while (curChild) {
- var nextSibling = curChild.nextSibling;
- var key = getNodeKey(curChild);
- if (key) {
- var unmatchedFromEl = fromNodesLookup[key];
- if (unmatchedFromEl && compareNodeNames(curChild, unmatchedFromEl)) {
- curChild.parentNode.replaceChild(unmatchedFromEl, curChild);
- morphEl(unmatchedFromEl, curChild);
- } else {
- handleNodeAdded(curChild);
- }
- } else {
- handleNodeAdded(curChild);
- }
- curChild = nextSibling;
- }
- }
- function cleanupFromEl(fromEl, curFromNodeChild, curFromNodeKey) {
- while (curFromNodeChild) {
- var fromNextSibling = curFromNodeChild.nextSibling;
- if (curFromNodeKey = getNodeKey(curFromNodeChild)) {
- addKeyedRemoval(curFromNodeKey);
- } else {
- removeNode(curFromNodeChild, fromEl, true);
- }
- curFromNodeChild = fromNextSibling;
- }
- }
- function morphEl(fromEl, toEl, childrenOnly2) {
- var toElKey = getNodeKey(toEl);
- if (toElKey) {
- delete fromNodesLookup[toElKey];
- }
- if (!childrenOnly2) {
- if (onBeforeElUpdated(fromEl, toEl) === false) {
- return;
- }
- morphAttrs2(fromEl, toEl);
- onElUpdated(fromEl);
- if (onBeforeElChildrenUpdated(fromEl, toEl) === false) {
- return;
- }
- }
- if (fromEl.nodeName !== "TEXTAREA") {
- morphChildren(fromEl, toEl);
- } else {
- specialElHandlers.TEXTAREA(fromEl, toEl);
- }
- }
- function morphChildren(fromEl, toEl) {
- var skipFrom = skipFromChildren(fromEl);
- var curToNodeChild = toEl.firstChild;
- var curFromNodeChild = fromEl.firstChild;
- var curToNodeKey;
- var curFromNodeKey;
- var fromNextSibling;
- var toNextSibling;
- var matchingFromEl;
- outer:
- while (curToNodeChild) {
- toNextSibling = curToNodeChild.nextSibling;
- curToNodeKey = getNodeKey(curToNodeChild);
- while (!skipFrom && curFromNodeChild) {
- fromNextSibling = curFromNodeChild.nextSibling;
- if (curToNodeChild.isSameNode && curToNodeChild.isSameNode(curFromNodeChild)) {
- curToNodeChild = toNextSibling;
- curFromNodeChild = fromNextSibling;
- continue outer;
- }
- curFromNodeKey = getNodeKey(curFromNodeChild);
- var curFromNodeType = curFromNodeChild.nodeType;
- var isCompatible = void 0;
- if (curFromNodeType === curToNodeChild.nodeType) {
- if (curFromNodeType === ELEMENT_NODE) {
- if (curToNodeKey) {
- if (curToNodeKey !== curFromNodeKey) {
- if (matchingFromEl = fromNodesLookup[curToNodeKey]) {
- if (fromNextSibling === matchingFromEl) {
- isCompatible = false;
- } else {
- fromEl.insertBefore(matchingFromEl, curFromNodeChild);
- if (curFromNodeKey) {
- addKeyedRemoval(curFromNodeKey);
- } else {
- removeNode(curFromNodeChild, fromEl, true);
- }
- curFromNodeChild = matchingFromEl;
- }
- } else {
- isCompatible = false;
- }
- }
- } else if (curFromNodeKey) {
- isCompatible = false;
- }
- isCompatible = isCompatible !== false && compareNodeNames(curFromNodeChild, curToNodeChild);
- if (isCompatible) {
- morphEl(curFromNodeChild, curToNodeChild);
- }
- } else if (curFromNodeType === TEXT_NODE || curFromNodeType == COMMENT_NODE) {
- isCompatible = true;
- if (curFromNodeChild.nodeValue !== curToNodeChild.nodeValue) {
- curFromNodeChild.nodeValue = curToNodeChild.nodeValue;
- }
- }
- }
- if (isCompatible) {
- curToNodeChild = toNextSibling;
- curFromNodeChild = fromNextSibling;
- continue outer;
- }
- if (curFromNodeKey) {
- addKeyedRemoval(curFromNodeKey);
- } else {
- removeNode(curFromNodeChild, fromEl, true);
- }
- curFromNodeChild = fromNextSibling;
- }
- if (curToNodeKey && (matchingFromEl = fromNodesLookup[curToNodeKey]) && compareNodeNames(matchingFromEl, curToNodeChild)) {
- if (!skipFrom) {
- addChild(fromEl, matchingFromEl);
- }
- morphEl(matchingFromEl, curToNodeChild);
- } else {
- var onBeforeNodeAddedResult = onBeforeNodeAdded(curToNodeChild);
- if (onBeforeNodeAddedResult !== false) {
- if (onBeforeNodeAddedResult) {
- curToNodeChild = onBeforeNodeAddedResult;
- }
- if (curToNodeChild.actualize) {
- curToNodeChild = curToNodeChild.actualize(fromEl.ownerDocument || doc);
- }
- addChild(fromEl, curToNodeChild);
- handleNodeAdded(curToNodeChild);
- }
- }
- curToNodeChild = toNextSibling;
- curFromNodeChild = fromNextSibling;
- }
- cleanupFromEl(fromEl, curFromNodeChild, curFromNodeKey);
- var specialElHandler = specialElHandlers[fromEl.nodeName];
- if (specialElHandler) {
- specialElHandler(fromEl, toEl);
- }
- }
- var morphedNode = fromNode;
- var morphedNodeType = morphedNode.nodeType;
- var toNodeType = toNode.nodeType;
- if (!childrenOnly) {
- if (morphedNodeType === ELEMENT_NODE) {
- if (toNodeType === ELEMENT_NODE) {
- if (!compareNodeNames(fromNode, toNode)) {
- onNodeDiscarded(fromNode);
- morphedNode = moveChildren(fromNode, createElementNS(toNode.nodeName, toNode.namespaceURI));
- }
- } else {
- morphedNode = toNode;
- }
- } else if (morphedNodeType === TEXT_NODE || morphedNodeType === COMMENT_NODE) {
- if (toNodeType === morphedNodeType) {
- if (morphedNode.nodeValue !== toNode.nodeValue) {
- morphedNode.nodeValue = toNode.nodeValue;
- }
- return morphedNode;
- } else {
- morphedNode = toNode;
- }
- }
- }
- if (morphedNode === toNode) {
- onNodeDiscarded(fromNode);
- } else {
- if (toNode.isSameNode && toNode.isSameNode(morphedNode)) {
- return;
- }
- morphEl(morphedNode, toNode, childrenOnly);
- if (keyedRemovalList) {
- for (var i2 = 0, len = keyedRemovalList.length; i2 < len; i2++) {
- var elToRemove = fromNodesLookup[keyedRemovalList[i2]];
- if (elToRemove) {
- removeNode(elToRemove, elToRemove.parentNode, false);
- }
- }
- }
- }
- if (!childrenOnly && morphedNode !== fromNode && fromNode.parentNode) {
- if (morphedNode.actualize) {
- morphedNode = morphedNode.actualize(fromNode.ownerDocument || doc);
- }
- fromNode.parentNode.replaceChild(morphedNode, fromNode);
- }
- return morphedNode;
- };
- }
- var morphdom = morphdomFactory(morphAttrs);
- var morphdom_esm_default = morphdom;
- var DOMPatch = class {
- static patchEl(fromEl, toEl, activeElement) {
- morphdom_esm_default(fromEl, toEl, {
- childrenOnly: false,
- onBeforeElUpdated: (fromEl2, toEl2) => {
- if (activeElement && activeElement.isSameNode(fromEl2) && dom_default.isFormInput(fromEl2)) {
- dom_default.mergeFocusedInput(fromEl2, toEl2);
- return false;
- }
- }
- });
- }
- constructor(view, container, id, html, streams, targetCID) {
- this.view = view;
- this.liveSocket = view.liveSocket;
- this.container = container;
- this.id = id;
- this.rootID = view.root.id;
- this.html = html;
- this.streams = streams;
- this.streamInserts = {};
- this.targetCID = targetCID;
- this.cidPatch = isCid(this.targetCID);
- this.pendingRemoves = [];
- this.phxRemove = this.liveSocket.binding("remove");
- this.callbacks = {
- beforeadded: [],
- beforeupdated: [],
- beforephxChildAdded: [],
- afteradded: [],
- afterupdated: [],
- afterdiscarded: [],
- afterphxChildAdded: [],
- aftertransitionsDiscarded: []
- };
- }
- before(kind, callback) {
- this.callbacks[`before${kind}`].push(callback);
- }
- after(kind, callback) {
- this.callbacks[`after${kind}`].push(callback);
- }
- trackBefore(kind, ...args) {
- this.callbacks[`before${kind}`].forEach((callback) => callback(...args));
- }
- trackAfter(kind, ...args) {
- this.callbacks[`after${kind}`].forEach((callback) => callback(...args));
- }
- markPrunableContentForRemoval() {
- let phxUpdate = this.liveSocket.binding(PHX_UPDATE);
- dom_default.all(this.container, `[${phxUpdate}=${PHX_STREAM}]`, (el) => el.innerHTML = "");
- dom_default.all(this.container, `[${phxUpdate}=append] > *, [${phxUpdate}=prepend] > *`, (el) => {
- el.setAttribute(PHX_PRUNE, "");
- });
- }
- perform() {
- let { view, liveSocket: liveSocket2, container, html } = this;
- let targetContainer = this.isCIDPatch() ? this.targetCIDContainer(html) : container;
- if (this.isCIDPatch() && !targetContainer) {
- return;
- }
- let focused = liveSocket2.getActiveElement();
- let { selectionStart, selectionEnd } = focused && dom_default.hasSelectionRange(focused) ? focused : {};
- let phxUpdate = liveSocket2.binding(PHX_UPDATE);
- let phxFeedbackFor = liveSocket2.binding(PHX_FEEDBACK_FOR);
- let disableWith = liveSocket2.binding(PHX_DISABLE_WITH);
- let phxViewportTop = liveSocket2.binding(PHX_VIEWPORT_TOP);
- let phxViewportBottom = liveSocket2.binding(PHX_VIEWPORT_BOTTOM);
- let phxTriggerExternal = liveSocket2.binding(PHX_TRIGGER_ACTION);
- let added = [];
- let trackedInputs = [];
- let updates = [];
- let appendPrependUpdates = [];
- let externalFormTriggered = null;
- let diffHTML = liveSocket2.time("premorph container prep", () => {
- return this.buildDiffHTML(container, html, phxUpdate, targetContainer);
- });
- this.trackBefore("added", container);
- this.trackBefore("updated", container, container);
- liveSocket2.time("morphdom", () => {
- this.streams.forEach(([ref, inserts, deleteIds, reset]) => {
- Object.entries(inserts).forEach(([key, [streamAt, limit]]) => {
- this.streamInserts[key] = { ref, streamAt, limit };
- });
- if (reset !== void 0) {
- dom_default.all(container, `[${PHX_STREAM_REF}="${ref}"]`, (child) => {
- if (!inserts[child.id]) {
- this.removeStreamChildElement(child);
- }
- });
- }
- deleteIds.forEach((id) => {
- let child = container.querySelector(`[id="${id}"]`);
- if (child) {
- this.removeStreamChildElement(child);
- }
- });
- });
- morphdom_esm_default(targetContainer, diffHTML, {
- childrenOnly: targetContainer.getAttribute(PHX_COMPONENT) === null,
- getNodeKey: (node) => {
- return dom_default.isPhxDestroyed(node) ? null : node.id;
- },
- skipFromChildren: (from) => {
- return from.getAttribute(phxUpdate) === PHX_STREAM;
- },
- addChild: (parent, child) => {
- let { ref, streamAt, limit } = this.getStreamInsert(child);
- if (ref === void 0) {
- return parent.appendChild(child);
- }
- dom_default.putSticky(child, PHX_STREAM_REF, (el) => el.setAttribute(PHX_STREAM_REF, ref));
- if (streamAt === 0) {
- parent.insertAdjacentElement("afterbegin", child);
- } else if (streamAt === -1) {
- parent.appendChild(child);
- } else if (streamAt > 0) {
- let sibling = Array.from(parent.children)[streamAt];
- parent.insertBefore(child, sibling);
- }
- let children = limit !== null && Array.from(parent.children);
- let childrenToRemove = [];
- if (limit && limit < 0 && children.length > limit * -1) {
- childrenToRemove = children.slice(0, children.length + limit);
- } else if (limit && limit >= 0 && children.length > limit) {
- childrenToRemove = children.slice(limit);
- }
- childrenToRemove.forEach((removeChild) => {
- if (!this.streamInserts[removeChild.id]) {
- this.removeStreamChildElement(removeChild);
- }
- });
- },
- onBeforeNodeAdded: (el) => {
- dom_default.maybeAddPrivateHooks(el, phxViewportTop, phxViewportBottom);
- this.trackBefore("added", el);
- return el;
- },
- onNodeAdded: (el) => {
- if (el.getAttribute) {
- this.maybeReOrderStream(el);
- }
- if (el instanceof HTMLImageElement && el.srcset) {
- el.srcset = el.srcset;
- } else if (el instanceof HTMLVideoElement && el.autoplay) {
- el.play();
- }
- if (dom_default.isNowTriggerFormExternal(el, phxTriggerExternal)) {
- externalFormTriggered = el;
- }
- if (el.getAttribute && el.getAttribute("name") && dom_default.isFormInput(el)) {
- trackedInputs.push(el);
- }
- if (dom_default.isPhxChild(el) && view.ownsElement(el) || dom_default.isPhxSticky(el) && view.ownsElement(el.parentNode)) {
- this.trackAfter("phxChildAdded", el);
- }
- added.push(el);
- },
- onNodeDiscarded: (el) => this.onNodeDiscarded(el),
- onBeforeNodeDiscarded: (el) => {
- if (el.getAttribute && el.getAttribute(PHX_PRUNE) !== null) {
- return true;
- }
- if (el.parentElement !== null && el.id && dom_default.isPhxUpdate(el.parentElement, phxUpdate, [PHX_STREAM, "append", "prepend"])) {
- return false;
- }
- if (this.maybePendingRemove(el)) {
- return false;
- }
- if (this.skipCIDSibling(el)) {
- return false;
- }
- return true;
- },
- onElUpdated: (el) => {
- if (dom_default.isNowTriggerFormExternal(el, phxTriggerExternal)) {
- externalFormTriggered = el;
- }
- updates.push(el);
- this.maybeReOrderStream(el);
- },
- onBeforeElUpdated: (fromEl, toEl) => {
- dom_default.maybeAddPrivateHooks(toEl, phxViewportTop, phxViewportBottom);
- dom_default.cleanChildNodes(toEl, phxUpdate);
- if (this.skipCIDSibling(toEl)) {
- return false;
- }
- if (dom_default.isPhxSticky(fromEl)) {
- return false;
- }
- if (dom_default.isIgnored(fromEl, phxUpdate) || fromEl.form && fromEl.form.isSameNode(externalFormTriggered)) {
- this.trackBefore("updated", fromEl, toEl);
- dom_default.mergeAttrs(fromEl, toEl, { isIgnored: true });
- updates.push(fromEl);
- dom_default.applyStickyOperations(fromEl);
- return false;
- }
- if (fromEl.type === "number" && (fromEl.validity && fromEl.validity.badInput)) {
- return false;
- }
- if (!dom_default.syncPendingRef(fromEl, toEl, disableWith)) {
- if (dom_default.isUploadInput(fromEl)) {
- this.trackBefore("updated", fromEl, toEl);
- updates.push(fromEl);
- }
- dom_default.applyStickyOperations(fromEl);
- return false;
- }
- if (dom_default.isPhxChild(toEl)) {
- let prevSession = fromEl.getAttribute(PHX_SESSION);
- dom_default.mergeAttrs(fromEl, toEl, { exclude: [PHX_STATIC] });
- if (prevSession !== "") {
- fromEl.setAttribute(PHX_SESSION, prevSession);
- }
- fromEl.setAttribute(PHX_ROOT_ID, this.rootID);
- dom_default.applyStickyOperations(fromEl);
- return false;
- }
- dom_default.copyPrivates(toEl, fromEl);
- let isFocusedFormEl = focused && fromEl.isSameNode(focused) && dom_default.isFormInput(fromEl);
- if (isFocusedFormEl && fromEl.type !== "hidden") {
- this.trackBefore("updated", fromEl, toEl);
- dom_default.mergeFocusedInput(fromEl, toEl);
- dom_default.syncAttrsToProps(fromEl);
- updates.push(fromEl);
- dom_default.applyStickyOperations(fromEl);
- trackedInputs.push(fromEl);
- return false;
- } else {
- if (dom_default.isPhxUpdate(toEl, phxUpdate, ["append", "prepend"])) {
- appendPrependUpdates.push(new DOMPostMorphRestorer(fromEl, toEl, toEl.getAttribute(phxUpdate)));
- }
- dom_default.syncAttrsToProps(toEl);
- dom_default.applyStickyOperations(toEl);
- if (toEl.getAttribute("name") && dom_default.isFormInput(toEl)) {
- trackedInputs.push(toEl);
- }
- this.trackBefore("updated", fromEl, toEl);
- return true;
- }
- }
- });
- });
- if (liveSocket2.isDebugEnabled()) {
- detectDuplicateIds();
- }
- if (appendPrependUpdates.length > 0) {
- liveSocket2.time("post-morph append/prepend restoration", () => {
- appendPrependUpdates.forEach((update) => update.perform());
- });
- }
- trackedInputs.forEach((input) => {
- dom_default.maybeHideFeedback(targetContainer, input, phxFeedbackFor);
- });
- liveSocket2.silenceEvents(() => dom_default.restoreFocus(focused, selectionStart, selectionEnd));
- dom_default.dispatchEvent(document, "phx:update");
- added.forEach((el) => this.trackAfter("added", el));
- updates.forEach((el) => this.trackAfter("updated", el));
- this.transitionPendingRemoves();
- if (externalFormTriggered) {
- liveSocket2.unload();
- Object.getPrototypeOf(externalFormTriggered).submit.call(externalFormTriggered);
- }
- return true;
- }
- onNodeDiscarded(el) {
- if (dom_default.isPhxChild(el) || dom_default.isPhxSticky(el)) {
- this.liveSocket.destroyViewByEl(el);
- }
- this.trackAfter("discarded", el);
- }
- maybePendingRemove(node) {
- if (node.getAttribute && node.getAttribute(this.phxRemove) !== null) {
- this.pendingRemoves.push(node);
- return true;
- } else {
- return false;
- }
- }
- removeStreamChildElement(child) {
- if (!this.maybePendingRemove(child)) {
- child.remove();
- this.onNodeDiscarded(child);
- }
- }
- getStreamInsert(el) {
- let insert = el.id ? this.streamInserts[el.id] : {};
- return insert || {};
- }
- maybeReOrderStream(el) {
- let { ref, streamAt, limit } = this.getStreamInsert(el);
- if (streamAt === void 0) {
- return;
- }
- dom_default.putSticky(el, PHX_STREAM_REF, (el2) => el2.setAttribute(PHX_STREAM_REF, ref));
- if (streamAt === 0) {
- el.parentElement.insertBefore(el, el.parentElement.firstElementChild);
- } else if (streamAt > 0) {
- let children = Array.from(el.parentElement.children);
- let oldIndex = children.indexOf(el);
- if (streamAt >= children.length - 1) {
- el.parentElement.appendChild(el);
- } else {
- let sibling = children[streamAt];
- if (oldIndex > streamAt) {
- el.parentElement.insertBefore(el, sibling);
- } else {
- el.parentElement.insertBefore(el, sibling.nextElementSibling);
- }
- }
- }
- }
- transitionPendingRemoves() {
- let { pendingRemoves, liveSocket: liveSocket2 } = this;
- if (pendingRemoves.length > 0) {
- liveSocket2.transitionRemoves(pendingRemoves);
- liveSocket2.requestDOMUpdate(() => {
- pendingRemoves.forEach((el) => {
- let child = dom_default.firstPhxChild(el);
- if (child) {
- liveSocket2.destroyViewByEl(child);
- }
- el.remove();
- });
- this.trackAfter("transitionsDiscarded", pendingRemoves);
- });
- }
- }
- isCIDPatch() {
- return this.cidPatch;
- }
- skipCIDSibling(el) {
- return el.nodeType === Node.ELEMENT_NODE && el.getAttribute(PHX_SKIP) !== null;
- }
- targetCIDContainer(html) {
- if (!this.isCIDPatch()) {
- return;
- }
- let [first, ...rest] = dom_default.findComponentNodeList(this.container, this.targetCID);
- if (rest.length === 0 && dom_default.childNodeLength(html) === 1) {
- return first;
- } else {
- return first && first.parentNode;
- }
- }
- buildDiffHTML(container, html, phxUpdate, targetContainer) {
- let isCIDPatch = this.isCIDPatch();
- let isCIDWithSingleRoot = isCIDPatch && targetContainer.getAttribute(PHX_COMPONENT) === this.targetCID.toString();
- if (!isCIDPatch || isCIDWithSingleRoot) {
- return html;
- } else {
- let diffContainer = null;
- let template = document.createElement("template");
- diffContainer = dom_default.cloneNode(targetContainer);
- let [firstComponent, ...rest] = dom_default.findComponentNodeList(diffContainer, this.targetCID);
- template.innerHTML = html;
- rest.forEach((el) => el.remove());
- Array.from(diffContainer.childNodes).forEach((child) => {
- if (child.id && child.nodeType === Node.ELEMENT_NODE && child.getAttribute(PHX_COMPONENT) !== this.targetCID.toString()) {
- child.setAttribute(PHX_SKIP, "");
- child.innerHTML = "";
- }
- });
- Array.from(template.content.childNodes).forEach((el) => diffContainer.insertBefore(el, firstComponent));
- firstComponent.remove();
- return diffContainer.outerHTML;
- }
- }
- indexOf(parent, child) {
- return Array.from(parent.children).indexOf(child);
- }
- };
- var Rendered = class {
- static extract(diff) {
- let { [REPLY]: reply, [EVENTS]: events, [TITLE]: title } = diff;
- delete diff[REPLY];
- delete diff[EVENTS];
- delete diff[TITLE];
- return { diff, title, reply: reply || null, events: events || [] };
- }
- constructor(viewId, rendered) {
- this.viewId = viewId;
- this.rendered = {};
- this.mergeDiff(rendered);
- }
- parentViewId() {
- return this.viewId;
- }
- toString(onlyCids) {
- let [str, streams] = this.recursiveToString(this.rendered, this.rendered[COMPONENTS], onlyCids);
- return [str, streams];
- }
- recursiveToString(rendered, components = rendered[COMPONENTS], onlyCids) {
- onlyCids = onlyCids ? new Set(onlyCids) : null;
- let output = { buffer: "", components, onlyCids, streams: /* @__PURE__ */ new Set() };
- this.toOutputBuffer(rendered, null, output);
- return [output.buffer, output.streams];
- }
- componentCIDs(diff) {
- return Object.keys(diff[COMPONENTS] || {}).map((i2) => parseInt(i2));
- }
- isComponentOnlyDiff(diff) {
- if (!diff[COMPONENTS]) {
- return false;
- }
- return Object.keys(diff).length === 1;
- }
- getComponent(diff, cid) {
- return diff[COMPONENTS][cid];
- }
- mergeDiff(diff) {
- let newc = diff[COMPONENTS];
- let cache = {};
- delete diff[COMPONENTS];
- this.rendered = this.mutableMerge(this.rendered, diff);
- this.rendered[COMPONENTS] = this.rendered[COMPONENTS] || {};
- if (newc) {
- let oldc = this.rendered[COMPONENTS];
- for (let cid in newc) {
- newc[cid] = this.cachedFindComponent(cid, newc[cid], oldc, newc, cache);
- }
- for (let cid in newc) {
- oldc[cid] = newc[cid];
- }
- diff[COMPONENTS] = newc;
- }
- }
- cachedFindComponent(cid, cdiff, oldc, newc, cache) {
- if (cache[cid]) {
- return cache[cid];
- } else {
- let ndiff, stat, scid = cdiff[STATIC];
- if (isCid(scid)) {
- let tdiff;
- if (scid > 0) {
- tdiff = this.cachedFindComponent(scid, newc[scid], oldc, newc, cache);
- } else {
- tdiff = oldc[-scid];
- }
- stat = tdiff[STATIC];
- ndiff = this.cloneMerge(tdiff, cdiff);
- ndiff[STATIC] = stat;
- } else {
- ndiff = cdiff[STATIC] !== void 0 ? cdiff : this.cloneMerge(oldc[cid] || {}, cdiff);
- }
- cache[cid] = ndiff;
- return ndiff;
- }
- }
- mutableMerge(target, source) {
- if (source[STATIC] !== void 0) {
- return source;
- } else {
- this.doMutableMerge(target, source);
- return target;
- }
- }
- doMutableMerge(target, source) {
- for (let key in source) {
- let val = source[key];
- let targetVal = target[key];
- let isObjVal = isObject(val);
- if (isObjVal && val[STATIC] === void 0 && isObject(targetVal)) {
- this.doMutableMerge(targetVal, val);
- } else {
- target[key] = val;
- }
- }
- }
- cloneMerge(target, source) {
- let merged = __spreadValues(__spreadValues({}, target), source);
- for (let key in merged) {
- let val = source[key];
- let targetVal = target[key];
- if (isObject(val) && val[STATIC] === void 0 && isObject(targetVal)) {
- merged[key] = this.cloneMerge(targetVal, val);
- }
- }
- return merged;
- }
- componentToString(cid) {
- let [str, streams] = this.recursiveCIDToString(this.rendered[COMPONENTS], cid, null, false);
- return [str, streams];
- }
- pruneCIDs(cids) {
- cids.forEach((cid) => delete this.rendered[COMPONENTS][cid]);
- }
- get() {
- return this.rendered;
- }
- isNewFingerprint(diff = {}) {
- return !!diff[STATIC];
- }
- templateStatic(part, templates) {
- if (typeof part === "number") {
- return templates[part];
- } else {
- return part;
- }
- }
- toOutputBuffer(rendered, templates, output) {
- if (rendered[DYNAMICS]) {
- return this.comprehensionToBuffer(rendered, templates, output);
- }
- let { [STATIC]: statics } = rendered;
- statics = this.templateStatic(statics, templates);
- output.buffer += statics[0];
- for (let i2 = 1; i2 < statics.length; i2++) {
- this.dynamicToBuffer(rendered[i2 - 1], templates, output);
- output.buffer += statics[i2];
- }
- }
- comprehensionToBuffer(rendered, templates, output) {
- let { [DYNAMICS]: dynamics, [STATIC]: statics, [STREAM]: stream } = rendered;
- let [_ref, _inserts, deleteIds, reset] = stream || [null, {}, [], null];
- statics = this.templateStatic(statics, templates);
- let compTemplates = templates || rendered[TEMPLATES];
- for (let d2 = 0; d2 < dynamics.length; d2++) {
- let dynamic = dynamics[d2];
- output.buffer += statics[0];
- for (let i2 = 1; i2 < statics.length; i2++) {
- this.dynamicToBuffer(dynamic[i2 - 1], compTemplates, output);
- output.buffer += statics[i2];
- }
- }
- if (stream !== void 0 && (rendered[DYNAMICS].length > 0 || deleteIds.length > 0 || reset)) {
- delete rendered[STREAM];
- rendered[DYNAMICS] = [];
- output.streams.add(stream);
- }
- }
- dynamicToBuffer(rendered, templates, output) {
- if (typeof rendered === "number") {
- let [str, streams] = this.recursiveCIDToString(output.components, rendered, output.onlyCids);
- output.buffer += str;
- output.streams = /* @__PURE__ */ new Set([...output.streams, ...streams]);
- } else if (isObject(rendered)) {
- this.toOutputBuffer(rendered, templates, output);
- } else {
- output.buffer += rendered;
- }
- }
- recursiveCIDToString(components, cid, onlyCids, allowRootComments = true) {
- let component = components[cid] || logError(`no component for CID ${cid}`, components);
- let template = document.createElement("template");
- let [html, streams] = this.recursiveToString(component, components, onlyCids);
- template.innerHTML = html;
- let container = template.content;
- let skip = onlyCids && !onlyCids.has(cid);
- let [hasChildNodes, hasChildComponents] = Array.from(container.childNodes).reduce(([hasNodes, hasComponents], child, i2) => {
- if (child.nodeType === Node.ELEMENT_NODE) {
- if (child.getAttribute(PHX_COMPONENT)) {
- return [hasNodes, true];
- }
- child.setAttribute(PHX_COMPONENT, cid);
- if (!child.id) {
- child.id = `${this.parentViewId()}-${cid}-${i2}`;
- }
- if (skip) {
- child.setAttribute(PHX_SKIP, "");
- child.innerHTML = "";
- }
- return [true, hasComponents];
- } else if (child.nodeType === Node.COMMENT_NODE) {
- if (!allowRootComments) {
- child.remove();
- }
- return [hasNodes, hasComponents];
- } else {
- if (child.nodeValue.trim() !== "") {
- logError(`only HTML element tags are allowed at the root of components.
-
-got: "${child.nodeValue.trim()}"
-
-within:
-`, template.innerHTML.trim());
- child.replaceWith(this.createSpan(child.nodeValue, cid));
- return [true, hasComponents];
- } else {
- child.remove();
- return [hasNodes, hasComponents];
- }
- }
- }, [false, false]);
- if (!hasChildNodes && !hasChildComponents) {
- logError("expected at least one HTML element tag inside a component, but the component is empty:\n", template.innerHTML.trim());
- return [this.createSpan("", cid).outerHTML, streams];
- } else if (!hasChildNodes && hasChildComponents) {
- logError("expected at least one HTML element tag directly inside a component, but only subcomponents were found. A component must render at least one HTML tag directly inside itself.", template.innerHTML.trim());
- return [template.innerHTML, streams];
- } else {
- return [template.innerHTML, streams];
- }
- }
- createSpan(text, cid) {
- let span = document.createElement("span");
- span.innerText = text;
- span.setAttribute(PHX_COMPONENT, cid);
- return span;
- }
- };
- var viewHookID = 1;
- var ViewHook = class {
- static makeID() {
- return viewHookID++;
- }
- static elementID(el) {
- return el.phxHookId;
- }
- constructor(view, el, callbacks) {
- this.__view = view;
- this.liveSocket = view.liveSocket;
- this.__callbacks = callbacks;
- this.__listeners = /* @__PURE__ */ new Set();
- this.__isDisconnected = false;
- this.el = el;
- this.el.phxHookId = this.constructor.makeID();
- for (let key in this.__callbacks) {
- this[key] = this.__callbacks[key];
- }
- }
- __mounted() {
- this.mounted && this.mounted();
- }
- __updated() {
- this.updated && this.updated();
- }
- __beforeUpdate() {
- this.beforeUpdate && this.beforeUpdate();
- }
- __destroyed() {
- this.destroyed && this.destroyed();
- }
- __reconnected() {
- if (this.__isDisconnected) {
- this.__isDisconnected = false;
- this.reconnected && this.reconnected();
- }
- }
- __disconnected() {
- this.__isDisconnected = true;
- this.disconnected && this.disconnected();
- }
- pushEvent(event, payload = {}, onReply = function() {
- }) {
- return this.__view.pushHookEvent(this.el, null, event, payload, onReply);
- }
- pushEventTo(phxTarget, event, payload = {}, onReply = function() {
- }) {
- return this.__view.withinTargets(phxTarget, (view, targetCtx) => {
- return view.pushHookEvent(this.el, targetCtx, event, payload, onReply);
- });
- }
- handleEvent(event, callback) {
- let callbackRef = (customEvent, bypass) => bypass ? event : callback(customEvent.detail);
- window.addEventListener(`phx:${event}`, callbackRef);
- this.__listeners.add(callbackRef);
- return callbackRef;
- }
- removeHandleEvent(callbackRef) {
- let event = callbackRef(null, true);
- window.removeEventListener(`phx:${event}`, callbackRef);
- this.__listeners.delete(callbackRef);
- }
- upload(name, files) {
- return this.__view.dispatchUploads(null, name, files);
- }
- uploadTo(phxTarget, name, files) {
- return this.__view.withinTargets(phxTarget, (view, targetCtx) => {
- view.dispatchUploads(targetCtx, name, files);
- });
- }
- __cleanup__() {
- this.__listeners.forEach((callbackRef) => this.removeHandleEvent(callbackRef));
- }
- };
- var focusStack = null;
- var JS = {
- exec(eventType, phxEvent, view, sourceEl, defaults) {
- let [defaultKind, defaultArgs] = defaults || [null, { callback: defaults && defaults.callback }];
- let commands = phxEvent.charAt(0) === "[" ? JSON.parse(phxEvent) : [[defaultKind, defaultArgs]];
- commands.forEach(([kind, args]) => {
- if (kind === defaultKind && defaultArgs.data) {
- args.data = Object.assign(args.data || {}, defaultArgs.data);
- args.callback = args.callback || defaultArgs.callback;
- }
- this.filterToEls(sourceEl, args).forEach((el) => {
- this[`exec_${kind}`](eventType, phxEvent, view, sourceEl, el, args);
- });
- });
- },
- isVisible(el) {
- return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length > 0);
- },
- exec_exec(eventType, phxEvent, view, sourceEl, el, [attr, to]) {
- let nodes = to ? dom_default.all(document, to) : [sourceEl];
- nodes.forEach((node) => {
- let encodedJS = node.getAttribute(attr);
- if (!encodedJS) {
- throw new Error(`expected ${attr} to contain JS command on "${to}"`);
- }
- view.liveSocket.execJS(node, encodedJS, eventType);
- });
- },
- exec_dispatch(eventType, phxEvent, view, sourceEl, el, { to, event, detail, bubbles }) {
- detail = detail || {};
- detail.dispatcher = sourceEl;
- dom_default.dispatchEvent(el, event, { detail, bubbles });
- },
- exec_push(eventType, phxEvent, view, sourceEl, el, args) {
- if (!view.isConnected()) {
- return;
- }
- let { event, data, target, page_loading, loading, value, dispatcher, callback } = args;
- let pushOpts = { loading, value, target, page_loading: !!page_loading };
- let targetSrc = eventType === "change" && dispatcher ? dispatcher : sourceEl;
- let phxTarget = target || targetSrc.getAttribute(view.binding("target")) || targetSrc;
- view.withinTargets(phxTarget, (targetView, targetCtx) => {
- if (eventType === "change") {
- let { newCid, _target } = args;
- _target = _target || (dom_default.isFormInput(sourceEl) ? sourceEl.name : void 0);
- if (_target) {
- pushOpts._target = _target;
- }
- targetView.pushInput(sourceEl, targetCtx, newCid, event || phxEvent, pushOpts, callback);
- } else if (eventType === "submit") {
- let { submitter } = args;
- targetView.submitForm(sourceEl, targetCtx, event || phxEvent, submitter, pushOpts, callback);
- } else {
- targetView.pushEvent(eventType, sourceEl, targetCtx, event || phxEvent, data, pushOpts, callback);
- }
- });
- },
- exec_navigate(eventType, phxEvent, view, sourceEl, el, { href, replace }) {
- view.liveSocket.historyRedirect(href, replace ? "replace" : "push");
- },
- exec_patch(eventType, phxEvent, view, sourceEl, el, { href, replace }) {
- view.liveSocket.pushHistoryPatch(href, replace ? "replace" : "push", sourceEl);
- },
- exec_focus(eventType, phxEvent, view, sourceEl, el) {
- window.requestAnimationFrame(() => aria_default.attemptFocus(el));
- },
- exec_focus_first(eventType, phxEvent, view, sourceEl, el) {
- window.requestAnimationFrame(() => aria_default.focusFirstInteractive(el) || aria_default.focusFirst(el));
- },
- exec_push_focus(eventType, phxEvent, view, sourceEl, el) {
- window.requestAnimationFrame(() => focusStack = el || sourceEl);
- },
- exec_pop_focus(eventType, phxEvent, view, sourceEl, el) {
- window.requestAnimationFrame(() => {
- if (focusStack) {
- focusStack.focus();
- }
- focusStack = null;
- });
- },
- exec_add_class(eventType, phxEvent, view, sourceEl, el, { names, transition, time }) {
- this.addOrRemoveClasses(el, names, [], transition, time, view);
- },
- exec_remove_class(eventType, phxEvent, view, sourceEl, el, { names, transition, time }) {
- this.addOrRemoveClasses(el, [], names, transition, time, view);
- },
- exec_transition(eventType, phxEvent, view, sourceEl, el, { time, transition }) {
- this.addOrRemoveClasses(el, [], [], transition, time, view);
- },
- exec_toggle(eventType, phxEvent, view, sourceEl, el, { display, ins, outs, time }) {
- this.toggle(eventType, view, el, display, ins, outs, time);
- },
- exec_show(eventType, phxEvent, view, sourceEl, el, { display, transition, time }) {
- this.show(eventType, view, el, display, transition, time);
- },
- exec_hide(eventType, phxEvent, view, sourceEl, el, { display, transition, time }) {
- this.hide(eventType, view, el, display, transition, time);
- },
- exec_set_attr(eventType, phxEvent, view, sourceEl, el, { attr: [attr, val] }) {
- this.setOrRemoveAttrs(el, [[attr, val]], []);
- },
- exec_remove_attr(eventType, phxEvent, view, sourceEl, el, { attr }) {
- this.setOrRemoveAttrs(el, [], [attr]);
- },
- show(eventType, view, el, display, transition, time) {
- if (!this.isVisible(el)) {
- this.toggle(eventType, view, el, display, transition, null, time);
- }
- },
- hide(eventType, view, el, display, transition, time) {
- if (this.isVisible(el)) {
- this.toggle(eventType, view, el, display, null, transition, time);
- }
- },
- toggle(eventType, view, el, display, ins, outs, time) {
- let [inClasses, inStartClasses, inEndClasses] = ins || [[], [], []];
- let [outClasses, outStartClasses, outEndClasses] = outs || [[], [], []];
- if (inClasses.length > 0 || outClasses.length > 0) {
- if (this.isVisible(el)) {
- let onStart = () => {
- this.addOrRemoveClasses(el, outStartClasses, inClasses.concat(inStartClasses).concat(inEndClasses));
- window.requestAnimationFrame(() => {
- this.addOrRemoveClasses(el, outClasses, []);
- window.requestAnimationFrame(() => this.addOrRemoveClasses(el, outEndClasses, outStartClasses));
- });
- };
- el.dispatchEvent(new Event("phx:hide-start"));
- view.transition(time, onStart, () => {
- this.addOrRemoveClasses(el, [], outClasses.concat(outEndClasses));
- dom_default.putSticky(el, "toggle", (currentEl) => currentEl.style.display = "none");
- el.dispatchEvent(new Event("phx:hide-end"));
- });
- } else {
- if (eventType === "remove") {
- return;
- }
- let onStart = () => {
- this.addOrRemoveClasses(el, inStartClasses, outClasses.concat(outStartClasses).concat(outEndClasses));
- let stickyDisplay = display || this.defaultDisplay(el);
- dom_default.putSticky(el, "toggle", (currentEl) => currentEl.style.display = stickyDisplay);
- window.requestAnimationFrame(() => {
- this.addOrRemoveClasses(el, inClasses, []);
- window.requestAnimationFrame(() => this.addOrRemoveClasses(el, inEndClasses, inStartClasses));
- });
- };
- el.dispatchEvent(new Event("phx:show-start"));
- view.transition(time, onStart, () => {
- this.addOrRemoveClasses(el, [], inClasses.concat(inEndClasses));
- el.dispatchEvent(new Event("phx:show-end"));
- });
- }
- } else {
- if (this.isVisible(el)) {
- window.requestAnimationFrame(() => {
- el.dispatchEvent(new Event("phx:hide-start"));
- dom_default.putSticky(el, "toggle", (currentEl) => currentEl.style.display = "none");
- el.dispatchEvent(new Event("phx:hide-end"));
- });
- } else {
- window.requestAnimationFrame(() => {
- el.dispatchEvent(new Event("phx:show-start"));
- let stickyDisplay = display || this.defaultDisplay(el);
- dom_default.putSticky(el, "toggle", (currentEl) => currentEl.style.display = stickyDisplay);
- el.dispatchEvent(new Event("phx:show-end"));
- });
- }
- }
- },
- addOrRemoveClasses(el, adds, removes, transition, time, view) {
- let [transitionRun, transitionStart, transitionEnd] = transition || [[], [], []];
- if (transitionRun.length > 0) {
- let onStart = () => {
- this.addOrRemoveClasses(el, transitionStart, [].concat(transitionRun).concat(transitionEnd));
- window.requestAnimationFrame(() => {
- this.addOrRemoveClasses(el, transitionRun, []);
- window.requestAnimationFrame(() => this.addOrRemoveClasses(el, transitionEnd, transitionStart));
- });
- };
- let onDone = () => this.addOrRemoveClasses(el, adds.concat(transitionEnd), removes.concat(transitionRun).concat(transitionStart));
- return view.transition(time, onStart, onDone);
- }
- window.requestAnimationFrame(() => {
- let [prevAdds, prevRemoves] = dom_default.getSticky(el, "classes", [[], []]);
- let keepAdds = adds.filter((name) => prevAdds.indexOf(name) < 0 && !el.classList.contains(name));
- let keepRemoves = removes.filter((name) => prevRemoves.indexOf(name) < 0 && el.classList.contains(name));
- let newAdds = prevAdds.filter((name) => removes.indexOf(name) < 0).concat(keepAdds);
- let newRemoves = prevRemoves.filter((name) => adds.indexOf(name) < 0).concat(keepRemoves);
- dom_default.putSticky(el, "classes", (currentEl) => {
- currentEl.classList.remove(...newRemoves);
- currentEl.classList.add(...newAdds);
- return [newAdds, newRemoves];
- });
- });
- },
- setOrRemoveAttrs(el, sets, removes) {
- let [prevSets, prevRemoves] = dom_default.getSticky(el, "attrs", [[], []]);
- let alteredAttrs = sets.map(([attr, _val]) => attr).concat(removes);
- let newSets = prevSets.filter(([attr, _val]) => !alteredAttrs.includes(attr)).concat(sets);
- let newRemoves = prevRemoves.filter((attr) => !alteredAttrs.includes(attr)).concat(removes);
- dom_default.putSticky(el, "attrs", (currentEl) => {
- newRemoves.forEach((attr) => currentEl.removeAttribute(attr));
- newSets.forEach(([attr, val]) => currentEl.setAttribute(attr, val));
- return [newSets, newRemoves];
- });
- },
- hasAllClasses(el, classes) {
- return classes.every((name) => el.classList.contains(name));
- },
- isToggledOut(el, outClasses) {
- return !this.isVisible(el) || this.hasAllClasses(el, outClasses);
- },
- filterToEls(sourceEl, { to }) {
- return to ? dom_default.all(document, to) : [sourceEl];
- },
- defaultDisplay(el) {
- return { tr: "table-row", td: "table-cell" }[el.tagName.toLowerCase()] || "block";
- }
- };
- var js_default = JS;
- var serializeForm = (form, metadata, onlyNames = []) => {
- let _a = metadata, { submitter } = _a, meta = __objRest(_a, ["submitter"]);
- let formData = new FormData(form);
- if (submitter && submitter.hasAttribute("name") && submitter.form && submitter.form === form) {
- formData.append(submitter.name, submitter.value);
- }
- let toRemove = [];
- formData.forEach((val, key, _index) => {
- if (val instanceof File) {
- toRemove.push(key);
- }
- });
- toRemove.forEach((key) => formData.delete(key));
- let params = new URLSearchParams();
- for (let [key, val] of formData.entries()) {
- if (onlyNames.length === 0 || onlyNames.indexOf(key) >= 0) {
- params.append(key, val);
- }
- }
- for (let metaKey in meta) {
- params.append(metaKey, meta[metaKey]);
- }
- return params.toString();
- };
- var View = class {
- constructor(el, liveSocket2, parentView, flash, liveReferer) {
- this.isDead = false;
- this.liveSocket = liveSocket2;
- this.flash = flash;
- this.parent = parentView;
- this.root = parentView ? parentView.root : this;
- this.el = el;
- this.id = this.el.id;
- this.ref = 0;
- this.childJoins = 0;
- this.loaderTimer = null;
- this.pendingDiffs = [];
- this.pruningCIDs = [];
- this.redirect = false;
- this.href = null;
- this.joinCount = this.parent ? this.parent.joinCount - 1 : 0;
- this.joinPending = true;
- this.destroyed = false;
- this.joinCallback = function(onDone) {
- onDone && onDone();
- };
- this.stopCallback = function() {
- };
- this.pendingJoinOps = this.parent ? null : [];
- this.viewHooks = {};
- this.uploaders = {};
- this.formSubmits = [];
- this.children = this.parent ? null : {};
- this.root.children[this.id] = {};
- this.channel = this.liveSocket.channel(`lv:${this.id}`, () => {
- let url = this.href && this.expandURL(this.href);
- return {
- redirect: this.redirect ? url : void 0,
- url: this.redirect ? void 0 : url || void 0,
- params: this.connectParams(liveReferer),
- session: this.getSession(),
- static: this.getStatic(),
- flash: this.flash
- };
- });
- }
- setHref(href) {
- this.href = href;
- }
- setRedirect(href) {
- this.redirect = true;
- this.href = href;
- }
- isMain() {
- return this.el.hasAttribute(PHX_MAIN);
- }
- connectParams(liveReferer) {
- let params = this.liveSocket.params(this.el);
- let manifest = dom_default.all(document, `[${this.binding(PHX_TRACK_STATIC)}]`).map((node) => node.src || node.href).filter((url) => typeof url === "string");
- if (manifest.length > 0) {
- params["_track_static"] = manifest;
- }
- params["_mounts"] = this.joinCount;
- params["_live_referer"] = liveReferer;
- return params;
- }
- isConnected() {
- return this.channel.canPush();
- }
- getSession() {
- return this.el.getAttribute(PHX_SESSION);
- }
- getStatic() {
- let val = this.el.getAttribute(PHX_STATIC);
- return val === "" ? null : val;
- }
- destroy(callback = function() {
- }) {
- this.destroyAllChildren();
- this.destroyed = true;
- delete this.root.children[this.id];
- if (this.parent) {
- delete this.root.children[this.parent.id][this.id];
- }
- clearTimeout(this.loaderTimer);
- let onFinished = () => {
- callback();
- for (let id in this.viewHooks) {
- this.destroyHook(this.viewHooks[id]);
- }
- };
- dom_default.markPhxChildDestroyed(this.el);
- this.log("destroyed", () => ["the child has been removed from the parent"]);
- this.channel.leave().receive("ok", onFinished).receive("error", onFinished).receive("timeout", onFinished);
- }
- setContainerClasses(...classes) {
- this.el.classList.remove(PHX_CONNECTED_CLASS, PHX_LOADING_CLASS, PHX_ERROR_CLASS, PHX_CLIENT_ERROR_CLASS, PHX_SERVER_ERROR_CLASS);
- this.el.classList.add(...classes);
- }
- showLoader(timeout) {
- clearTimeout(this.loaderTimer);
- if (timeout) {
- this.loaderTimer = setTimeout(() => this.showLoader(), timeout);
- } else {
- for (let id in this.viewHooks) {
- this.viewHooks[id].__disconnected();
- }
- this.setContainerClasses(PHX_LOADING_CLASS);
- }
- }
- execAll(binding) {
- dom_default.all(this.el, `[${binding}]`, (el) => this.liveSocket.execJS(el, el.getAttribute(binding)));
- }
- hideLoader() {
- clearTimeout(this.loaderTimer);
- this.setContainerClasses(PHX_CONNECTED_CLASS);
- this.execAll(this.binding("connected"));
- }
- triggerReconnected() {
- for (let id in this.viewHooks) {
- this.viewHooks[id].__reconnected();
- }
- }
- log(kind, msgCallback) {
- this.liveSocket.log(this, kind, msgCallback);
- }
- transition(time, onStart, onDone = function() {
- }) {
- this.liveSocket.transition(time, onStart, onDone);
- }
- withinTargets(phxTarget, callback) {
- if (phxTarget instanceof HTMLElement || phxTarget instanceof SVGElement) {
- return this.liveSocket.owner(phxTarget, (view) => callback(view, phxTarget));
- }
- if (isCid(phxTarget)) {
- let targets = dom_default.findComponentNodeList(this.el, phxTarget);
- if (targets.length === 0) {
- logError(`no component found matching phx-target of ${phxTarget}`);
- } else {
- callback(this, parseInt(phxTarget));
- }
- } else {
- let targets = Array.from(document.querySelectorAll(phxTarget));
- if (targets.length === 0) {
- logError(`nothing found matching the phx-target selector "${phxTarget}"`);
- }
- targets.forEach((target) => this.liveSocket.owner(target, (view) => callback(view, target)));
- }
- }
- applyDiff(type, rawDiff, callback) {
- this.log(type, () => ["", clone(rawDiff)]);
- let { diff, reply, events, title } = Rendered.extract(rawDiff);
- callback({ diff, reply, events });
- if (title) {
- window.requestAnimationFrame(() => dom_default.putTitle(title));
- }
- }
- onJoin(resp) {
- let { rendered, container } = resp;
- if (container) {
- let [tag, attrs] = container;
- this.el = dom_default.replaceRootContainer(this.el, tag, attrs);
- }
- this.childJoins = 0;
- this.joinPending = true;
- this.flash = null;
- browser_default.dropLocal(this.liveSocket.localStorage, window.location.pathname, CONSECUTIVE_RELOADS);
- this.applyDiff("mount", rendered, ({ diff, events }) => {
- this.rendered = new Rendered(this.id, diff);
- let [html, streams] = this.renderContainer(null, "join");
- this.dropPendingRefs();
- let forms = this.formsForRecovery(html);
- this.joinCount++;
- if (forms.length > 0) {
- forms.forEach(([form, newForm, newCid], i2) => {
- this.pushFormRecovery(form, newCid, (resp2) => {
- if (i2 === forms.length - 1) {
- this.onJoinComplete(resp2, html, streams, events);
- }
- });
- });
- } else {
- this.onJoinComplete(resp, html, streams, events);
- }
- });
- }
- dropPendingRefs() {
- dom_default.all(document, `[${PHX_REF_SRC}="${this.id}"][${PHX_REF}]`, (el) => {
- el.removeAttribute(PHX_REF);
- el.removeAttribute(PHX_REF_SRC);
- });
- }
- onJoinComplete({ live_patch }, html, streams, events) {
- if (this.joinCount > 1 || this.parent && !this.parent.isJoinPending()) {
- return this.applyJoinPatch(live_patch, html, streams, events);
- }
- let newChildren = dom_default.findPhxChildrenInFragment(html, this.id).filter((toEl) => {
- let fromEl = toEl.id && this.el.querySelector(`[id="${toEl.id}"]`);
- let phxStatic = fromEl && fromEl.getAttribute(PHX_STATIC);
- if (phxStatic) {
- toEl.setAttribute(PHX_STATIC, phxStatic);
- }
- return this.joinChild(toEl);
- });
- if (newChildren.length === 0) {
- if (this.parent) {
- this.root.pendingJoinOps.push([this, () => this.applyJoinPatch(live_patch, html, streams, events)]);
- this.parent.ackJoin(this);
- } else {
- this.onAllChildJoinsComplete();
- this.applyJoinPatch(live_patch, html, streams, events);
- }
- } else {
- this.root.pendingJoinOps.push([this, () => this.applyJoinPatch(live_patch, html, streams, events)]);
- }
- }
- attachTrueDocEl() {
- this.el = dom_default.byId(this.id);
- this.el.setAttribute(PHX_ROOT_ID, this.root.id);
- }
- execNewMounted() {
- let phxViewportTop = this.binding(PHX_VIEWPORT_TOP);
- let phxViewportBottom = this.binding(PHX_VIEWPORT_BOTTOM);
- dom_default.all(this.el, `[${phxViewportTop}], [${phxViewportBottom}]`, (hookEl) => {
- dom_default.maybeAddPrivateHooks(hookEl, phxViewportTop, phxViewportBottom);
- this.maybeAddNewHook(hookEl);
- });
- dom_default.all(this.el, `[${this.binding(PHX_HOOK)}], [data-phx-${PHX_HOOK}]`, (hookEl) => {
- this.maybeAddNewHook(hookEl);
- });
- dom_default.all(this.el, `[${this.binding(PHX_MOUNTED)}]`, (el) => this.maybeMounted(el));
- }
- applyJoinPatch(live_patch, html, streams, events) {
- this.attachTrueDocEl();
- let patch = new DOMPatch(this, this.el, this.id, html, streams, null);
- patch.markPrunableContentForRemoval();
- this.performPatch(patch, false);
- this.joinNewChildren();
- this.execNewMounted();
- this.joinPending = false;
- this.liveSocket.dispatchEvents(events);
- this.applyPendingUpdates();
- if (live_patch) {
- let { kind, to } = live_patch;
- this.liveSocket.historyPatch(to, kind);
- }
- this.hideLoader();
- if (this.joinCount > 1) {
- this.triggerReconnected();
- }
- this.stopCallback();
- }
- triggerBeforeUpdateHook(fromEl, toEl) {
- this.liveSocket.triggerDOM("onBeforeElUpdated", [fromEl, toEl]);
- let hook = this.getHook(fromEl);
- let isIgnored = hook && dom_default.isIgnored(fromEl, this.binding(PHX_UPDATE));
- if (hook && !fromEl.isEqualNode(toEl) && !(isIgnored && isEqualObj(fromEl.dataset, toEl.dataset))) {
- hook.__beforeUpdate();
- return hook;
- }
- }
- maybeMounted(el) {
- let phxMounted = el.getAttribute(this.binding(PHX_MOUNTED));
- let hasBeenInvoked = phxMounted && dom_default.private(el, "mounted");
- if (phxMounted && !hasBeenInvoked) {
- this.liveSocket.execJS(el, phxMounted);
- dom_default.putPrivate(el, "mounted", true);
- }
- }
- maybeAddNewHook(el, force) {
- let newHook = this.addHook(el);
- if (newHook) {
- newHook.__mounted();
- }
- }
- performPatch(patch, pruneCids) {
- let removedEls = [];
- let phxChildrenAdded = false;
- let updatedHookIds = /* @__PURE__ */ new Set();
- patch.after("added", (el) => {
- this.liveSocket.triggerDOM("onNodeAdded", [el]);
- this.maybeAddNewHook(el);
- if (el.getAttribute) {
- this.maybeMounted(el);
- }
- });
- patch.after("phxChildAdded", (el) => {
- if (dom_default.isPhxSticky(el)) {
- this.liveSocket.joinRootViews();
- } else {
- phxChildrenAdded = true;
- }
- });
- patch.before("updated", (fromEl, toEl) => {
- let hook = this.triggerBeforeUpdateHook(fromEl, toEl);
- if (hook) {
- updatedHookIds.add(fromEl.id);
- }
- });
- patch.after("updated", (el) => {
- if (updatedHookIds.has(el.id)) {
- this.getHook(el).__updated();
- }
- });
- patch.after("discarded", (el) => {
- if (el.nodeType === Node.ELEMENT_NODE) {
- removedEls.push(el);
- }
- });
- patch.after("transitionsDiscarded", (els) => this.afterElementsRemoved(els, pruneCids));
- patch.perform();
- this.afterElementsRemoved(removedEls, pruneCids);
- return phxChildrenAdded;
- }
- afterElementsRemoved(elements, pruneCids) {
- let destroyedCIDs = [];
- elements.forEach((parent) => {
- let components = dom_default.all(parent, `[${PHX_COMPONENT}]`);
- let hooks = dom_default.all(parent, `[${this.binding(PHX_HOOK)}]`);
- components.concat(parent).forEach((el) => {
- let cid = this.componentID(el);
- if (isCid(cid) && destroyedCIDs.indexOf(cid) === -1) {
- destroyedCIDs.push(cid);
- }
- });
- hooks.concat(parent).forEach((hookEl) => {
- let hook = this.getHook(hookEl);
- hook && this.destroyHook(hook);
- });
- });
- if (pruneCids) {
- this.maybePushComponentsDestroyed(destroyedCIDs);
- }
- }
- joinNewChildren() {
- dom_default.findPhxChildren(this.el, this.id).forEach((el) => this.joinChild(el));
- }
- getChildById(id) {
- return this.root.children[this.id][id];
- }
- getDescendentByEl(el) {
- if (el.id === this.id) {
- return this;
- } else {
- return this.children[el.getAttribute(PHX_PARENT_ID)][el.id];
- }
- }
- destroyDescendent(id) {
- for (let parentId in this.root.children) {
- for (let childId in this.root.children[parentId]) {
- if (childId === id) {
- return this.root.children[parentId][childId].destroy();
- }
- }
- }
- }
- joinChild(el) {
- let child = this.getChildById(el.id);
- if (!child) {
- let view = new View(el, this.liveSocket, this);
- this.root.children[this.id][view.id] = view;
- view.join();
- this.childJoins++;
- return true;
- }
- }
- isJoinPending() {
- return this.joinPending;
- }
- ackJoin(_child) {
- this.childJoins--;
- if (this.childJoins === 0) {
- if (this.parent) {
- this.parent.ackJoin(this);
- } else {
- this.onAllChildJoinsComplete();
- }
- }
- }
- onAllChildJoinsComplete() {
- this.joinCallback(() => {
- this.pendingJoinOps.forEach(([view, op]) => {
- if (!view.isDestroyed()) {
- op();
- }
- });
- this.pendingJoinOps = [];
- });
- }
- update(diff, events) {
- if (this.isJoinPending() || this.liveSocket.hasPendingLink() && this.root.isMain()) {
- return this.pendingDiffs.push({ diff, events });
- }
- this.rendered.mergeDiff(diff);
- let phxChildrenAdded = false;
- if (this.rendered.isComponentOnlyDiff(diff)) {
- this.liveSocket.time("component patch complete", () => {
- let parentCids = dom_default.findParentCIDs(this.el, this.rendered.componentCIDs(diff));
- parentCids.forEach((parentCID) => {
- if (this.componentPatch(this.rendered.getComponent(diff, parentCID), parentCID)) {
- phxChildrenAdded = true;
- }
- });
- });
- } else if (!isEmpty(diff)) {
- this.liveSocket.time("full patch complete", () => {
- let [html, streams] = this.renderContainer(diff, "update");
- let patch = new DOMPatch(this, this.el, this.id, html, streams, null);
- phxChildrenAdded = this.performPatch(patch, true);
- });
- }
- this.liveSocket.dispatchEvents(events);
- if (phxChildrenAdded) {
- this.joinNewChildren();
- }
- }
- renderContainer(diff, kind) {
- return this.liveSocket.time(`toString diff (${kind})`, () => {
- let tag = this.el.tagName;
- let cids = diff ? this.rendered.componentCIDs(diff).concat(this.pruningCIDs) : null;
- let [html, streams] = this.rendered.toString(cids);
- return [`<${tag}>${html}${tag}>`, streams];
- });
- }
- componentPatch(diff, cid) {
- if (isEmpty(diff))
- return false;
- let [html, streams] = this.rendered.componentToString(cid);
- let patch = new DOMPatch(this, this.el, this.id, html, streams, cid);
- let childrenAdded = this.performPatch(patch, true);
- return childrenAdded;
- }
- getHook(el) {
- return this.viewHooks[ViewHook.elementID(el)];
- }
- addHook(el) {
- if (ViewHook.elementID(el) || !el.getAttribute) {
- return;
- }
- let hookName = el.getAttribute(`data-phx-${PHX_HOOK}`) || el.getAttribute(this.binding(PHX_HOOK));
- if (hookName && !this.ownsElement(el)) {
- return;
- }
- let callbacks = this.liveSocket.getHookCallbacks(hookName);
- if (callbacks) {
- if (!el.id) {
- logError(`no DOM ID for hook "${hookName}". Hooks require a unique ID on each element.`, el);
- }
- let hook = new ViewHook(this, el, callbacks);
- this.viewHooks[ViewHook.elementID(hook.el)] = hook;
- return hook;
- } else if (hookName !== null) {
- logError(`unknown hook found for "${hookName}"`, el);
- }
- }
- destroyHook(hook) {
- hook.__destroyed();
- hook.__cleanup__();
- delete this.viewHooks[ViewHook.elementID(hook.el)];
- }
- applyPendingUpdates() {
- this.pendingDiffs.forEach(({ diff, events }) => this.update(diff, events));
- this.pendingDiffs = [];
- this.eachChild((child) => child.applyPendingUpdates());
- }
- eachChild(callback) {
- let children = this.root.children[this.id] || {};
- for (let id in children) {
- callback(this.getChildById(id));
- }
- }
- onChannel(event, cb) {
- this.liveSocket.onChannel(this.channel, event, (resp) => {
- if (this.isJoinPending()) {
- this.root.pendingJoinOps.push([this, () => cb(resp)]);
- } else {
- this.liveSocket.requestDOMUpdate(() => cb(resp));
- }
- });
- }
- bindChannel() {
- this.liveSocket.onChannel(this.channel, "diff", (rawDiff) => {
- this.liveSocket.requestDOMUpdate(() => {
- this.applyDiff("update", rawDiff, ({ diff, events }) => this.update(diff, events));
- });
- });
- this.onChannel("redirect", ({ to, flash }) => this.onRedirect({ to, flash }));
- this.onChannel("live_patch", (redir) => this.onLivePatch(redir));
- this.onChannel("live_redirect", (redir) => this.onLiveRedirect(redir));
- this.channel.onError((reason) => this.onError(reason));
- this.channel.onClose((reason) => this.onClose(reason));
- }
- destroyAllChildren() {
- this.eachChild((child) => child.destroy());
- }
- onLiveRedirect(redir) {
- let { to, kind, flash } = redir;
- let url = this.expandURL(to);
- this.liveSocket.historyRedirect(url, kind, flash);
- }
- onLivePatch(redir) {
- let { to, kind } = redir;
- this.href = this.expandURL(to);
- this.liveSocket.historyPatch(to, kind);
- }
- expandURL(to) {
- return to.startsWith("/") ? `${window.location.protocol}//${window.location.host}${to}` : to;
- }
- onRedirect({ to, flash }) {
- this.liveSocket.redirect(to, flash);
- }
- isDestroyed() {
- return this.destroyed;
- }
- joinDead() {
- this.isDead = true;
- }
- join(callback) {
- this.showLoader(this.liveSocket.loaderTimeout);
- this.bindChannel();
- if (this.isMain()) {
- this.stopCallback = this.liveSocket.withPageLoading({ to: this.href, kind: "initial" });
- }
- this.joinCallback = (onDone) => {
- onDone = onDone || function() {
- };
- callback ? callback(this.joinCount, onDone) : onDone();
- };
- this.liveSocket.wrapPush(this, { timeout: false }, () => {
- return this.channel.join().receive("ok", (data) => {
- if (!this.isDestroyed()) {
- this.liveSocket.requestDOMUpdate(() => this.onJoin(data));
- }
- }).receive("error", (resp) => !this.isDestroyed() && this.onJoinError(resp)).receive("timeout", () => !this.isDestroyed() && this.onJoinError({ reason: "timeout" }));
- });
- }
- onJoinError(resp) {
- if (resp.reason === "reload") {
- this.log("error", () => [`failed mount with ${resp.status}. Falling back to page request`, resp]);
- if (this.isMain()) {
- this.onRedirect({ to: this.href });
- }
- return;
- } else if (resp.reason === "unauthorized" || resp.reason === "stale") {
- this.log("error", () => ["unauthorized live_redirect. Falling back to page request", resp]);
- if (this.isMain()) {
- this.onRedirect({ to: this.href });
- }
- return;
- }
- if (resp.redirect || resp.live_redirect) {
- this.joinPending = false;
- this.channel.leave();
- }
- if (resp.redirect) {
- return this.onRedirect(resp.redirect);
- }
- if (resp.live_redirect) {
- return this.onLiveRedirect(resp.live_redirect);
- }
- this.displayError([PHX_LOADING_CLASS, PHX_ERROR_CLASS, PHX_SERVER_ERROR_CLASS]);
- this.log("error", () => ["unable to join", resp]);
- if (this.liveSocket.isConnected()) {
- this.liveSocket.reloadWithJitter(this);
- }
- }
- onClose(reason) {
- if (this.isDestroyed()) {
- return;
- }
- if (this.liveSocket.hasPendingLink() && reason !== "leave") {
- return this.liveSocket.reloadWithJitter(this);
- }
- this.destroyAllChildren();
- this.liveSocket.dropActiveElement(this);
- if (document.activeElement) {
- document.activeElement.blur();
- }
- if (this.liveSocket.isUnloaded()) {
- this.showLoader(BEFORE_UNLOAD_LOADER_TIMEOUT);
- }
- }
- onError(reason) {
- this.onClose(reason);
- if (this.liveSocket.isConnected()) {
- this.log("error", () => ["view crashed", reason]);
- }
- if (!this.liveSocket.isUnloaded()) {
- if (this.liveSocket.isConnected()) {
- this.displayError([PHX_LOADING_CLASS, PHX_ERROR_CLASS, PHX_SERVER_ERROR_CLASS]);
- } else {
- this.displayError([PHX_LOADING_CLASS, PHX_ERROR_CLASS, PHX_CLIENT_ERROR_CLASS]);
- }
- }
- }
- displayError(classes) {
- if (this.isMain()) {
- dom_default.dispatchEvent(window, "phx:page-loading-start", { detail: { to: this.href, kind: "error" } });
- }
- this.showLoader();
- this.setContainerClasses(...classes);
- this.execAll(this.binding("disconnected"));
- }
- pushWithReply(refGenerator, event, payload, onReply = function() {
- }) {
- if (!this.isConnected()) {
- return;
- }
- let [ref, [el], opts] = refGenerator ? refGenerator() : [null, [], {}];
- let onLoadingDone = function() {
- };
- if (opts.page_loading || el && el.getAttribute(this.binding(PHX_PAGE_LOADING)) !== null) {
- onLoadingDone = this.liveSocket.withPageLoading({ kind: "element", target: el });
- }
- if (typeof payload.cid !== "number") {
- delete payload.cid;
- }
- return this.liveSocket.wrapPush(this, { timeout: true }, () => {
- return this.channel.push(event, payload, PUSH_TIMEOUT).receive("ok", (resp) => {
- let finish = (hookReply) => {
- if (resp.redirect) {
- this.onRedirect(resp.redirect);
- }
- if (resp.live_patch) {
- this.onLivePatch(resp.live_patch);
- }
- if (resp.live_redirect) {
- this.onLiveRedirect(resp.live_redirect);
- }
- onLoadingDone();
- onReply(resp, hookReply);
- };
- if (resp.diff) {
- this.liveSocket.requestDOMUpdate(() => {
- this.applyDiff("update", resp.diff, ({ diff, reply, events }) => {
- if (ref !== null) {
- this.undoRefs(ref);
- }
- this.update(diff, events);
- finish(reply);
- });
- });
- } else {
- if (ref !== null) {
- this.undoRefs(ref);
- }
- finish(null);
- }
- });
- });
- }
- undoRefs(ref) {
- if (!this.isConnected()) {
- return;
- }
- dom_default.all(document, `[${PHX_REF_SRC}="${this.id}"][${PHX_REF}="${ref}"]`, (el) => {
- let disabledVal = el.getAttribute(PHX_DISABLED);
- el.removeAttribute(PHX_REF);
- el.removeAttribute(PHX_REF_SRC);
- if (el.getAttribute(PHX_READONLY) !== null) {
- el.readOnly = false;
- el.removeAttribute(PHX_READONLY);
- }
- if (disabledVal !== null) {
- el.disabled = disabledVal === "true" ? true : false;
- el.removeAttribute(PHX_DISABLED);
- }
- PHX_EVENT_CLASSES.forEach((className) => dom_default.removeClass(el, className));
- let disableRestore = el.getAttribute(PHX_DISABLE_WITH_RESTORE);
- if (disableRestore !== null) {
- el.innerText = disableRestore;
- el.removeAttribute(PHX_DISABLE_WITH_RESTORE);
- }
- let toEl = dom_default.private(el, PHX_REF);
- if (toEl) {
- let hook = this.triggerBeforeUpdateHook(el, toEl);
- DOMPatch.patchEl(el, toEl, this.liveSocket.getActiveElement());
- if (hook) {
- hook.__updated();
- }
- dom_default.deletePrivate(el, PHX_REF);
- }
- });
- }
- putRef(elements, event, opts = {}) {
- let newRef = this.ref++;
- let disableWith = this.binding(PHX_DISABLE_WITH);
- if (opts.loading) {
- elements = elements.concat(dom_default.all(document, opts.loading));
- }
- elements.forEach((el) => {
- el.classList.add(`phx-${event}-loading`);
- el.setAttribute(PHX_REF, newRef);
- el.setAttribute(PHX_REF_SRC, this.el.id);
- let disableText = el.getAttribute(disableWith);
- if (disableText !== null) {
- if (!el.getAttribute(PHX_DISABLE_WITH_RESTORE)) {
- el.setAttribute(PHX_DISABLE_WITH_RESTORE, el.innerText);
- }
- if (disableText !== "") {
- el.innerText = disableText;
- }
- el.setAttribute("disabled", "");
- }
- });
- return [newRef, elements, opts];
- }
- componentID(el) {
- let cid = el.getAttribute && el.getAttribute(PHX_COMPONENT);
- return cid ? parseInt(cid) : null;
- }
- targetComponentID(target, targetCtx, opts = {}) {
- if (isCid(targetCtx)) {
- return targetCtx;
- }
- let cidOrSelector = target.getAttribute(this.binding("target"));
- if (isCid(cidOrSelector)) {
- return parseInt(cidOrSelector);
- } else if (targetCtx && (cidOrSelector !== null || opts.target)) {
- return this.closestComponentID(targetCtx);
- } else {
- return null;
- }
- }
- closestComponentID(targetCtx) {
- if (isCid(targetCtx)) {
- return targetCtx;
- } else if (targetCtx) {
- return maybe(targetCtx.closest(`[${PHX_COMPONENT}]`), (el) => this.ownsElement(el) && this.componentID(el));
- } else {
- return null;
- }
- }
- pushHookEvent(el, targetCtx, event, payload, onReply) {
- if (!this.isConnected()) {
- this.log("hook", () => ["unable to push hook event. LiveView not connected", event, payload]);
- return false;
- }
- let [ref, els, opts] = this.putRef([el], "hook");
- this.pushWithReply(() => [ref, els, opts], "event", {
- type: "hook",
- event,
- value: payload,
- cid: this.closestComponentID(targetCtx)
- }, (resp, reply) => onReply(reply, ref));
- return ref;
- }
- extractMeta(el, meta, value) {
- let prefix = this.binding("value-");
- for (let i2 = 0; i2 < el.attributes.length; i2++) {
- if (!meta) {
- meta = {};
- }
- let name = el.attributes[i2].name;
- if (name.startsWith(prefix)) {
- meta[name.replace(prefix, "")] = el.getAttribute(name);
- }
- }
- if (el.value !== void 0 && !(el instanceof HTMLFormElement)) {
- if (!meta) {
- meta = {};
- }
- meta.value = el.value;
- if (el.tagName === "INPUT" && CHECKABLE_INPUTS.indexOf(el.type) >= 0 && !el.checked) {
- delete meta.value;
- }
- }
- if (value) {
- if (!meta) {
- meta = {};
- }
- for (let key in value) {
- meta[key] = value[key];
- }
- }
- return meta;
- }
- pushEvent(type, el, targetCtx, phxEvent, meta, opts = {}, onReply) {
- this.pushWithReply(() => this.putRef([el], type, opts), "event", {
- type,
- event: phxEvent,
- value: this.extractMeta(el, meta, opts.value),
- cid: this.targetComponentID(el, targetCtx, opts)
- }, (resp, reply) => onReply && onReply(reply));
- }
- pushFileProgress(fileEl, entryRef, progress, onReply = function() {
- }) {
- this.liveSocket.withinOwners(fileEl.form, (view, targetCtx) => {
- view.pushWithReply(null, "progress", {
- event: fileEl.getAttribute(view.binding(PHX_PROGRESS)),
- ref: fileEl.getAttribute(PHX_UPLOAD_REF),
- entry_ref: entryRef,
- progress,
- cid: view.targetComponentID(fileEl.form, targetCtx)
- }, onReply);
- });
- }
- pushInput(inputEl, targetCtx, forceCid, phxEvent, opts, callback) {
- let uploads;
- let cid = isCid(forceCid) ? forceCid : this.targetComponentID(inputEl.form, targetCtx);
- let refGenerator = () => this.putRef([inputEl, inputEl.form], "change", opts);
- let formData;
- let meta = this.extractMeta(inputEl.form);
- if (inputEl.getAttribute(this.binding("change"))) {
- formData = serializeForm(inputEl.form, __spreadValues({ _target: opts._target }, meta), [inputEl.name]);
- } else {
- formData = serializeForm(inputEl.form, __spreadValues({ _target: opts._target }, meta));
- }
- if (dom_default.isUploadInput(inputEl) && inputEl.files && inputEl.files.length > 0) {
- LiveUploader.trackFiles(inputEl, Array.from(inputEl.files));
- }
- uploads = LiveUploader.serializeUploads(inputEl);
- let event = {
- type: "form",
- event: phxEvent,
- value: formData,
- uploads,
- cid
- };
- this.pushWithReply(refGenerator, "event", event, (resp) => {
- dom_default.showError(inputEl, this.liveSocket.binding(PHX_FEEDBACK_FOR));
- if (dom_default.isUploadInput(inputEl) && dom_default.isAutoUpload(inputEl)) {
- if (LiveUploader.filesAwaitingPreflight(inputEl).length > 0) {
- let [ref, _els] = refGenerator();
- this.uploadFiles(inputEl.form, targetCtx, ref, cid, (_uploads) => {
- callback && callback(resp);
- this.triggerAwaitingSubmit(inputEl.form);
- });
- }
- } else {
- callback && callback(resp);
- }
- });
- }
- triggerAwaitingSubmit(formEl) {
- let awaitingSubmit = this.getScheduledSubmit(formEl);
- if (awaitingSubmit) {
- let [_el, _ref, _opts, callback] = awaitingSubmit;
- this.cancelSubmit(formEl);
- callback();
- }
- }
- getScheduledSubmit(formEl) {
- return this.formSubmits.find(([el, _ref, _opts, _callback]) => el.isSameNode(formEl));
- }
- scheduleSubmit(formEl, ref, opts, callback) {
- if (this.getScheduledSubmit(formEl)) {
- return true;
- }
- this.formSubmits.push([formEl, ref, opts, callback]);
- }
- cancelSubmit(formEl) {
- this.formSubmits = this.formSubmits.filter(([el, ref, _callback]) => {
- if (el.isSameNode(formEl)) {
- this.undoRefs(ref);
- return false;
- } else {
- return true;
- }
- });
- }
- disableForm(formEl, opts = {}) {
- let filterIgnored = (el) => {
- let userIgnored = closestPhxBinding(el, `${this.binding(PHX_UPDATE)}=ignore`, el.form);
- return !(userIgnored || closestPhxBinding(el, "data-phx-update=ignore", el.form));
- };
- let filterDisables = (el) => {
- return el.hasAttribute(this.binding(PHX_DISABLE_WITH));
- };
- let filterButton = (el) => el.tagName == "BUTTON";
- let filterInput = (el) => ["INPUT", "TEXTAREA", "SELECT"].includes(el.tagName);
- let formElements = Array.from(formEl.elements);
- let disables = formElements.filter(filterDisables);
- let buttons = formElements.filter(filterButton).filter(filterIgnored);
- let inputs = formElements.filter(filterInput).filter(filterIgnored);
- buttons.forEach((button) => {
- button.setAttribute(PHX_DISABLED, button.disabled);
- button.disabled = true;
- });
- inputs.forEach((input) => {
- input.setAttribute(PHX_READONLY, input.readOnly);
- input.readOnly = true;
- if (input.files) {
- input.setAttribute(PHX_DISABLED, input.disabled);
- input.disabled = true;
- }
- });
- formEl.setAttribute(this.binding(PHX_PAGE_LOADING), "");
- return this.putRef([formEl].concat(disables).concat(buttons).concat(inputs), "submit", opts);
- }
- pushFormSubmit(formEl, targetCtx, phxEvent, submitter, opts, onReply) {
- let refGenerator = () => this.disableForm(formEl, opts);
- let cid = this.targetComponentID(formEl, targetCtx);
- if (LiveUploader.hasUploadsInProgress(formEl)) {
- let [ref, _els] = refGenerator();
- let push = () => this.pushFormSubmit(formEl, submitter, targetCtx, phxEvent, opts, onReply);
- return this.scheduleSubmit(formEl, ref, opts, push);
- } else if (LiveUploader.inputsAwaitingPreflight(formEl).length > 0) {
- let [ref, els] = refGenerator();
- let proxyRefGen = () => [ref, els, opts];
- this.uploadFiles(formEl, targetCtx, ref, cid, (_uploads) => {
- let meta = this.extractMeta(formEl);
- let formData = serializeForm(formEl, __spreadValues({ submitter }, meta));
- this.pushWithReply(proxyRefGen, "event", {
- type: "form",
- event: phxEvent,
- value: formData,
- cid
- }, onReply);
- });
- } else if (!(formEl.hasAttribute(PHX_REF) && formEl.classList.contains("phx-submit-loading"))) {
- let meta = this.extractMeta(formEl);
- let formData = serializeForm(formEl, __spreadValues({ submitter }, meta));
- this.pushWithReply(refGenerator, "event", {
- type: "form",
- event: phxEvent,
- value: formData,
- cid
- }, onReply);
- }
- }
- uploadFiles(formEl, targetCtx, ref, cid, onComplete) {
- let joinCountAtUpload = this.joinCount;
- let inputEls = LiveUploader.activeFileInputs(formEl);
- let numFileInputsInProgress = inputEls.length;
- inputEls.forEach((inputEl) => {
- let uploader = new LiveUploader(inputEl, this, () => {
- numFileInputsInProgress--;
- if (numFileInputsInProgress === 0) {
- onComplete();
- }
- });
- this.uploaders[inputEl] = uploader;
- let entries = uploader.entries().map((entry) => entry.toPreflightPayload());
- let payload = {
- ref: inputEl.getAttribute(PHX_UPLOAD_REF),
- entries,
- cid: this.targetComponentID(inputEl.form, targetCtx)
- };
- this.log("upload", () => ["sending preflight request", payload]);
- this.pushWithReply(null, "allow_upload", payload, (resp) => {
- this.log("upload", () => ["got preflight response", resp]);
- if (resp.error) {
- this.undoRefs(ref);
- let [entry_ref, reason] = resp.error;
- this.log("upload", () => [`error for entry ${entry_ref}`, reason]);
- } else {
- let onError = (callback) => {
- this.channel.onError(() => {
- if (this.joinCount === joinCountAtUpload) {
- callback();
- }
- });
- };
- uploader.initAdapterUpload(resp, onError, this.liveSocket);
- }
- });
- });
- }
- dispatchUploads(targetCtx, name, filesOrBlobs) {
- let targetElement = this.targetCtxElement(targetCtx) || this.el;
- let inputs = dom_default.findUploadInputs(targetElement).filter((el) => el.name === name);
- if (inputs.length === 0) {
- logError(`no live file inputs found matching the name "${name}"`);
- } else if (inputs.length > 1) {
- logError(`duplicate live file inputs found matching the name "${name}"`);
- } else {
- dom_default.dispatchEvent(inputs[0], PHX_TRACK_UPLOADS, { detail: { files: filesOrBlobs } });
- }
- }
- targetCtxElement(targetCtx) {
- if (isCid(targetCtx)) {
- let [target] = dom_default.findComponentNodeList(this.el, targetCtx);
- return target;
- } else if (targetCtx) {
- return targetCtx;
- } else {
- return null;
- }
- }
- pushFormRecovery(form, newCid, callback) {
- this.liveSocket.withinOwners(form, (view, targetCtx) => {
- let phxChange = this.binding("change");
- let inputs = Array.from(form.elements).filter((el) => dom_default.isFormInput(el) && el.name && !el.hasAttribute(phxChange));
- if (inputs.length === 0) {
- return;
- }
- inputs.forEach((input2) => input2.hasAttribute(PHX_UPLOAD_REF) && LiveUploader.clearFiles(input2));
- let input = inputs.find((el) => el.type !== "hidden") || inputs[0];
- let phxEvent = form.getAttribute(this.binding(PHX_AUTO_RECOVER)) || form.getAttribute(this.binding("change"));
- js_default.exec("change", phxEvent, view, input, ["push", { _target: input.name, newCid, callback }]);
- });
- }
- pushLinkPatch(href, targetEl, callback) {
- let linkRef = this.liveSocket.setPendingLink(href);
- let refGen = targetEl ? () => this.putRef([targetEl], "click") : null;
- let fallback = () => this.liveSocket.redirect(window.location.href);
- let url = href.startsWith("/") ? `${location.protocol}//${location.host}${href}` : href;
- let push = this.pushWithReply(refGen, "live_patch", { url }, (resp) => {
- this.liveSocket.requestDOMUpdate(() => {
- if (resp.link_redirect) {
- this.liveSocket.replaceMain(href, null, callback, linkRef);
- } else {
- if (this.liveSocket.commitPendingLink(linkRef)) {
- this.href = href;
- }
- this.applyPendingUpdates();
- callback && callback(linkRef);
- }
- });
- });
- if (push) {
- push.receive("timeout", fallback);
- } else {
- fallback();
- }
- }
- formsForRecovery(html) {
- if (this.joinCount === 0) {
- return [];
- }
- let phxChange = this.binding("change");
- let template = document.createElement("template");
- template.innerHTML = html;
- return dom_default.all(this.el, `form[${phxChange}]`).filter((form) => form.id && this.ownsElement(form)).filter((form) => form.elements.length > 0).filter((form) => form.getAttribute(this.binding(PHX_AUTO_RECOVER)) !== "ignore").map((form) => {
- const phxChangeValue = form.getAttribute(phxChange).replaceAll(/([\[\]"])/g, "\\$1");
- let newForm = template.content.querySelector(`form[id="${form.id}"][${phxChange}="${phxChangeValue}"]`);
- if (newForm) {
- return [form, newForm, this.targetComponentID(newForm)];
- } else {
- return [form, form, this.targetComponentID(form)];
- }
- }).filter(([form, newForm, newCid]) => newForm);
- }
- maybePushComponentsDestroyed(destroyedCIDs) {
- let willDestroyCIDs = destroyedCIDs.filter((cid) => {
- return dom_default.findComponentNodeList(this.el, cid).length === 0;
- });
- if (willDestroyCIDs.length > 0) {
- this.pruningCIDs.push(...willDestroyCIDs);
- this.pushWithReply(null, "cids_will_destroy", { cids: willDestroyCIDs }, () => {
- this.pruningCIDs = this.pruningCIDs.filter((cid) => willDestroyCIDs.indexOf(cid) !== -1);
- let completelyDestroyCIDs = willDestroyCIDs.filter((cid) => {
- return dom_default.findComponentNodeList(this.el, cid).length === 0;
- });
- if (completelyDestroyCIDs.length > 0) {
- this.pushWithReply(null, "cids_destroyed", { cids: completelyDestroyCIDs }, (resp) => {
- this.rendered.pruneCIDs(resp.cids);
- });
- }
- });
- }
- }
- ownsElement(el) {
- let parentViewEl = el.closest(PHX_VIEW_SELECTOR);
- return el.getAttribute(PHX_PARENT_ID) === this.id || parentViewEl && parentViewEl.id === this.id || !parentViewEl && this.isDead;
- }
- submitForm(form, targetCtx, phxEvent, submitter, opts = {}) {
- dom_default.putPrivate(form, PHX_HAS_SUBMITTED, true);
- let phxFeedback = this.liveSocket.binding(PHX_FEEDBACK_FOR);
- let inputs = Array.from(form.elements);
- inputs.forEach((input) => dom_default.putPrivate(input, PHX_HAS_SUBMITTED, true));
- this.liveSocket.blurActiveElement(this);
- this.pushFormSubmit(form, targetCtx, phxEvent, submitter, opts, () => {
- inputs.forEach((input) => dom_default.showError(input, phxFeedback));
- this.liveSocket.restorePreviouslyActiveFocus();
- });
- }
- binding(kind) {
- return this.liveSocket.binding(kind);
- }
- };
- var LiveSocket = class {
- constructor(url, phxSocket, opts = {}) {
- this.unloaded = false;
- if (!phxSocket || phxSocket.constructor.name === "Object") {
- throw new Error(`
- a phoenix Socket must be provided as the second argument to the LiveSocket constructor. For example:
-
- import {Socket} from "phoenix"
- import {LiveSocket} from "phoenix_live_view"
- let liveSocket = new LiveSocket("/live", Socket, {...})
- `);
- }
- this.socket = new phxSocket(url, opts);
- this.bindingPrefix = opts.bindingPrefix || BINDING_PREFIX;
- this.opts = opts;
- this.params = closure2(opts.params || {});
- this.viewLogger = opts.viewLogger;
- this.metadataCallbacks = opts.metadata || {};
- this.defaults = Object.assign(clone(DEFAULTS), opts.defaults || {});
- this.activeElement = null;
- this.prevActive = null;
- this.silenced = false;
- this.main = null;
- this.outgoingMainEl = null;
- this.clickStartedAtTarget = null;
- this.linkRef = 1;
- this.roots = {};
- this.href = window.location.href;
- this.pendingLink = null;
- this.currentLocation = clone(window.location);
- this.hooks = opts.hooks || {};
- this.uploaders = opts.uploaders || {};
- this.loaderTimeout = opts.loaderTimeout || LOADER_TIMEOUT;
- this.reloadWithJitterTimer = null;
- this.maxReloads = opts.maxReloads || MAX_RELOADS;
- this.reloadJitterMin = opts.reloadJitterMin || RELOAD_JITTER_MIN;
- this.reloadJitterMax = opts.reloadJitterMax || RELOAD_JITTER_MAX;
- this.failsafeJitter = opts.failsafeJitter || FAILSAFE_JITTER;
- this.localStorage = opts.localStorage || window.localStorage;
- this.sessionStorage = opts.sessionStorage || window.sessionStorage;
- this.boundTopLevelEvents = false;
- this.domCallbacks = Object.assign({ onNodeAdded: closure2(), onBeforeElUpdated: closure2() }, opts.dom || {});
- this.transitions = new TransitionSet();
- window.addEventListener("pagehide", (_e2) => {
- this.unloaded = true;
- });
- this.socket.onOpen(() => {
- if (this.isUnloaded()) {
- window.location.reload();
- }
- });
- }
- isProfileEnabled() {
- return this.sessionStorage.getItem(PHX_LV_PROFILE) === "true";
- }
- isDebugEnabled() {
- return this.sessionStorage.getItem(PHX_LV_DEBUG) === "true";
- }
- isDebugDisabled() {
- return this.sessionStorage.getItem(PHX_LV_DEBUG) === "false";
- }
- enableDebug() {
- this.sessionStorage.setItem(PHX_LV_DEBUG, "true");
- }
- enableProfiling() {
- this.sessionStorage.setItem(PHX_LV_PROFILE, "true");
- }
- disableDebug() {
- this.sessionStorage.setItem(PHX_LV_DEBUG, "false");
- }
- disableProfiling() {
- this.sessionStorage.removeItem(PHX_LV_PROFILE);
- }
- enableLatencySim(upperBoundMs) {
- this.enableDebug();
- console.log("latency simulator enabled for the duration of this browser session. Call disableLatencySim() to disable");
- this.sessionStorage.setItem(PHX_LV_LATENCY_SIM, upperBoundMs);
- }
- disableLatencySim() {
- this.sessionStorage.removeItem(PHX_LV_LATENCY_SIM);
- }
- getLatencySim() {
- let str = this.sessionStorage.getItem(PHX_LV_LATENCY_SIM);
- return str ? parseInt(str) : null;
- }
- getSocket() {
- return this.socket;
- }
- connect() {
- if (window.location.hostname === "localhost" && !this.isDebugDisabled()) {
- this.enableDebug();
- }
- let doConnect = () => {
- if (this.joinRootViews()) {
- this.bindTopLevelEvents();
- this.socket.connect();
- } else if (this.main) {
- this.socket.connect();
- } else {
- this.bindTopLevelEvents({ dead: true });
- }
- this.joinDeadView();
- };
- if (["complete", "loaded", "interactive"].indexOf(document.readyState) >= 0) {
- doConnect();
- } else {
- document.addEventListener("DOMContentLoaded", () => doConnect());
- }
- }
- disconnect(callback) {
- clearTimeout(this.reloadWithJitterTimer);
- this.socket.disconnect(callback);
- }
- replaceTransport(transport) {
- clearTimeout(this.reloadWithJitterTimer);
- this.socket.replaceTransport(transport);
- this.connect();
- }
- execJS(el, encodedJS, eventType = null) {
- this.owner(el, (view) => js_default.exec(eventType, encodedJS, view, el));
- }
- execJSHookPush(el, phxEvent, data, callback) {
- this.withinOwners(el, (view) => {
- js_default.exec("hook", phxEvent, view, el, ["push", { data, callback }]);
- });
- }
- unload() {
- if (this.unloaded) {
- return;
- }
- if (this.main && this.isConnected()) {
- this.log(this.main, "socket", () => ["disconnect for page nav"]);
- }
- this.unloaded = true;
- this.destroyAllViews();
- this.disconnect();
- }
- triggerDOM(kind, args) {
- this.domCallbacks[kind](...args);
- }
- time(name, func) {
- if (!this.isProfileEnabled() || !console.time) {
- return func();
- }
- console.time(name);
- let result = func();
- console.timeEnd(name);
- return result;
- }
- log(view, kind, msgCallback) {
- if (this.viewLogger) {
- let [msg, obj] = msgCallback();
- this.viewLogger(view, kind, msg, obj);
- } else if (this.isDebugEnabled()) {
- let [msg, obj] = msgCallback();
- debug(view, kind, msg, obj);
- }
- }
- requestDOMUpdate(callback) {
- this.transitions.after(callback);
- }
- transition(time, onStart, onDone = function() {
- }) {
- this.transitions.addTransition(time, onStart, onDone);
- }
- onChannel(channel, event, cb) {
- channel.on(event, (data) => {
- let latency = this.getLatencySim();
- if (!latency) {
- cb(data);
- } else {
- setTimeout(() => cb(data), latency);
- }
- });
- }
- wrapPush(view, opts, push) {
- let latency = this.getLatencySim();
- let oldJoinCount = view.joinCount;
- if (!latency) {
- if (this.isConnected() && opts.timeout) {
- return push().receive("timeout", () => {
- if (view.joinCount === oldJoinCount && !view.isDestroyed()) {
- this.reloadWithJitter(view, () => {
- this.log(view, "timeout", () => ["received timeout while communicating with server. Falling back to hard refresh for recovery"]);
- });
- }
- });
- } else {
- return push();
- }
- }
- let fakePush = {
- receives: [],
- receive(kind, cb) {
- this.receives.push([kind, cb]);
- }
- };
- setTimeout(() => {
- if (view.isDestroyed()) {
- return;
- }
- fakePush.receives.reduce((acc, [kind, cb]) => acc.receive(kind, cb), push());
- }, latency);
- return fakePush;
- }
- reloadWithJitter(view, log) {
- clearTimeout(this.reloadWithJitterTimer);
- this.disconnect();
- let minMs = this.reloadJitterMin;
- let maxMs = this.reloadJitterMax;
- let afterMs = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
- let tries = browser_default.updateLocal(this.localStorage, window.location.pathname, CONSECUTIVE_RELOADS, 0, (count) => count + 1);
- if (tries > this.maxReloads) {
- afterMs = this.failsafeJitter;
- }
- this.reloadWithJitterTimer = setTimeout(() => {
- if (view.isDestroyed() || view.isConnected()) {
- return;
- }
- view.destroy();
- log ? log() : this.log(view, "join", () => [`encountered ${tries} consecutive reloads`]);
- if (tries > this.maxReloads) {
- this.log(view, "join", () => [`exceeded ${this.maxReloads} consecutive reloads. Entering failsafe mode`]);
- }
- if (this.hasPendingLink()) {
- window.location = this.pendingLink;
- } else {
- window.location.reload();
- }
- }, afterMs);
- }
- getHookCallbacks(name) {
- return name && name.startsWith("Phoenix.") ? hooks_default[name.split(".")[1]] : this.hooks[name];
- }
- isUnloaded() {
- return this.unloaded;
- }
- isConnected() {
- return this.socket.isConnected();
- }
- getBindingPrefix() {
- return this.bindingPrefix;
- }
- binding(kind) {
- return `${this.getBindingPrefix()}${kind}`;
- }
- channel(topic, params) {
- return this.socket.channel(topic, params);
- }
- joinDeadView() {
- let body = document.body;
- if (body && !this.isPhxView(body) && !this.isPhxView(document.firstElementChild)) {
- let view = this.newRootView(body);
- view.setHref(this.getHref());
- view.joinDead();
- if (!this.main) {
- this.main = view;
- }
- window.requestAnimationFrame(() => view.execNewMounted());
- }
- }
- joinRootViews() {
- let rootsFound = false;
- dom_default.all(document, `${PHX_VIEW_SELECTOR}:not([${PHX_PARENT_ID}])`, (rootEl) => {
- if (!this.getRootById(rootEl.id)) {
- let view = this.newRootView(rootEl);
- view.setHref(this.getHref());
- view.join();
- if (rootEl.hasAttribute(PHX_MAIN)) {
- this.main = view;
- }
- }
- rootsFound = true;
- });
- return rootsFound;
- }
- redirect(to, flash) {
- this.unload();
- browser_default.redirect(to, flash);
- }
- replaceMain(href, flash, callback = null, linkRef = this.setPendingLink(href)) {
- let liveReferer = this.currentLocation.href;
- this.outgoingMainEl = this.outgoingMainEl || this.main.el;
- let newMainEl = dom_default.cloneNode(this.outgoingMainEl, "");
- this.main.showLoader(this.loaderTimeout);
- this.main.destroy();
- this.main = this.newRootView(newMainEl, flash, liveReferer);
- this.main.setRedirect(href);
- this.transitionRemoves();
- this.main.join((joinCount, onDone) => {
- if (joinCount === 1 && this.commitPendingLink(linkRef)) {
- this.requestDOMUpdate(() => {
- dom_default.findPhxSticky(document).forEach((el) => newMainEl.appendChild(el));
- this.outgoingMainEl.replaceWith(newMainEl);
- this.outgoingMainEl = null;
- callback && requestAnimationFrame(() => callback(linkRef));
- onDone();
- });
- }
- });
- }
- transitionRemoves(elements) {
- let removeAttr = this.binding("remove");
- elements = elements || dom_default.all(document, `[${removeAttr}]`);
- elements.forEach((el) => {
- this.execJS(el, el.getAttribute(removeAttr), "remove");
- });
- }
- isPhxView(el) {
- return el.getAttribute && el.getAttribute(PHX_SESSION) !== null;
- }
- newRootView(el, flash, liveReferer) {
- let view = new View(el, this, null, flash, liveReferer);
- this.roots[view.id] = view;
- return view;
- }
- owner(childEl, callback) {
- let view = maybe(childEl.closest(PHX_VIEW_SELECTOR), (el) => this.getViewByEl(el)) || this.main;
- if (view) {
- callback(view);
- }
- }
- withinOwners(childEl, callback) {
- this.owner(childEl, (view) => callback(view, childEl));
- }
- getViewByEl(el) {
- let rootId = el.getAttribute(PHX_ROOT_ID);
- return maybe(this.getRootById(rootId), (root) => root.getDescendentByEl(el));
- }
- getRootById(id) {
- return this.roots[id];
- }
- destroyAllViews() {
- for (let id in this.roots) {
- this.roots[id].destroy();
- delete this.roots[id];
- }
- this.main = null;
- }
- destroyViewByEl(el) {
- let root = this.getRootById(el.getAttribute(PHX_ROOT_ID));
- if (root && root.id === el.id) {
- root.destroy();
- delete this.roots[root.id];
- } else if (root) {
- root.destroyDescendent(el.id);
- }
- }
- setActiveElement(target) {
- if (this.activeElement === target) {
- return;
- }
- this.activeElement = target;
- let cancel = () => {
- if (target === this.activeElement) {
- this.activeElement = null;
- }
- target.removeEventListener("mouseup", this);
- target.removeEventListener("touchend", this);
- };
- target.addEventListener("mouseup", cancel);
- target.addEventListener("touchend", cancel);
- }
- getActiveElement() {
- if (document.activeElement === document.body) {
- return this.activeElement || document.activeElement;
- } else {
- return document.activeElement || document.body;
- }
- }
- dropActiveElement(view) {
- if (this.prevActive && view.ownsElement(this.prevActive)) {
- this.prevActive = null;
- }
- }
- restorePreviouslyActiveFocus() {
- if (this.prevActive && this.prevActive !== document.body) {
- this.prevActive.focus();
- }
- }
- blurActiveElement() {
- this.prevActive = this.getActiveElement();
- if (this.prevActive !== document.body) {
- this.prevActive.blur();
- }
- }
- bindTopLevelEvents({ dead } = {}) {
- if (this.boundTopLevelEvents) {
- return;
- }
- this.boundTopLevelEvents = true;
- this.socket.onClose((event) => {
- if (event && event.code === 1e3 && this.main) {
- return this.reloadWithJitter(this.main);
- }
- });
- document.body.addEventListener("click", function() {
- });
- window.addEventListener("pageshow", (e2) => {
- if (e2.persisted) {
- this.getSocket().disconnect();
- this.withPageLoading({ to: window.location.href, kind: "redirect" });
- window.location.reload();
- }
- }, true);
- if (!dead) {
- this.bindNav();
- }
- this.bindClicks();
- if (!dead) {
- this.bindForms();
- }
- this.bind({ keyup: "keyup", keydown: "keydown" }, (e2, type, view, targetEl, phxEvent, eventTarget) => {
- let matchKey = targetEl.getAttribute(this.binding(PHX_KEY));
- let pressedKey = e2.key && e2.key.toLowerCase();
- if (matchKey && matchKey.toLowerCase() !== pressedKey) {
- return;
- }
- let data = __spreadValues({ key: e2.key }, this.eventMeta(type, e2, targetEl));
- js_default.exec(type, phxEvent, view, targetEl, ["push", { data }]);
- });
- this.bind({ blur: "focusout", focus: "focusin" }, (e2, type, view, targetEl, phxEvent, eventTarget) => {
- if (!eventTarget) {
- let data = __spreadValues({ key: e2.key }, this.eventMeta(type, e2, targetEl));
- js_default.exec(type, phxEvent, view, targetEl, ["push", { data }]);
- }
- });
- this.bind({ blur: "blur", focus: "focus" }, (e2, type, view, targetEl, targetCtx, phxEvent, phxTarget) => {
- if (phxTarget === "window") {
- let data = this.eventMeta(type, e2, targetEl);
- js_default.exec(type, phxEvent, view, targetEl, ["push", { data }]);
- }
- });
- window.addEventListener("dragover", (e2) => e2.preventDefault());
- window.addEventListener("drop", (e2) => {
- e2.preventDefault();
- let dropTargetId = maybe(closestPhxBinding(e2.target, this.binding(PHX_DROP_TARGET)), (trueTarget) => {
- return trueTarget.getAttribute(this.binding(PHX_DROP_TARGET));
- });
- let dropTarget = dropTargetId && document.getElementById(dropTargetId);
- let files = Array.from(e2.dataTransfer.files || []);
- if (!dropTarget || dropTarget.disabled || files.length === 0 || !(dropTarget.files instanceof FileList)) {
- return;
- }
- LiveUploader.trackFiles(dropTarget, files, e2.dataTransfer);
- dropTarget.dispatchEvent(new Event("input", { bubbles: true }));
- });
- this.on(PHX_TRACK_UPLOADS, (e2) => {
- let uploadTarget = e2.target;
- if (!dom_default.isUploadInput(uploadTarget)) {
- return;
- }
- let files = Array.from(e2.detail.files || []).filter((f2) => f2 instanceof File || f2 instanceof Blob);
- LiveUploader.trackFiles(uploadTarget, files);
- uploadTarget.dispatchEvent(new Event("input", { bubbles: true }));
- });
- }
- eventMeta(eventName, e2, targetEl) {
- let callback = this.metadataCallbacks[eventName];
- return callback ? callback(e2, targetEl) : {};
- }
- setPendingLink(href) {
- this.linkRef++;
- this.pendingLink = href;
- return this.linkRef;
- }
- commitPendingLink(linkRef) {
- if (this.linkRef !== linkRef) {
- return false;
- } else {
- this.href = this.pendingLink;
- this.pendingLink = null;
- return true;
- }
- }
- getHref() {
- return this.href;
- }
- hasPendingLink() {
- return !!this.pendingLink;
- }
- bind(events, callback) {
- for (let event in events) {
- let browserEventName = events[event];
- this.on(browserEventName, (e2) => {
- let binding = this.binding(event);
- let windowBinding = this.binding(`window-${event}`);
- let targetPhxEvent = e2.target.getAttribute && e2.target.getAttribute(binding);
- if (targetPhxEvent) {
- this.debounce(e2.target, e2, browserEventName, () => {
- this.withinOwners(e2.target, (view) => {
- callback(e2, event, view, e2.target, targetPhxEvent, null);
- });
- });
- } else {
- dom_default.all(document, `[${windowBinding}]`, (el) => {
- let phxEvent = el.getAttribute(windowBinding);
- this.debounce(el, e2, browserEventName, () => {
- this.withinOwners(el, (view) => {
- callback(e2, event, view, el, phxEvent, "window");
- });
- });
- });
- }
- });
- }
- }
- bindClicks() {
- window.addEventListener("click", (e2) => this.clickStartedAtTarget = e2.target);
- this.bindClick("click", "click", false);
- this.bindClick("mousedown", "capture-click", true);
- }
- bindClick(eventName, bindingName, capture) {
- let click = this.binding(bindingName);
- window.addEventListener(eventName, (e2) => {
- let target = null;
- if (capture) {
- target = e2.target.matches(`[${click}]`) ? e2.target : e2.target.querySelector(`[${click}]`);
- } else {
- let clickStartedAtTarget = this.clickStartedAtTarget || e2.target;
- target = closestPhxBinding(clickStartedAtTarget, click);
- this.dispatchClickAway(e2, clickStartedAtTarget);
- this.clickStartedAtTarget = null;
- }
- let phxEvent = target && target.getAttribute(click);
- if (!phxEvent) {
- if (!capture && dom_default.isNewPageClick(e2, window.location)) {
- this.unload();
- }
- return;
- }
- if (target.getAttribute("href") === "#") {
- e2.preventDefault();
- }
- if (target.hasAttribute(PHX_REF)) {
- return;
- }
- this.debounce(target, e2, "click", () => {
- this.withinOwners(target, (view) => {
- js_default.exec("click", phxEvent, view, target, ["push", { data: this.eventMeta("click", e2, target) }]);
- });
- });
- }, capture);
- }
- dispatchClickAway(e2, clickStartedAt) {
- let phxClickAway = this.binding("click-away");
- dom_default.all(document, `[${phxClickAway}]`, (el) => {
- if (!(el.isSameNode(clickStartedAt) || el.contains(clickStartedAt))) {
- this.withinOwners(e2.target, (view) => {
- let phxEvent = el.getAttribute(phxClickAway);
- if (js_default.isVisible(el)) {
- js_default.exec("click", phxEvent, view, el, ["push", { data: this.eventMeta("click", e2, e2.target) }]);
- }
- });
- }
- });
- }
- bindNav() {
- if (!browser_default.canPushState()) {
- return;
- }
- if (history.scrollRestoration) {
- history.scrollRestoration = "manual";
- }
- let scrollTimer = null;
- window.addEventListener("scroll", (_e2) => {
- clearTimeout(scrollTimer);
- scrollTimer = setTimeout(() => {
- browser_default.updateCurrentState((state) => Object.assign(state, { scroll: window.scrollY }));
- }, 100);
- });
- window.addEventListener("popstate", (event) => {
- if (!this.registerNewLocation(window.location)) {
- return;
- }
- let { type, id, root, scroll } = event.state || {};
- let href = window.location.href;
- dom_default.dispatchEvent(window, "phx:navigate", { detail: { href, patch: type === "patch", pop: true } });
- this.requestDOMUpdate(() => {
- if (this.main.isConnected() && (type === "patch" && id === this.main.id)) {
- this.main.pushLinkPatch(href, null, () => {
- this.maybeScroll(scroll);
- });
- } else {
- this.replaceMain(href, null, () => {
- if (root) {
- this.replaceRootHistory();
- }
- this.maybeScroll(scroll);
- });
- }
- });
- }, false);
- window.addEventListener("click", (e2) => {
- let target = closestPhxBinding(e2.target, PHX_LIVE_LINK);
- let type = target && target.getAttribute(PHX_LIVE_LINK);
- if (!type || !this.isConnected() || !this.main || dom_default.wantsNewTab(e2)) {
- return;
- }
- let href = target.href;
- let linkState = target.getAttribute(PHX_LINK_STATE);
- e2.preventDefault();
- e2.stopImmediatePropagation();
- if (this.pendingLink === href) {
- return;
- }
- this.requestDOMUpdate(() => {
- if (type === "patch") {
- this.pushHistoryPatch(href, linkState, target);
- } else if (type === "redirect") {
- this.historyRedirect(href, linkState);
- } else {
- throw new Error(`expected ${PHX_LIVE_LINK} to be "patch" or "redirect", got: ${type}`);
- }
- let phxClick = target.getAttribute(this.binding("click"));
- if (phxClick) {
- this.requestDOMUpdate(() => this.execJS(target, phxClick, "click"));
- }
- });
- }, false);
- }
- maybeScroll(scroll) {
- if (typeof scroll === "number") {
- requestAnimationFrame(() => {
- window.scrollTo(0, scroll);
- });
- }
- }
- dispatchEvent(event, payload = {}) {
- dom_default.dispatchEvent(window, `phx:${event}`, { detail: payload });
- }
- dispatchEvents(events) {
- events.forEach(([event, payload]) => this.dispatchEvent(event, payload));
- }
- withPageLoading(info, callback) {
- dom_default.dispatchEvent(window, "phx:page-loading-start", { detail: info });
- let done = () => dom_default.dispatchEvent(window, "phx:page-loading-stop", { detail: info });
- return callback ? callback(done) : done;
- }
- pushHistoryPatch(href, linkState, targetEl) {
- if (!this.isConnected()) {
- return browser_default.redirect(href);
- }
- this.withPageLoading({ to: href, kind: "patch" }, (done) => {
- this.main.pushLinkPatch(href, targetEl, (linkRef) => {
- this.historyPatch(href, linkState, linkRef);
- done();
- });
- });
- }
- historyPatch(href, linkState, linkRef = this.setPendingLink(href)) {
- if (!this.commitPendingLink(linkRef)) {
- return;
- }
- browser_default.pushState(linkState, { type: "patch", id: this.main.id }, href);
- dom_default.dispatchEvent(window, "phx:navigate", { detail: { patch: true, href, pop: false } });
- this.registerNewLocation(window.location);
- }
- historyRedirect(href, linkState, flash) {
- if (!this.isConnected()) {
- return browser_default.redirect(href, flash);
- }
- if (/^\/$|^\/[^\/]+.*$/.test(href)) {
- let { protocol, host } = window.location;
- href = `${protocol}//${host}${href}`;
- }
- let scroll = window.scrollY;
- this.withPageLoading({ to: href, kind: "redirect" }, (done) => {
- this.replaceMain(href, flash, (linkRef) => {
- if (linkRef === this.linkRef) {
- browser_default.pushState(linkState, { type: "redirect", id: this.main.id, scroll }, href);
- dom_default.dispatchEvent(window, "phx:navigate", { detail: { href, patch: false, pop: false } });
- this.registerNewLocation(window.location);
- }
- done();
- });
- });
- }
- replaceRootHistory() {
- browser_default.pushState("replace", { root: true, type: "patch", id: this.main.id });
- }
- registerNewLocation(newLocation) {
- let { pathname, search } = this.currentLocation;
- if (pathname + search === newLocation.pathname + newLocation.search) {
- return false;
- } else {
- this.currentLocation = clone(newLocation);
- return true;
- }
- }
- bindForms() {
- let iterations = 0;
- let externalFormSubmitted = false;
- this.on("submit", (e2) => {
- let phxSubmit = e2.target.getAttribute(this.binding("submit"));
- let phxChange = e2.target.getAttribute(this.binding("change"));
- if (!externalFormSubmitted && phxChange && !phxSubmit) {
- externalFormSubmitted = true;
- e2.preventDefault();
- this.withinOwners(e2.target, (view) => {
- view.disableForm(e2.target);
- window.requestAnimationFrame(() => {
- if (dom_default.isUnloadableFormSubmit(e2)) {
- this.unload();
- }
- e2.target.submit();
- });
- });
- }
- }, true);
- this.on("submit", (e2) => {
- let phxEvent = e2.target.getAttribute(this.binding("submit"));
- if (!phxEvent) {
- if (dom_default.isUnloadableFormSubmit(e2)) {
- this.unload();
- }
- return;
- }
- e2.preventDefault();
- e2.target.disabled = true;
- this.withinOwners(e2.target, (view) => {
- js_default.exec("submit", phxEvent, view, e2.target, ["push", { submitter: e2.submitter }]);
- });
- }, false);
- for (let type of ["change", "input"]) {
- this.on(type, (e2) => {
- let phxChange = this.binding("change");
- let input = e2.target;
- let inputEvent = input.getAttribute(phxChange);
- let formEvent = input.form && input.form.getAttribute(phxChange);
- let phxEvent = inputEvent || formEvent;
- if (!phxEvent) {
- return;
- }
- if (input.type === "number" && input.validity && input.validity.badInput) {
- return;
- }
- let dispatcher = inputEvent ? input : input.form;
- let currentIterations = iterations;
- iterations++;
- let { at: at2, type: lastType } = dom_default.private(input, "prev-iteration") || {};
- if (at2 === currentIterations - 1 && type === "change" && lastType === "input") {
- return;
- }
- dom_default.putPrivate(input, "prev-iteration", { at: currentIterations, type });
- this.debounce(input, e2, type, () => {
- this.withinOwners(dispatcher, (view) => {
- dom_default.putPrivate(input, PHX_HAS_FOCUSED, true);
- if (!dom_default.isTextualInput(input)) {
- this.setActiveElement(input);
- }
- js_default.exec("change", phxEvent, view, input, ["push", { _target: e2.target.name, dispatcher }]);
- });
- });
- }, false);
- }
- this.on("reset", (e2) => {
- let form = e2.target;
- dom_default.resetForm(form, this.binding(PHX_FEEDBACK_FOR));
- let input = Array.from(form.elements).find((el) => el.type === "reset");
- window.requestAnimationFrame(() => {
- input.dispatchEvent(new Event("input", { bubbles: true, cancelable: false }));
- });
- });
- }
- debounce(el, event, eventType, callback) {
- if (eventType === "blur" || eventType === "focusout") {
- return callback();
- }
- let phxDebounce = this.binding(PHX_DEBOUNCE);
- let phxThrottle = this.binding(PHX_THROTTLE);
- let defaultDebounce = this.defaults.debounce.toString();
- let defaultThrottle = this.defaults.throttle.toString();
- this.withinOwners(el, (view) => {
- let asyncFilter = () => !view.isDestroyed() && document.body.contains(el);
- dom_default.debounce(el, event, phxDebounce, defaultDebounce, phxThrottle, defaultThrottle, asyncFilter, () => {
- callback();
- });
- });
- }
- silenceEvents(callback) {
- this.silenced = true;
- callback();
- this.silenced = false;
- }
- on(event, callback) {
- window.addEventListener(event, (e2) => {
- if (!this.silenced) {
- callback(e2);
- }
- });
- }
- };
- var TransitionSet = class {
- constructor() {
- this.transitions = /* @__PURE__ */ new Set();
- this.pendingOps = [];
- }
- reset() {
- this.transitions.forEach((timer) => {
- clearTimeout(timer);
- this.transitions.delete(timer);
- });
- this.flushPendingOps();
- }
- after(callback) {
- if (this.size() === 0) {
- callback();
- } else {
- this.pushPendingOp(callback);
- }
- }
- addTransition(time, onStart, onDone) {
- onStart();
- let timer = setTimeout(() => {
- this.transitions.delete(timer);
- onDone();
- this.flushPendingOps();
- }, time);
- this.transitions.add(timer);
- }
- pushPendingOp(op) {
- this.pendingOps.push(op);
- }
- size() {
- return this.transitions.size;
- }
- flushPendingOps() {
- if (this.size() > 0) {
- return;
- }
- let op = this.pendingOps.shift();
- if (op) {
- op();
- this.flushPendingOps();
- }
- }
- };
-
- // node_modules/blurhash/dist/esm/base83.js
- var digitCharacters = [
- "0",
- "1",
- "2",
- "3",
- "4",
- "5",
- "6",
- "7",
- "8",
- "9",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
- "M",
- "N",
- "O",
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
- "m",
- "n",
- "o",
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "#",
- "$",
- "%",
- "*",
- "+",
- ",",
- "-",
- ".",
- ":",
- ";",
- "=",
- "?",
- "@",
- "[",
- "]",
- "^",
- "_",
- "{",
- "|",
- "}",
- "~"
- ];
- var decode83 = (str) => {
- let value = 0;
- for (let i2 = 0; i2 < str.length; i2++) {
- const c2 = str[i2];
- const digit = digitCharacters.indexOf(c2);
- value = value * 83 + digit;
- }
- return value;
- };
-
- // node_modules/blurhash/dist/esm/utils.js
- var sRGBToLinear = (value) => {
- let v2 = value / 255;
- if (v2 <= 0.04045) {
- return v2 / 12.92;
- } else {
- return Math.pow((v2 + 0.055) / 1.055, 2.4);
- }
- };
- var linearTosRGB = (value) => {
- let v2 = Math.max(0, Math.min(1, value));
- if (v2 <= 31308e-7) {
- return Math.round(v2 * 12.92 * 255 + 0.5);
- } else {
- return Math.round((1.055 * Math.pow(v2, 1 / 2.4) - 0.055) * 255 + 0.5);
- }
- };
- var sign = (n2) => n2 < 0 ? -1 : 1;
- var signPow = (val, exp) => sign(val) * Math.pow(Math.abs(val), exp);
-
- // node_modules/blurhash/dist/esm/error.js
- var ValidationError = class extends Error {
- constructor(message) {
- super(message);
- this.name = "ValidationError";
- this.message = message;
- }
- };
-
- // node_modules/blurhash/dist/esm/decode.js
- var validateBlurhash = (blurhash) => {
- if (!blurhash || blurhash.length < 6) {
- throw new ValidationError("The blurhash string must be at least 6 characters");
- }
- const sizeFlag = decode83(blurhash[0]);
- const numY = Math.floor(sizeFlag / 9) + 1;
- const numX = sizeFlag % 9 + 1;
- if (blurhash.length !== 4 + 2 * numX * numY) {
- throw new ValidationError(`blurhash length mismatch: length is ${blurhash.length} but it should be ${4 + 2 * numX * numY}`);
- }
- };
- var decodeDC = (value) => {
- const intR = value >> 16;
- const intG = value >> 8 & 255;
- const intB = value & 255;
- return [sRGBToLinear(intR), sRGBToLinear(intG), sRGBToLinear(intB)];
- };
- var decodeAC = (value, maximumValue) => {
- const quantR = Math.floor(value / (19 * 19));
- const quantG = Math.floor(value / 19) % 19;
- const quantB = value % 19;
- const rgb = [
- signPow((quantR - 9) / 9, 2) * maximumValue,
- signPow((quantG - 9) / 9, 2) * maximumValue,
- signPow((quantB - 9) / 9, 2) * maximumValue
- ];
- return rgb;
- };
- var decode = (blurhash, width, height, punch) => {
- validateBlurhash(blurhash);
- punch = punch | 1;
- const sizeFlag = decode83(blurhash[0]);
- const numY = Math.floor(sizeFlag / 9) + 1;
- const numX = sizeFlag % 9 + 1;
- const quantisedMaximumValue = decode83(blurhash[1]);
- const maximumValue = (quantisedMaximumValue + 1) / 166;
- const colors = new Array(numX * numY);
- for (let i2 = 0; i2 < colors.length; i2++) {
- if (i2 === 0) {
- const value = decode83(blurhash.substring(2, 6));
- colors[i2] = decodeDC(value);
- } else {
- const value = decode83(blurhash.substring(4 + i2 * 2, 6 + i2 * 2));
- colors[i2] = decodeAC(value, maximumValue * punch);
- }
- }
- const bytesPerRow = width * 4;
- const pixels = new Uint8ClampedArray(bytesPerRow * height);
- for (let y2 = 0; y2 < height; y2++) {
- for (let x2 = 0; x2 < width; x2++) {
- let r2 = 0;
- let g2 = 0;
- let b2 = 0;
- for (let j2 = 0; j2 < numY; j2++) {
- for (let i2 = 0; i2 < numX; i2++) {
- const basis = Math.cos(Math.PI * x2 * i2 / width) * Math.cos(Math.PI * y2 * j2 / height);
- let color = colors[i2 + j2 * numX];
- r2 += color[0] * basis;
- g2 += color[1] * basis;
- b2 += color[2] * basis;
- }
- }
- let intR = linearTosRGB(r2);
- let intG = linearTosRGB(g2);
- let intB = linearTosRGB(b2);
- pixels[4 * x2 + 0 + y2 * bytesPerRow] = intR;
- pixels[4 * x2 + 1 + y2 * bytesPerRow] = intG;
- pixels[4 * x2 + 2 + y2 * bytesPerRow] = intB;
- pixels[4 * x2 + 3 + y2 * bytesPerRow] = 255;
- }
- }
- return pixels;
- };
- var decode_default = decode;
-
- // js/apns.js
- var registerAPNSDeviceToken = (deviceToken) => {
- fetch("/api/apns-token", {
- method: "post",
- headers: {
- "Content-type": "application/json"
- },
- body: JSON.stringify({ device_token: deviceToken })
- });
- };
-
- // js/100vh-fix.js
- function setDocHeight() {
- document.documentElement.style.setProperty(
- "--vh",
- `${window.innerHeight / 100}px`
- );
- }
- ["resize", "orientationchange", "DOMContentLoaded"].forEach((eventName) => {
- window.addEventListener(eventName, setDocHeight);
- });
-
- // js/viewport_resize.js
- var import_lodash2 = __toESM(require_lodash());
- var resizeHandler;
- var ViewportResize = {
- mounted() {
- this.pushResizeEvent();
- window.addEventListener("resize", (event) => {
- this.pushResizeEvent();
- });
- },
- pushResizeEvent() {
- console.log("pushResizeEvent");
- this.pushEvent("viewport_resize", {
- width: window.innerWidth,
- height: window.innerHeight
- });
- },
- turbolinksDisconnected() {
- window.removeEventListener("resize", resizeHandler);
- }
- };
-
- // js/side_panel.js
- var maxBottomMargin = 63;
- var SidePanel = {
- mounted() {
- this.mainContent = document.getElementById("main-content");
- this.parent = document.getElementById(this.el.dataset.parent);
- this.panel = this.el.getElementsByClassName("panel")[0];
- this.panel.style = `position: fixed; height: 0px; top: 0px`;
- this.updateFrame();
- new ResizeObserver(() => {
- this.updateFrame();
- }).observe(this.parent);
- this.mainContent.addEventListener("scroll", (event) => {
- this.updateFrame();
- });
- window.addEventListener("resize", (event) => {
- this.updateFrame();
- });
- window.addEventListener("tab-activated", (event) => {
- this.updateFrame();
- });
- },
- updated() {
- this.updateFrame();
- },
- updateFrame() {
- const bottomDistance = this.mainContent.scrollHeight - this.mainContent.scrollTop - window.innerHeight;
- const bottomMargin = maxBottomMargin - Math.min(maxBottomMargin, bottomDistance);
- const topMargin = Math.max(0, this.parent.getBoundingClientRect().top);
- const height = window.innerHeight - (topMargin + bottomMargin);
- this.panel.style = `position: fixed; height: ${height}px; top: ${topMargin}px`;
- }
- };
-
- // js/toggle.js
- var Toggle = {
- mounted() {
- this.targetId = this.el.getAttribute("target");
- this.target = document.getElementById(this.targetId);
- this.target.style.display = "none";
- document.addEventListener("click", (event) => {
- if (event.target === this.el) {
- if (this.target.style.display !== "block") {
- this.target.style.display = "block";
- } else {
- this.target.style.display = "none";
- }
- } else if (event.target === this.target) {
- } else {
- this.target.style.display = "none";
- }
- });
- }
- };
-
- // js/cell.js
- var COLLAPSED = "collapsed";
- var EXPANDED = "expanded";
- var COLLAPSED_VIEW = "cell-collapsed-view";
- var EXPANDED_VIEW = "cell-expanded-view";
- var COLLAPSE_BUTTON = "cell-collapse-button";
- var EXPAND_BUTTON = "cell-expand-button";
- var Cell = {
- mounted() {
- this.collapseButton = this.el.getElementsByClassName(COLLAPSE_BUTTON)[0];
- this.collapsedView = this.el.getElementsByClassName(COLLAPSED_VIEW)[0];
- this.expandButton = this.el.getElementsByClassName(EXPAND_BUTTON)[0];
- this.expandedView = this.el.getElementsByClassName(EXPANDED_VIEW)[0];
- this.collapseButton.addEventListener("click", (event) => {
- event.stopPropagation();
- this.updateStatus(COLLAPSED);
- });
- this.expandButton.addEventListener("click", (event) => {
- event.stopPropagation();
- this.updateStatus(EXPANDED);
- });
- var initialStatus = this.el.dataset.initialStatus ? this.el.dataset.initialTab : COLLAPSED;
- var savedStatus = this.loadStatus();
- this.status = savedStatus ? savedStatus : initialStatus;
- this.updateUI();
- },
- updated() {
- this.updateUI();
- },
- loadStatus() {
- const key = this.getStatusKey();
- const status = window.localStorage.getItem(key);
- if (typeof status === "string") {
- return status;
- }
- return void 0;
- },
- saveStatus() {
- console.info("saveStatus ", this.status);
- window.localStorage.setItem(this.getStatusKey(), this.status);
- },
- getStatusKey() {
- return "cell://" + this.el.id + "/status";
- },
- updateStatus(status) {
- this.status = status;
- this.saveStatus();
- this.updateUI();
- },
- updateUI() {
- if (this.status == EXPANDED) {
- this.hide(this.collapsedView);
- this.show(this.expandedView);
- } else {
- this.show(this.collapsedView);
- this.hide(this.expandedView);
- }
- },
- hide(element) {
- if (!element.classList.contains("hidden")) {
- element.classList.add("hidden");
- }
- },
- show(element) {
- element.classList.remove("hidden");
- }
- };
-
- // js/live_content.js
- var STATIC_CLASS_ATTR = "__eyra_field_static_class";
- var HAS_ERRORS_ATTR = "__eyra_field_has_errors";
- var ACTIVE_COLOR_ATTR = "__eyra_field_active_color";
- var FIELD_LABEL_TYPE = "field-label";
- var FIELD_INPUT_TYPE = "field-input";
- var FIELD_ERROR_TYPE = "field-error";
- var DATA_SHOW_ERRORS = "data-show-errors";
- var LABEL_IDLE = "text-grey1";
- var LABEL_ERROR = "text-warning";
- var INPUT_IDLE = "border-grey3";
- var INPUT_ERROR = "border-warning";
- var HIDDEN = "hidden";
- var LiveContent = {
- mounted() {
- console.log("LiveContent mounted", this.el);
- this.showErrors = this.el.getAttribute(DATA_SHOW_ERRORS) != null;
- this.activeField = void 0;
- this.el.addEventListener("click", (event) => {
- this.activeField = void 0;
- this.applyActiveField();
- });
- this.el.addEventListener("field-activated", (event) => {
- event.stopPropagation();
- this.activeField = event.target.dataset.fieldId;
- this.applyActiveField();
- });
- this.el.addEventListener("field-deactivated", (event) => {
- event.stopPropagation();
- if (this.activeField == event.target.id) {
- this.activeField = void 0;
- this.applyActiveField();
- }
- });
- this.applyErrors();
- this.applyActiveField();
- },
- updated() {
- this.showErrors = this.el.getAttribute(DATA_SHOW_ERRORS) != null;
- this.applyErrors();
- this.applyActiveField();
- },
- onBeforeElUpdated(from, to) {
- const field_id = from.getAttribute("__eyra_field_id");
- if (field_id != null) {
- to.classList = from.classList;
- }
- },
- applyErrors() {
- const fieldErrors = Array.from(
- this.el.querySelectorAll(`.${FIELD_ERROR_TYPE}`)
- );
- console.log("fieldErrors", fieldErrors);
- if (this.showErrors) {
- fieldErrors.forEach((fieldError) => fieldError.classList.remove(HIDDEN));
- } else {
- fieldErrors.forEach((fieldError) => fieldError.classList.add(HIDDEN));
- }
- },
- updateFieldItem(fieldItem, activate) {
- const hasErrors = fieldItem.getAttribute(HAS_ERRORS_ATTR) != null;
- if (fieldItem.classList.contains(FIELD_LABEL_TYPE)) {
- this.updateFieldLabel(fieldItem, activate, hasErrors);
- } else if (fieldItem.classList.contains(FIELD_INPUT_TYPE)) {
- this.updateFieldInput(fieldItem, activate, hasErrors);
- }
- },
- applyActiveField() {
- var fields = Array.from(this.el.querySelectorAll('[id^="field-"]'));
- fields.forEach((field) => {
- var activate = field.dataset.fieldId === this.activeField;
- this.updateField(field, activate);
- });
- },
- updateField(field, activate) {
- const label = field.getElementsByClassName(FIELD_LABEL_TYPE)[0];
- const input = field.getElementsByClassName(FIELD_INPUT_TYPE)[0];
- const hasErrors = field.getElementsByClassName(FIELD_ERROR_TYPE)[0] != null;
- if (label) {
- this.updateFieldLabel(label, activate, hasErrors);
- }
- if (input) {
- this.updateFieldInput(input, activate, hasErrors);
- }
- },
- updateFieldLabel(label, activate, hasErrors) {
- this.updateFieldItemClass(
- label,
- activate,
- hasErrors,
- LABEL_IDLE,
- LABEL_ERROR
- );
- },
- updateFieldInput(input, activate, hasErrors) {
- this.updateFieldItemClass(
- input,
- activate,
- hasErrors,
- INPUT_IDLE,
- INPUT_ERROR
- );
- },
- updateFieldItemClass(fieldItem, activate, hasErrors, idle_class, error_class) {
- var dynamic_class = idle_class;
- if (activate) {
- dynamic_class = fieldItem.getAttribute(ACTIVE_COLOR_ATTR);
- } else if (this.showErrors && hasErrors) {
- dynamic_class = error_class;
- }
- const static_class = fieldItem.getAttribute(STATIC_CLASS_ATTR);
- fieldItem.setAttribute("class", static_class + " " + dynamic_class);
- }
- };
- var LiveField = {
- mounted() {
- console.log("LiveField mounted");
- const input = this.el.getElementsByClassName(FIELD_INPUT_TYPE)[0];
- if (input) {
- input.addEventListener("click", (event) => {
- event.stopPropagation();
- this.activate();
- });
- input.addEventListener("focus", (event) => {
- event.stopPropagation();
- this.activate();
- });
- input.addEventListener("blur", (event) => {
- event.stopPropagation();
- this.deactivate();
- });
- }
- },
- activate() {
- this.el.dispatchEvent(new Event("field-activated", { bubbles: true }));
- },
- deactivate() {
- this.el.dispatchEvent(new Event("field-deactivated", { bubbles: true }));
- }
- };
-
- // js/tabbar.js
- var tabbarId = "";
- var Tabbar = {
- mounted() {
- tabbarId = this.el.id;
- var initialTabId = this.el.dataset.initialTab ? "tab_" + this.el.dataset.initialTab : void 0;
- var savedTabId = this.loadActiveTab();
- var firstTabId = this.getFirstTab();
- var nextTabId = initialTabId ? initialTabId : savedTabId ? savedTabId : firstTabId;
- this.show(nextTabId, true);
- },
- updated() {
- var savedTabId = this.loadActiveTab();
- this.show(savedTabId, false);
- },
- getActiveTabKey() {
- return "tabbar://" + tabbarId + "/active_tab";
- },
- loadActiveTab() {
- const tabKey = this.getActiveTabKey();
- const activeTab = window.localStorage.getItem(tabKey);
- if (typeof activeTab === "string") {
- return activeTab;
- }
- return void 0;
- },
- saveActiveTab(tabId) {
- console.info("saveActiveTab ", tabId);
- window.localStorage.setItem(this.getActiveTabKey(), tabId);
- },
- getFirstTab() {
- var firstTab = document.querySelectorAll('[id^="tab_"]')[0];
- return firstTab.id;
- },
- show(nextTabId, scrollToTop) {
- this.saveActiveTab(nextTabId);
- var tabs = Array.from(document.querySelectorAll('[id^="tab_"]'));
- if (!tabs.some((tab) => tab.id === nextTabId)) {
- console.warn("Skip unknown tab", nextTabId);
- return;
- }
- tabs.forEach((tab) => {
- var isVisible = tab.id === nextTabId;
- setVisible(tab, isVisible);
- if (isVisible) {
- tab.dispatchEvent(new Event("tab-activated", { bubbles: true }));
- }
- });
- var tabbar_items = Array.from(
- document.getElementsByClassName("tabbar-item")
- );
- tabbar_items.forEach((tabbar_item) => {
- var tab_id = "tab_" + tabbar_item.dataset.tabId;
- updateTabbarItem(tabbar_item, tab_id === nextTabId);
- });
- var tabbar_footer_items = Array.from(
- document.getElementsByClassName("tabbar-footer-item")
- );
- tabbar_footer_items.forEach((tabbar_footer_item) => {
- var tab_id = "tab_" + tabbar_footer_item.dataset.tabId;
- var isVisible = tab_id === nextTabId;
- setVisible(tabbar_footer_item, isVisible);
- });
- if (scrollToTop) {
- window.scrollTo(0, 0);
- }
- }
- };
- var TabbarItem = {
- mounted() {
- this.el.addEventListener("click", (event) => {
- this.tabbar = document.getElementById("tabbar");
- Tabbar.show("tab_" + this.el.dataset.tabId, true);
- });
- }
- };
- var TabbarFooterItem = {
- mounted() {
- this.el.addEventListener("click", (event) => {
- this.tabbar = document.getElementById("tabbar");
- Tabbar.show("tab_" + this.el.dataset.targetTabId, true);
- });
- }
- };
- function setVisible(element, isVisible) {
- element.classList[isVisible ? "remove" : "add"]("hidden");
- }
- function updateTabbarItem(tabbar_item, activate) {
- var hideWhenIdle = Array.from(tabbar_item.classList).filter((clazz) => {
- return clazz === "hide-when-idle";
- }).length > 0;
- if (hideWhenIdle) {
- setVisible(tabbar_item, activate);
- }
- var icon = tabbar_item.getElementsByClassName("icon")[0];
- var title = tabbar_item.getElementsByClassName("title")[0];
- updateElement(tabbar_item, activate);
- if (icon) {
- updateElement(icon, activate);
- }
- updateElement(title, activate);
- }
- function updateElement(element, activate) {
- if (!element) {
- return console.warn("Unknown element");
- }
- var idle_classes = customClasses(element, "idle");
- var active_classes = customClasses(element, "active");
- if (activate) {
- updateClassList(element, idle_classes, "remove");
- updateClassList(element, active_classes, "add");
- } else {
- updateClassList(element, active_classes, "remove");
- updateClassList(element, idle_classes, "add");
- }
- }
- function customClasses(element, name) {
- return element.getAttribute(name + "-class").split(" ");
- }
- function updateClassList(element, classes, type) {
- classes.forEach((clazz) => {
- element.classList[type](clazz);
- });
- }
-
- // js/clipboard.js
- var Clipboard = {
- mounted() {
- this.textToCopy = this.el.getAttribute("data-text");
- this.el.addEventListener("click", (event) => {
- event.stopPropagation();
- const textArea = document.createElement("textarea");
- textArea.value = this.textToCopy;
- textArea.setAttribute("readonly", "");
- textArea.style.position = "absolute";
- textArea.style.left = "-9999px";
- document.body.appendChild(textArea);
- textArea.select();
- document.execCommand("copy");
- document.body.removeChild(textArea);
- });
- },
- updated() {
- this.textToCopy = this.el.getAttribute("data-text");
- }
- };
-
- // js/feldspar_app.js
- var FeldsparApp = {
- mounted() {
- console.log("[FeldsparApp] Mounted");
- console.log(this.el.dataset);
- const iframe = this.getIframe();
- iframe.addEventListener("load", () => {
- this.onFrameLoaded();
- });
- iframe.setAttribute("src", this.el.dataset.src);
- window.addEventListener("message", function(event) {
- if (event.data.action === "resize") {
- console.log("[FeldsparApp] resize event:", event.data.height);
- iframe.setAttribute("style", `height:${event.data.height}px`);
- }
- });
- },
- getIframe() {
- return this.el.querySelector("iframe");
- },
- onFrameLoaded() {
- console.log("[FeldsparApp] Initializing iframe app");
- this.channel = new MessageChannel();
- this.channel.port1.onmessage = (e2) => {
- this.handleMessage(e2);
- };
- let action = "live-init";
- let locale = this.el.dataset.locale;
- const iframe = this.getIframe();
- iframe.contentWindow.postMessage({ action, locale }, "*", [
- this.channel.port2
- ]);
- },
- handleMessage(e2) {
- this.pushEvent("feldspar_event", e2.data);
- }
- };
-
- // node_modules/trix/dist/trix.esm.min.js
- var t = "2.0.8";
- var e = "[data-trix-attachment]";
- var i = { preview: { presentation: "gallery", caption: { name: true, size: true } }, file: { caption: { size: true } } };
- var n = { default: { tagName: "div", parse: false }, quote: { tagName: "blockquote", nestable: true }, heading1: { tagName: "h1", terminal: true, breakOnReturn: true, group: false }, code: { tagName: "pre", terminal: true, text: { plaintext: true } }, bulletList: { tagName: "ul", parse: false }, bullet: { tagName: "li", listAttribute: "bulletList", group: false, nestable: true, test(t2) {
- return r(t2.parentNode) === n[this.listAttribute].tagName;
- } }, numberList: { tagName: "ol", parse: false }, number: { tagName: "li", listAttribute: "numberList", group: false, nestable: true, test(t2) {
- return r(t2.parentNode) === n[this.listAttribute].tagName;
- } }, attachmentGallery: { tagName: "div", exclusive: true, terminal: true, parse: false, group: false } };
- var r = (t2) => {
- var e2;
- return null == t2 || null === (e2 = t2.tagName) || void 0 === e2 ? void 0 : e2.toLowerCase();
- };
- var o = navigator.userAgent.match(/android\s([0-9]+.*Chrome)/i);
- var s = o && parseInt(o[1]);
- var a = { composesExistingText: /Android.*Chrome/.test(navigator.userAgent), recentAndroid: s && s > 12, samsungAndroid: s && navigator.userAgent.match(/Android.*SM-/), forcesObjectResizing: /Trident.*rv:11/.test(navigator.userAgent), supportsInputEvents: "undefined" != typeof InputEvent && ["data", "getTargetRanges", "inputType"].every((t2) => t2 in InputEvent.prototype) };
- var l = { attachFiles: "Attach Files", bold: "Bold", bullets: "Bullets", byte: "Byte", bytes: "Bytes", captionPlaceholder: "Add a caption\u2026", code: "Code", heading1: "Heading", indent: "Increase Level", italic: "Italic", link: "Link", numbers: "Numbers", outdent: "Decrease Level", quote: "Quote", redo: "Redo", remove: "Remove", strike: "Strikethrough", undo: "Undo", unlink: "Unlink", url: "URL", urlPlaceholder: "Enter a URL\u2026", GB: "GB", KB: "KB", MB: "MB", PB: "PB", TB: "TB" };
- var c = [l.bytes, l.KB, l.MB, l.GB, l.TB, l.PB];
- var h = { prefix: "IEC", precision: 2, formatter(t2) {
- switch (t2) {
- case 0:
- return "0 ".concat(l.bytes);
- case 1:
- return "1 ".concat(l.byte);
- default:
- let e2;
- "SI" === this.prefix ? e2 = 1e3 : "IEC" === this.prefix && (e2 = 1024);
- const i2 = Math.floor(Math.log(t2) / Math.log(e2)), n2 = (t2 / Math.pow(e2, i2)).toFixed(this.precision).replace(/0*$/, "").replace(/\.$/, "");
- return "".concat(n2, " ").concat(c[i2]);
- }
- } };
- var u = "\uFEFF";
- var d = "\xA0";
- var g = function(t2) {
- for (const e2 in t2) {
- const i2 = t2[e2];
- this[e2] = i2;
- }
- return this;
- };
- var m = document.documentElement;
- var p = m.matches;
- var f = function(t2) {
- let { onElement: e2, matchingSelector: i2, withCallback: n2, inPhase: r2, preventDefault: o2, times: s2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- const a2 = e2 || m, l2 = i2, c2 = "capturing" === r2, h2 = function(t3) {
- null != s2 && 0 == --s2 && h2.destroy();
- const e3 = A(t3.target, { matchingSelector: l2 });
- null != e3 && (null == n2 || n2.call(e3, t3, e3), o2 && t3.preventDefault());
- };
- return h2.destroy = () => a2.removeEventListener(t2, h2, c2), a2.addEventListener(t2, h2, c2), h2;
- };
- var b = function(t2) {
- let { onElement: e2, bubbles: i2, cancelable: n2, attributes: r2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- const o2 = null != e2 ? e2 : m;
- i2 = false !== i2, n2 = false !== n2;
- const s2 = document.createEvent("Events");
- return s2.initEvent(t2, i2, n2), null != r2 && g.call(s2, r2), o2.dispatchEvent(s2);
- };
- var v = function(t2, e2) {
- if (1 === (null == t2 ? void 0 : t2.nodeType))
- return p.call(t2, e2);
- };
- var A = function(t2) {
- let { matchingSelector: e2, untilNode: i2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- for (; t2 && t2.nodeType !== Node.ELEMENT_NODE; )
- t2 = t2.parentNode;
- if (null != t2) {
- if (null == e2)
- return t2;
- if (t2.closest && null == i2)
- return t2.closest(e2);
- for (; t2 && t2 !== i2; ) {
- if (v(t2, e2))
- return t2;
- t2 = t2.parentNode;
- }
- }
- };
- var x = (t2) => document.activeElement !== t2 && y(t2, document.activeElement);
- var y = function(t2, e2) {
- if (t2 && e2)
- for (; e2; ) {
- if (e2 === t2)
- return true;
- e2 = e2.parentNode;
- }
- };
- var C = function(t2) {
- var e2;
- if (null === (e2 = t2) || void 0 === e2 || !e2.parentNode)
- return;
- let i2 = 0;
- for (t2 = t2.previousSibling; t2; )
- i2++, t2 = t2.previousSibling;
- return i2;
- };
- var R = (t2) => {
- var e2;
- return null == t2 || null === (e2 = t2.parentNode) || void 0 === e2 ? void 0 : e2.removeChild(t2);
- };
- var S = function(t2) {
- let { onlyNodesOfType: e2, usingFilter: i2, expandEntityReferences: n2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- const r2 = (() => {
- switch (e2) {
- case "element":
- return NodeFilter.SHOW_ELEMENT;
- case "text":
- return NodeFilter.SHOW_TEXT;
- case "comment":
- return NodeFilter.SHOW_COMMENT;
- default:
- return NodeFilter.SHOW_ALL;
- }
- })();
- return document.createTreeWalker(t2, r2, null != i2 ? i2 : null, true === n2);
- };
- var E = (t2) => {
- var e2;
- return null == t2 || null === (e2 = t2.tagName) || void 0 === e2 ? void 0 : e2.toLowerCase();
- };
- var k = function(t2) {
- let e2, i2, n2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- "object" == typeof t2 ? (n2 = t2, t2 = n2.tagName) : n2 = { attributes: n2 };
- const r2 = document.createElement(t2);
- if (null != n2.editable && (null == n2.attributes && (n2.attributes = {}), n2.attributes.contenteditable = n2.editable), n2.attributes)
- for (e2 in n2.attributes)
- i2 = n2.attributes[e2], r2.setAttribute(e2, i2);
- if (n2.style)
- for (e2 in n2.style)
- i2 = n2.style[e2], r2.style[e2] = i2;
- if (n2.data)
- for (e2 in n2.data)
- i2 = n2.data[e2], r2.dataset[e2] = i2;
- return n2.className && n2.className.split(" ").forEach((t3) => {
- r2.classList.add(t3);
- }), n2.textContent && (r2.textContent = n2.textContent), n2.childNodes && [].concat(n2.childNodes).forEach((t3) => {
- r2.appendChild(t3);
- }), r2;
- };
- var L;
- var D = function() {
- if (null != L)
- return L;
- L = [];
- for (const t2 in n) {
- const e2 = n[t2];
- e2.tagName && L.push(e2.tagName);
- }
- return L;
- };
- var w = (t2) => B(null == t2 ? void 0 : t2.firstChild);
- var T = function(t2) {
- let { strict: e2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : { strict: true };
- return e2 ? B(t2) : B(t2) || !B(t2.firstChild) && function(t3) {
- return D().includes(E(t3)) && !D().includes(E(t3.firstChild));
- }(t2);
- };
- var B = (t2) => F(t2) && "block" === (null == t2 ? void 0 : t2.data);
- var F = (t2) => (null == t2 ? void 0 : t2.nodeType) === Node.COMMENT_NODE;
- var I = function(t2) {
- let { name: e2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- if (t2)
- return O(t2) ? t2.data === u ? !e2 || t2.parentNode.dataset.trixCursorTarget === e2 : void 0 : I(t2.firstChild);
- };
- var P = (t2) => v(t2, e);
- var N = (t2) => O(t2) && "" === (null == t2 ? void 0 : t2.data);
- var O = (t2) => (null == t2 ? void 0 : t2.nodeType) === Node.TEXT_NODE;
- var M = { level2Enabled: true, getLevel() {
- return this.level2Enabled && a.supportsInputEvents ? 2 : 0;
- }, pickFiles(t2) {
- const e2 = k("input", { type: "file", multiple: true, hidden: true, id: this.fileInputId });
- e2.addEventListener("change", () => {
- t2(e2.files), R(e2);
- }), R(document.getElementById(this.fileInputId)), document.body.appendChild(e2), e2.click();
- } };
- var j = { removeBlankTableCells: false, tableCellSeparator: " | ", tableRowSeparator: "\n" };
- var W = { bold: { tagName: "strong", inheritable: true, parser(t2) {
- const e2 = window.getComputedStyle(t2);
- return "bold" === e2.fontWeight || e2.fontWeight >= 600;
- } }, italic: { tagName: "em", inheritable: true, parser: (t2) => "italic" === window.getComputedStyle(t2).fontStyle }, href: { groupTagName: "a", parser(t2) {
- const i2 = "a:not(".concat(e, ")"), n2 = t2.closest(i2);
- if (n2)
- return n2.getAttribute("href");
- } }, strike: { tagName: "del", inheritable: true }, frozen: { style: { backgroundColor: "highlight" } } };
- var U = { getDefaultHTML: () => '\n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n\n \n \n \n\n \n\n \n \n \n \n
\n\n ') };
- var q = { interval: 5e3 };
- var V = Object.freeze({ __proto__: null, attachments: i, blockAttributes: n, browser: a, css: { attachment: "attachment", attachmentCaption: "attachment__caption", attachmentCaptionEditor: "attachment__caption-editor", attachmentMetadata: "attachment__metadata", attachmentMetadataContainer: "attachment__metadata-container", attachmentName: "attachment__name", attachmentProgress: "attachment__progress", attachmentSize: "attachment__size", attachmentToolbar: "attachment__toolbar", attachmentGallery: "attachment-gallery" }, fileSize: h, input: M, keyNames: { 8: "backspace", 9: "tab", 13: "return", 27: "escape", 37: "left", 39: "right", 46: "delete", 68: "d", 72: "h", 79: "o" }, lang: l, parser: j, textAttributes: W, toolbar: U, undo: q });
- var z = class {
- static proxyMethod(t2) {
- const { name: e2, toMethod: i2, toProperty: n2, optional: r2 } = _3(t2);
- this.prototype[e2] = function() {
- let t3, o2;
- var s2, a2;
- i2 ? o2 = r2 ? null === (s2 = this[i2]) || void 0 === s2 ? void 0 : s2.call(this) : this[i2]() : n2 && (o2 = this[n2]);
- return r2 ? (t3 = null === (a2 = o2) || void 0 === a2 ? void 0 : a2[e2], t3 ? H.call(t3, o2, arguments) : void 0) : (t3 = o2[e2], H.call(t3, o2, arguments));
- };
- }
- };
- var _3 = function(t2) {
- const e2 = t2.match(J);
- if (!e2)
- throw new Error("can't parse @proxyMethod expression: ".concat(t2));
- const i2 = { name: e2[4] };
- return null != e2[2] ? i2.toMethod = e2[1] : i2.toProperty = e2[1], null != e2[3] && (i2.optional = true), i2;
- };
- var { apply: H } = Function.prototype;
- var J = new RegExp("^(.+?)(\\(\\))?(\\?)?\\.(.+?)$");
- var K;
- var G;
- var $;
- var X = class extends z {
- static box() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "";
- return t2 instanceof this ? t2 : this.fromUCS2String(null == t2 ? void 0 : t2.toString());
- }
- static fromUCS2String(t2) {
- return new this(t2, tt(t2));
- }
- static fromCodepoints(t2) {
- return new this(et(t2), t2);
- }
- constructor(t2, e2) {
- super(...arguments), this.ucs2String = t2, this.codepoints = e2, this.length = this.codepoints.length, this.ucs2Length = this.ucs2String.length;
- }
- offsetToUCS2Offset(t2) {
- return et(this.codepoints.slice(0, Math.max(0, t2))).length;
- }
- offsetFromUCS2Offset(t2) {
- return tt(this.ucs2String.slice(0, Math.max(0, t2))).length;
- }
- slice() {
- return this.constructor.fromCodepoints(this.codepoints.slice(...arguments));
- }
- charAt(t2) {
- return this.slice(t2, t2 + 1);
- }
- isEqualTo(t2) {
- return this.constructor.box(t2).ucs2String === this.ucs2String;
- }
- toJSON() {
- return this.ucs2String;
- }
- getCacheKey() {
- return this.ucs2String;
- }
- toString() {
- return this.ucs2String;
- }
- };
- var Y = 1 === (null === (K = Array.from) || void 0 === K ? void 0 : K.call(Array, "\u{1F47C}").length);
- var Q = null != (null === (G = " ".codePointAt) || void 0 === G ? void 0 : G.call(" ", 0));
- var Z = " \u{1F47C}" === (null === ($ = String.fromCodePoint) || void 0 === $ ? void 0 : $.call(String, 32, 128124));
- var tt;
- var et;
- tt = Y && Q ? (t2) => Array.from(t2).map((t3) => t3.codePointAt(0)) : function(t2) {
- const e2 = [];
- let i2 = 0;
- const { length: n2 } = t2;
- for (; i2 < n2; ) {
- let r2 = t2.charCodeAt(i2++);
- if (55296 <= r2 && r2 <= 56319 && i2 < n2) {
- const e3 = t2.charCodeAt(i2++);
- 56320 == (64512 & e3) ? r2 = ((1023 & r2) << 10) + (1023 & e3) + 65536 : i2--;
- }
- e2.push(r2);
- }
- return e2;
- }, et = Z ? (t2) => String.fromCodePoint(...Array.from(t2 || [])) : function(t2) {
- return (() => {
- const e2 = [];
- return Array.from(t2).forEach((t3) => {
- let i2 = "";
- t3 > 65535 && (t3 -= 65536, i2 += String.fromCharCode(t3 >>> 10 & 1023 | 55296), t3 = 56320 | 1023 & t3), e2.push(i2 + String.fromCharCode(t3));
- }), e2;
- })().join("");
- };
- var it = 0;
- var nt = class extends z {
- static fromJSONString(t2) {
- return this.fromJSON(JSON.parse(t2));
- }
- constructor() {
- super(...arguments), this.id = ++it;
- }
- hasSameConstructorAs(t2) {
- return this.constructor === (null == t2 ? void 0 : t2.constructor);
- }
- isEqualTo(t2) {
- return this === t2;
- }
- inspect() {
- const t2 = [], e2 = this.contentsForInspection() || {};
- for (const i2 in e2) {
- const n2 = e2[i2];
- t2.push("".concat(i2, "=").concat(n2));
- }
- return "#<".concat(this.constructor.name, ":").concat(this.id).concat(t2.length ? " ".concat(t2.join(", ")) : "", ">");
- }
- contentsForInspection() {
- }
- toJSONString() {
- return JSON.stringify(this);
- }
- toUTF16String() {
- return X.box(this);
- }
- getCacheKey() {
- return this.id.toString();
- }
- };
- var rt = function() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [], e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : [];
- if (t2.length !== e2.length)
- return false;
- for (let i2 = 0; i2 < t2.length; i2++) {
- if (t2[i2] !== e2[i2])
- return false;
- }
- return true;
- };
- var ot = function(t2) {
- const e2 = t2.slice(0);
- for (var i2 = arguments.length, n2 = new Array(i2 > 1 ? i2 - 1 : 0), r2 = 1; r2 < i2; r2++)
- n2[r2 - 1] = arguments[r2];
- return e2.splice(...n2), e2;
- };
- var st = /[\u05BE\u05C0\u05C3\u05D0-\u05EA\u05F0-\u05F4\u061B\u061F\u0621-\u063A\u0640-\u064A\u066D\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D5\u06E5\u06E6\u200F\u202B\u202E\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE72\uFE74\uFE76-\uFEFC]/;
- var at = function() {
- const t2 = k("input", { dir: "auto", name: "x", dirName: "x.dir" }), e2 = k("textarea", { dir: "auto", name: "y", dirName: "y.dir" }), i2 = k("form");
- i2.appendChild(t2), i2.appendChild(e2);
- const n2 = function() {
- try {
- return new FormData(i2).has(e2.dirName);
- } catch (t3) {
- return false;
- }
- }(), r2 = function() {
- try {
- return t2.matches(":dir(ltr),:dir(rtl)");
- } catch (t3) {
- return false;
- }
- }();
- return n2 ? function(t3) {
- return e2.value = t3, new FormData(i2).get(e2.dirName);
- } : r2 ? function(e3) {
- return t2.value = e3, t2.matches(":dir(rtl)") ? "rtl" : "ltr";
- } : function(t3) {
- const e3 = t3.trim().charAt(0);
- return st.test(e3) ? "rtl" : "ltr";
- };
- }();
- var lt = null;
- var ct = null;
- var ht = null;
- var ut = null;
- var dt = () => (lt || (lt = ft().concat(mt())), lt);
- var gt = (t2) => n[t2];
- var mt = () => (ct || (ct = Object.keys(n)), ct);
- var pt = (t2) => W[t2];
- var ft = () => (ht || (ht = Object.keys(W)), ht);
- var bt = function(t2, e2) {
- vt(t2).textContent = e2.replace(/%t/g, t2);
- };
- var vt = function(t2) {
- const e2 = document.createElement("style");
- e2.setAttribute("type", "text/css"), e2.setAttribute("data-tag-name", t2.toLowerCase());
- const i2 = At();
- return i2 && e2.setAttribute("nonce", i2), document.head.insertBefore(e2, document.head.firstChild), e2;
- };
- var At = function() {
- const t2 = xt("trix-csp-nonce") || xt("csp-nonce");
- if (t2)
- return t2.getAttribute("content");
- };
- var xt = (t2) => document.head.querySelector("meta[name=".concat(t2, "]"));
- var yt = { "application/x-trix-feature-detection": "test" };
- var Ct = function(t2) {
- const e2 = t2.getData("text/plain"), i2 = t2.getData("text/html");
- if (!e2 || !i2)
- return null == e2 ? void 0 : e2.length;
- {
- const { body: t3 } = new DOMParser().parseFromString(i2, "text/html");
- if (t3.textContent === e2)
- return !t3.querySelector("*");
- }
- };
- var Rt = /Mac|^iP/.test(navigator.platform) ? (t2) => t2.metaKey : (t2) => t2.ctrlKey;
- var St = (t2) => setTimeout(t2, 1);
- var Et = function() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
- const e2 = {};
- for (const i2 in t2) {
- const n2 = t2[i2];
- e2[i2] = n2;
- }
- return e2;
- };
- var kt = function() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- if (Object.keys(t2).length !== Object.keys(e2).length)
- return false;
- for (const i2 in t2) {
- if (t2[i2] !== e2[i2])
- return false;
- }
- return true;
- };
- var Lt = function(t2) {
- if (null != t2)
- return Array.isArray(t2) || (t2 = [t2, t2]), [Tt(t2[0]), Tt(null != t2[1] ? t2[1] : t2[0])];
- };
- var Dt = function(t2) {
- if (null == t2)
- return;
- const [e2, i2] = Lt(t2);
- return Bt(e2, i2);
- };
- var wt = function(t2, e2) {
- if (null == t2 || null == e2)
- return;
- const [i2, n2] = Lt(t2), [r2, o2] = Lt(e2);
- return Bt(i2, r2) && Bt(n2, o2);
- };
- var Tt = function(t2) {
- return "number" == typeof t2 ? t2 : Et(t2);
- };
- var Bt = function(t2, e2) {
- return "number" == typeof t2 ? t2 === e2 : kt(t2, e2);
- };
- var Ft = class extends z {
- constructor() {
- super(...arguments), this.update = this.update.bind(this), this.selectionManagers = [];
- }
- start() {
- this.started || (this.started = true, document.addEventListener("selectionchange", this.update, true));
- }
- stop() {
- if (this.started)
- return this.started = false, document.removeEventListener("selectionchange", this.update, true);
- }
- registerSelectionManager(t2) {
- if (!this.selectionManagers.includes(t2))
- return this.selectionManagers.push(t2), this.start();
- }
- unregisterSelectionManager(t2) {
- if (this.selectionManagers = this.selectionManagers.filter((e2) => e2 !== t2), 0 === this.selectionManagers.length)
- return this.stop();
- }
- notifySelectionManagersOfSelectionChange() {
- return this.selectionManagers.map((t2) => t2.selectionDidChange());
- }
- update() {
- this.notifySelectionManagersOfSelectionChange();
- }
- reset() {
- this.update();
- }
- };
- var It = new Ft();
- var Pt = function() {
- const t2 = window.getSelection();
- if (t2.rangeCount > 0)
- return t2;
- };
- var Nt = function() {
- var t2;
- const e2 = null === (t2 = Pt()) || void 0 === t2 ? void 0 : t2.getRangeAt(0);
- if (e2 && !Mt(e2))
- return e2;
- };
- var Ot = function(t2) {
- const e2 = window.getSelection();
- return e2.removeAllRanges(), e2.addRange(t2), It.update();
- };
- var Mt = (t2) => jt(t2.startContainer) || jt(t2.endContainer);
- var jt = (t2) => !Object.getPrototypeOf(t2);
- var Wt = (t2) => t2.replace(new RegExp("".concat(u), "g"), "").replace(new RegExp("".concat(d), "g"), " ");
- var Ut = new RegExp("[^\\S".concat(d, "]"));
- var qt = (t2) => t2.replace(new RegExp("".concat(Ut.source), "g"), " ").replace(/\ {2,}/g, " ");
- var Vt = function(t2, e2) {
- if (t2.isEqualTo(e2))
- return ["", ""];
- const i2 = zt(t2, e2), { length: n2 } = i2.utf16String;
- let r2;
- if (n2) {
- const { offset: o2 } = i2, s2 = t2.codepoints.slice(0, o2).concat(t2.codepoints.slice(o2 + n2));
- r2 = zt(e2, X.fromCodepoints(s2));
- } else
- r2 = zt(e2, t2);
- return [i2.utf16String.toString(), r2.utf16String.toString()];
- };
- var zt = function(t2, e2) {
- let i2 = 0, n2 = t2.length, r2 = e2.length;
- for (; i2 < n2 && t2.charAt(i2).isEqualTo(e2.charAt(i2)); )
- i2++;
- for (; n2 > i2 + 1 && t2.charAt(n2 - 1).isEqualTo(e2.charAt(r2 - 1)); )
- n2--, r2--;
- return { utf16String: t2.slice(i2, n2), offset: i2 };
- };
- var _t = class extends nt {
- static fromCommonAttributesOfObjects() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
- if (!t2.length)
- return new this();
- let e2 = Gt(t2[0]), i2 = e2.getKeys();
- return t2.slice(1).forEach((t3) => {
- i2 = e2.getKeysCommonToHash(Gt(t3)), e2 = e2.slice(i2);
- }), e2;
- }
- static box(t2) {
- return Gt(t2);
- }
- constructor() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
- super(...arguments), this.values = Kt(t2);
- }
- add(t2, e2) {
- return this.merge(Ht(t2, e2));
- }
- remove(t2) {
- return new _t(Kt(this.values, t2));
- }
- get(t2) {
- return this.values[t2];
- }
- has(t2) {
- return t2 in this.values;
- }
- merge(t2) {
- return new _t(Jt(this.values, $t(t2)));
- }
- slice(t2) {
- const e2 = {};
- return Array.from(t2).forEach((t3) => {
- this.has(t3) && (e2[t3] = this.values[t3]);
- }), new _t(e2);
- }
- getKeys() {
- return Object.keys(this.values);
- }
- getKeysCommonToHash(t2) {
- return t2 = Gt(t2), this.getKeys().filter((e2) => this.values[e2] === t2.values[e2]);
- }
- isEqualTo(t2) {
- return rt(this.toArray(), Gt(t2).toArray());
- }
- isEmpty() {
- return 0 === this.getKeys().length;
- }
- toArray() {
- if (!this.array) {
- const t2 = [];
- for (const e2 in this.values) {
- const i2 = this.values[e2];
- t2.push(t2.push(e2, i2));
- }
- this.array = t2.slice(0);
- }
- return this.array;
- }
- toObject() {
- return Kt(this.values);
- }
- toJSON() {
- return this.toObject();
- }
- contentsForInspection() {
- return { values: JSON.stringify(this.values) };
- }
- };
- var Ht = function(t2, e2) {
- const i2 = {};
- return i2[t2] = e2, i2;
- };
- var Jt = function(t2, e2) {
- const i2 = Kt(t2);
- for (const t3 in e2) {
- const n2 = e2[t3];
- i2[t3] = n2;
- }
- return i2;
- };
- var Kt = function(t2, e2) {
- const i2 = {};
- return Object.keys(t2).sort().forEach((n2) => {
- n2 !== e2 && (i2[n2] = t2[n2]);
- }), i2;
- };
- var Gt = function(t2) {
- return t2 instanceof _t ? t2 : new _t(t2);
- };
- var $t = function(t2) {
- return t2 instanceof _t ? t2.values : t2;
- };
- var Xt = class {
- static groupObjects() {
- let t2, e2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [], { depth: i2, asTree: n2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- n2 && null == i2 && (i2 = 0);
- const r2 = [];
- return Array.from(e2).forEach((e3) => {
- var o2;
- if (t2) {
- var s2, a2, l2;
- if (null !== (s2 = e3.canBeGrouped) && void 0 !== s2 && s2.call(e3, i2) && null !== (a2 = (l2 = t2[t2.length - 1]).canBeGroupedWith) && void 0 !== a2 && a2.call(l2, e3, i2))
- return void t2.push(e3);
- r2.push(new this(t2, { depth: i2, asTree: n2 })), t2 = null;
- }
- null !== (o2 = e3.canBeGrouped) && void 0 !== o2 && o2.call(e3, i2) ? t2 = [e3] : r2.push(e3);
- }), t2 && r2.push(new this(t2, { depth: i2, asTree: n2 })), r2;
- }
- constructor() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [], { depth: e2, asTree: i2 } = arguments.length > 1 ? arguments[1] : void 0;
- this.objects = t2, i2 && (this.depth = e2, this.objects = this.constructor.groupObjects(this.objects, { asTree: i2, depth: this.depth + 1 }));
- }
- getObjects() {
- return this.objects;
- }
- getDepth() {
- return this.depth;
- }
- getCacheKey() {
- const t2 = ["objectGroup"];
- return Array.from(this.getObjects()).forEach((e2) => {
- t2.push(e2.getCacheKey());
- }), t2.join("/");
- }
- };
- var Yt = class extends z {
- constructor() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
- super(...arguments), this.objects = {}, Array.from(t2).forEach((t3) => {
- const e2 = JSON.stringify(t3);
- null == this.objects[e2] && (this.objects[e2] = t3);
- });
- }
- find(t2) {
- const e2 = JSON.stringify(t2);
- return this.objects[e2];
- }
- };
- var Qt = class {
- constructor(t2) {
- this.reset(t2);
- }
- add(t2) {
- const e2 = Zt(t2);
- this.elements[e2] = t2;
- }
- remove(t2) {
- const e2 = Zt(t2), i2 = this.elements[e2];
- if (i2)
- return delete this.elements[e2], i2;
- }
- reset() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
- return this.elements = {}, Array.from(t2).forEach((t3) => {
- this.add(t3);
- }), t2;
- }
- };
- var Zt = (t2) => t2.dataset.trixStoreKey;
- var te = class extends z {
- isPerforming() {
- return true === this.performing;
- }
- hasPerformed() {
- return true === this.performed;
- }
- hasSucceeded() {
- return this.performed && this.succeeded;
- }
- hasFailed() {
- return this.performed && !this.succeeded;
- }
- getPromise() {
- return this.promise || (this.promise = new Promise((t2, e2) => (this.performing = true, this.perform((i2, n2) => {
- this.succeeded = i2, this.performing = false, this.performed = true, this.succeeded ? t2(n2) : e2(n2);
- })))), this.promise;
- }
- perform(t2) {
- return t2(false);
- }
- release() {
- var t2, e2;
- null === (t2 = this.promise) || void 0 === t2 || null === (e2 = t2.cancel) || void 0 === e2 || e2.call(t2), this.promise = null, this.performing = null, this.performed = null, this.succeeded = null;
- }
- };
- te.proxyMethod("getPromise().then"), te.proxyMethod("getPromise().catch");
- var ee = class extends z {
- constructor(t2) {
- let e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- super(...arguments), this.object = t2, this.options = e2, this.childViews = [], this.rootView = this;
- }
- getNodes() {
- return this.nodes || (this.nodes = this.createNodes()), this.nodes.map((t2) => t2.cloneNode(true));
- }
- invalidate() {
- var t2;
- return this.nodes = null, this.childViews = [], null === (t2 = this.parentView) || void 0 === t2 ? void 0 : t2.invalidate();
- }
- invalidateViewForObject(t2) {
- var e2;
- return null === (e2 = this.findViewForObject(t2)) || void 0 === e2 ? void 0 : e2.invalidate();
- }
- findOrCreateCachedChildView(t2, e2, i2) {
- let n2 = this.getCachedViewForObject(e2);
- return n2 ? this.recordChildView(n2) : (n2 = this.createChildView(...arguments), this.cacheViewForObject(n2, e2)), n2;
- }
- createChildView(t2, e2) {
- let i2 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {};
- e2 instanceof Xt && (i2.viewClass = t2, t2 = ie);
- const n2 = new t2(e2, i2);
- return this.recordChildView(n2);
- }
- recordChildView(t2) {
- return t2.parentView = this, t2.rootView = this.rootView, this.childViews.push(t2), t2;
- }
- getAllChildViews() {
- let t2 = [];
- return this.childViews.forEach((e2) => {
- t2.push(e2), t2 = t2.concat(e2.getAllChildViews());
- }), t2;
- }
- findElement() {
- return this.findElementForObject(this.object);
- }
- findElementForObject(t2) {
- const e2 = null == t2 ? void 0 : t2.id;
- if (e2)
- return this.rootView.element.querySelector("[data-trix-id='".concat(e2, "']"));
- }
- findViewForObject(t2) {
- for (const e2 of this.getAllChildViews())
- if (e2.object === t2)
- return e2;
- }
- getViewCache() {
- return this.rootView !== this ? this.rootView.getViewCache() : this.isViewCachingEnabled() ? (this.viewCache || (this.viewCache = {}), this.viewCache) : void 0;
- }
- isViewCachingEnabled() {
- return false !== this.shouldCacheViews;
- }
- enableViewCaching() {
- this.shouldCacheViews = true;
- }
- disableViewCaching() {
- this.shouldCacheViews = false;
- }
- getCachedViewForObject(t2) {
- var e2;
- return null === (e2 = this.getViewCache()) || void 0 === e2 ? void 0 : e2[t2.getCacheKey()];
- }
- cacheViewForObject(t2, e2) {
- const i2 = this.getViewCache();
- i2 && (i2[e2.getCacheKey()] = t2);
- }
- garbageCollectCachedViews() {
- const t2 = this.getViewCache();
- if (t2) {
- const e2 = this.getAllChildViews().concat(this).map((t3) => t3.object.getCacheKey());
- for (const i2 in t2)
- e2.includes(i2) || delete t2[i2];
- }
- }
- };
- var ie = class extends ee {
- constructor() {
- super(...arguments), this.objectGroup = this.object, this.viewClass = this.options.viewClass, delete this.options.viewClass;
- }
- getChildViews() {
- return this.childViews.length || Array.from(this.objectGroup.getObjects()).forEach((t2) => {
- this.findOrCreateCachedChildView(this.viewClass, t2, this.options);
- }), this.childViews;
- }
- createNodes() {
- const t2 = this.createContainerElement();
- return this.getChildViews().forEach((e2) => {
- Array.from(e2.getNodes()).forEach((e3) => {
- t2.appendChild(e3);
- });
- }), [t2];
- }
- createContainerElement() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.objectGroup.getDepth();
- return this.getChildViews()[0].createContainerElement(t2);
- }
- };
- var { css: ne } = V;
- var re = class extends ee {
- constructor() {
- super(...arguments), this.attachment = this.object, this.attachment.uploadProgressDelegate = this, this.attachmentPiece = this.options.piece;
- }
- createContentNodes() {
- return [];
- }
- createNodes() {
- let t2;
- const e2 = t2 = k({ tagName: "figure", className: this.getClassName(), data: this.getData(), editable: false }), i2 = this.getHref();
- return i2 && (t2 = k({ tagName: "a", editable: false, attributes: { href: i2, tabindex: -1 } }), e2.appendChild(t2)), this.attachment.hasContent() ? t2.innerHTML = this.attachment.getContent() : this.createContentNodes().forEach((e3) => {
- t2.appendChild(e3);
- }), t2.appendChild(this.createCaptionElement()), this.attachment.isPending() && (this.progressElement = k({ tagName: "progress", attributes: { class: ne.attachmentProgress, value: this.attachment.getUploadProgress(), max: 100 }, data: { trixMutable: true, trixStoreKey: ["progressElement", this.attachment.id].join("/") } }), e2.appendChild(this.progressElement)), [oe("left"), e2, oe("right")];
- }
- createCaptionElement() {
- const t2 = k({ tagName: "figcaption", className: ne.attachmentCaption }), e2 = this.attachmentPiece.getCaption();
- if (e2)
- t2.classList.add("".concat(ne.attachmentCaption, "--edited")), t2.textContent = e2;
- else {
- let e3, i2;
- const n2 = this.getCaptionConfig();
- if (n2.name && (e3 = this.attachment.getFilename()), n2.size && (i2 = this.attachment.getFormattedFilesize()), e3) {
- const i3 = k({ tagName: "span", className: ne.attachmentName, textContent: e3 });
- t2.appendChild(i3);
- }
- if (i2) {
- e3 && t2.appendChild(document.createTextNode(" "));
- const n3 = k({ tagName: "span", className: ne.attachmentSize, textContent: i2 });
- t2.appendChild(n3);
- }
- }
- return t2;
- }
- getClassName() {
- const t2 = [ne.attachment, "".concat(ne.attachment, "--").concat(this.attachment.getType())], e2 = this.attachment.getExtension();
- return e2 && t2.push("".concat(ne.attachment, "--").concat(e2)), t2.join(" ");
- }
- getData() {
- const t2 = { trixAttachment: JSON.stringify(this.attachment), trixContentType: this.attachment.getContentType(), trixId: this.attachment.id }, { attributes: e2 } = this.attachmentPiece;
- return e2.isEmpty() || (t2.trixAttributes = JSON.stringify(e2)), this.attachment.isPending() && (t2.trixSerialize = false), t2;
- }
- getHref() {
- if (!se(this.attachment.getContent(), "a"))
- return this.attachment.getHref();
- }
- getCaptionConfig() {
- var t2;
- const e2 = this.attachment.getType(), n2 = Et(null === (t2 = i[e2]) || void 0 === t2 ? void 0 : t2.caption);
- return "file" === e2 && (n2.name = true), n2;
- }
- findProgressElement() {
- var t2;
- return null === (t2 = this.findElement()) || void 0 === t2 ? void 0 : t2.querySelector("progress");
- }
- attachmentDidChangeUploadProgress() {
- const t2 = this.attachment.getUploadProgress(), e2 = this.findProgressElement();
- e2 && (e2.value = t2);
- }
- };
- var oe = (t2) => k({ tagName: "span", textContent: u, data: { trixCursorTarget: t2, trixSerialize: false } });
- var se = function(t2, e2) {
- const i2 = k("div");
- return i2.innerHTML = t2 || "", i2.querySelector(e2);
- };
- var ae = class extends re {
- constructor() {
- super(...arguments), this.attachment.previewDelegate = this;
- }
- createContentNodes() {
- return this.image = k({ tagName: "img", attributes: { src: "" }, data: { trixMutable: true } }), this.refresh(this.image), [this.image];
- }
- createCaptionElement() {
- const t2 = super.createCaptionElement(...arguments);
- return t2.textContent || t2.setAttribute("data-trix-placeholder", l.captionPlaceholder), t2;
- }
- refresh(t2) {
- var e2;
- t2 || (t2 = null === (e2 = this.findElement()) || void 0 === e2 ? void 0 : e2.querySelector("img"));
- if (t2)
- return this.updateAttributesForImage(t2);
- }
- updateAttributesForImage(t2) {
- const e2 = this.attachment.getURL(), i2 = this.attachment.getPreviewURL();
- if (t2.src = i2 || e2, i2 === e2)
- t2.removeAttribute("data-trix-serialized-attributes");
- else {
- const i3 = JSON.stringify({ src: e2 });
- t2.setAttribute("data-trix-serialized-attributes", i3);
- }
- const n2 = this.attachment.getWidth(), r2 = this.attachment.getHeight();
- null != n2 && (t2.width = n2), null != r2 && (t2.height = r2);
- const o2 = ["imageElement", this.attachment.id, t2.src, t2.width, t2.height].join("/");
- t2.dataset.trixStoreKey = o2;
- }
- attachmentDidChangeAttributes() {
- return this.refresh(this.image), this.refresh();
- }
- };
- var le = class extends ee {
- constructor() {
- super(...arguments), this.piece = this.object, this.attributes = this.piece.getAttributes(), this.textConfig = this.options.textConfig, this.context = this.options.context, this.piece.attachment ? this.attachment = this.piece.attachment : this.string = this.piece.toString();
- }
- createNodes() {
- let t2 = this.attachment ? this.createAttachmentNodes() : this.createStringNodes();
- const e2 = this.createElement();
- if (e2) {
- const i2 = function(t3) {
- for (; null !== (e3 = t3) && void 0 !== e3 && e3.firstElementChild; ) {
- var e3;
- t3 = t3.firstElementChild;
- }
- return t3;
- }(e2);
- Array.from(t2).forEach((t3) => {
- i2.appendChild(t3);
- }), t2 = [e2];
- }
- return t2;
- }
- createAttachmentNodes() {
- const t2 = this.attachment.isPreviewable() ? ae : re;
- return this.createChildView(t2, this.piece.attachment, { piece: this.piece }).getNodes();
- }
- createStringNodes() {
- var t2;
- if (null !== (t2 = this.textConfig) && void 0 !== t2 && t2.plaintext)
- return [document.createTextNode(this.string)];
- {
- const t3 = [], e2 = this.string.split("\n");
- for (let i2 = 0; i2 < e2.length; i2++) {
- const n2 = e2[i2];
- if (i2 > 0) {
- const e3 = k("br");
- t3.push(e3);
- }
- if (n2.length) {
- const e3 = document.createTextNode(this.preserveSpaces(n2));
- t3.push(e3);
- }
- }
- return t3;
- }
- }
- createElement() {
- let t2, e2, i2;
- const n2 = {};
- for (e2 in this.attributes) {
- i2 = this.attributes[e2];
- const o2 = pt(e2);
- if (o2) {
- if (o2.tagName) {
- var r2;
- const e3 = k(o2.tagName);
- r2 ? (r2.appendChild(e3), r2 = e3) : t2 = r2 = e3;
- }
- if (o2.styleProperty && (n2[o2.styleProperty] = i2), o2.style)
- for (e2 in o2.style)
- i2 = o2.style[e2], n2[e2] = i2;
- }
- }
- if (Object.keys(n2).length)
- for (e2 in t2 || (t2 = k("span")), n2)
- i2 = n2[e2], t2.style[e2] = i2;
- return t2;
- }
- createContainerElement() {
- for (const t2 in this.attributes) {
- const e2 = this.attributes[t2], i2 = pt(t2);
- if (i2 && i2.groupTagName) {
- const n2 = {};
- return n2[t2] = e2, k(i2.groupTagName, n2);
- }
- }
- }
- preserveSpaces(t2) {
- return this.context.isLast && (t2 = t2.replace(/\ $/, d)), t2 = t2.replace(/(\S)\ {3}(\S)/g, "$1 ".concat(d, " $2")).replace(/\ {2}/g, "".concat(d, " ")).replace(/\ {2}/g, " ".concat(d)), (this.context.isFirst || this.context.followsWhitespace) && (t2 = t2.replace(/^\ /, d)), t2;
- }
- };
- var ce = class extends ee {
- constructor() {
- super(...arguments), this.text = this.object, this.textConfig = this.options.textConfig;
- }
- createNodes() {
- const t2 = [], e2 = Xt.groupObjects(this.getPieces()), i2 = e2.length - 1;
- for (let r2 = 0; r2 < e2.length; r2++) {
- const o2 = e2[r2], s2 = {};
- 0 === r2 && (s2.isFirst = true), r2 === i2 && (s2.isLast = true), he(n2) && (s2.followsWhitespace = true);
- const a2 = this.findOrCreateCachedChildView(le, o2, { textConfig: this.textConfig, context: s2 });
- t2.push(...Array.from(a2.getNodes() || []));
- var n2 = o2;
- }
- return t2;
- }
- getPieces() {
- return Array.from(this.text.getPieces()).filter((t2) => !t2.hasAttribute("blockBreak"));
- }
- };
- var he = (t2) => /\s$/.test(null == t2 ? void 0 : t2.toString());
- var { css: ue } = V;
- var de = class extends ee {
- constructor() {
- super(...arguments), this.block = this.object, this.attributes = this.block.getAttributes();
- }
- createNodes() {
- const t2 = [document.createComment("block")];
- if (this.block.isEmpty())
- t2.push(k("br"));
- else {
- var e2;
- const i2 = null === (e2 = gt(this.block.getLastAttribute())) || void 0 === e2 ? void 0 : e2.text, n2 = this.findOrCreateCachedChildView(ce, this.block.text, { textConfig: i2 });
- t2.push(...Array.from(n2.getNodes() || [])), this.shouldAddExtraNewlineElement() && t2.push(k("br"));
- }
- if (this.attributes.length)
- return t2;
- {
- let e3;
- const { tagName: i2 } = n.default;
- this.block.isRTL() && (e3 = { dir: "rtl" });
- const r2 = k({ tagName: i2, attributes: e3 });
- return t2.forEach((t3) => r2.appendChild(t3)), [r2];
- }
- }
- createContainerElement(t2) {
- let e2, i2;
- const n2 = this.attributes[t2], { tagName: r2 } = gt(n2);
- if (0 === t2 && this.block.isRTL() && (e2 = { dir: "rtl" }), "attachmentGallery" === n2) {
- const t3 = this.block.getBlockBreakPosition();
- i2 = "".concat(ue.attachmentGallery, " ").concat(ue.attachmentGallery, "--").concat(t3);
- }
- return k({ tagName: r2, className: i2, attributes: e2 });
- }
- shouldAddExtraNewlineElement() {
- return /\n\n$/.test(this.block.toString());
- }
- };
- var ge = class extends ee {
- static render(t2) {
- const e2 = k("div"), i2 = new this(t2, { element: e2 });
- return i2.render(), i2.sync(), e2;
- }
- constructor() {
- super(...arguments), this.element = this.options.element, this.elementStore = new Qt(), this.setDocument(this.object);
- }
- setDocument(t2) {
- t2.isEqualTo(this.document) || (this.document = this.object = t2);
- }
- render() {
- if (this.childViews = [], this.shadowElement = k("div"), !this.document.isEmpty()) {
- const t2 = Xt.groupObjects(this.document.getBlocks(), { asTree: true });
- Array.from(t2).forEach((t3) => {
- const e2 = this.findOrCreateCachedChildView(de, t3);
- Array.from(e2.getNodes()).map((t4) => this.shadowElement.appendChild(t4));
- });
- }
- }
- isSynced() {
- return pe(this.shadowElement, this.element);
- }
- sync() {
- const t2 = this.createDocumentFragmentForSync();
- for (; this.element.lastChild; )
- this.element.removeChild(this.element.lastChild);
- return this.element.appendChild(t2), this.didSync();
- }
- didSync() {
- return this.elementStore.reset(me(this.element)), St(() => this.garbageCollectCachedViews());
- }
- createDocumentFragmentForSync() {
- const t2 = document.createDocumentFragment();
- return Array.from(this.shadowElement.childNodes).forEach((e2) => {
- t2.appendChild(e2.cloneNode(true));
- }), Array.from(me(t2)).forEach((t3) => {
- const e2 = this.elementStore.remove(t3);
- e2 && t3.parentNode.replaceChild(e2, t3);
- }), t2;
- }
- };
- var me = (t2) => t2.querySelectorAll("[data-trix-store-key]");
- var pe = (t2, e2) => fe(t2.innerHTML) === fe(e2.innerHTML);
- var fe = (t2) => t2.replace(/ /g, " ");
- function be(t2) {
- var e2, i2;
- function n2(e3, i3) {
- try {
- var o2 = t2[e3](i3), s2 = o2.value, a2 = s2 instanceof ve;
- Promise.resolve(a2 ? s2.v : s2).then(function(i4) {
- if (a2) {
- var l2 = "return" === e3 ? "return" : "next";
- if (!s2.k || i4.done)
- return n2(l2, i4);
- i4 = t2[l2](i4).value;
- }
- r2(o2.done ? "return" : "normal", i4);
- }, function(t3) {
- n2("throw", t3);
- });
- } catch (t3) {
- r2("throw", t3);
- }
- }
- function r2(t3, r3) {
- switch (t3) {
- case "return":
- e2.resolve({ value: r3, done: true });
- break;
- case "throw":
- e2.reject(r3);
- break;
- default:
- e2.resolve({ value: r3, done: false });
- }
- (e2 = e2.next) ? n2(e2.key, e2.arg) : i2 = null;
- }
- this._invoke = function(t3, r3) {
- return new Promise(function(o2, s2) {
- var a2 = { key: t3, arg: r3, resolve: o2, reject: s2, next: null };
- i2 ? i2 = i2.next = a2 : (e2 = i2 = a2, n2(t3, r3));
- });
- }, "function" != typeof t2.return && (this.return = void 0);
- }
- function ve(t2, e2) {
- this.v = t2, this.k = e2;
- }
- function Ae(t2, e2, i2) {
- return (e2 = xe(e2)) in t2 ? Object.defineProperty(t2, e2, { value: i2, enumerable: true, configurable: true, writable: true }) : t2[e2] = i2, t2;
- }
- function xe(t2) {
- var e2 = function(t3, e3) {
- if ("object" != typeof t3 || null === t3)
- return t3;
- var i2 = t3[Symbol.toPrimitive];
- if (void 0 !== i2) {
- var n2 = i2.call(t3, e3 || "default");
- if ("object" != typeof n2)
- return n2;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return ("string" === e3 ? String : Number)(t3);
- }(t2, "string");
- return "symbol" == typeof e2 ? e2 : String(e2);
- }
- be.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
- return this;
- }, be.prototype.next = function(t2) {
- return this._invoke("next", t2);
- }, be.prototype.throw = function(t2) {
- return this._invoke("throw", t2);
- }, be.prototype.return = function(t2) {
- return this._invoke("return", t2);
- };
- var ye = class extends nt {
- static registerType(t2, e2) {
- e2.type = t2, this.types[t2] = e2;
- }
- static fromJSON(t2) {
- const e2 = this.types[t2.type];
- if (e2)
- return e2.fromJSON(t2);
- }
- constructor(t2) {
- let e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- super(...arguments), this.attributes = _t.box(e2);
- }
- copyWithAttributes(t2) {
- return new this.constructor(this.getValue(), t2);
- }
- copyWithAdditionalAttributes(t2) {
- return this.copyWithAttributes(this.attributes.merge(t2));
- }
- copyWithoutAttribute(t2) {
- return this.copyWithAttributes(this.attributes.remove(t2));
- }
- copy() {
- return this.copyWithAttributes(this.attributes);
- }
- getAttribute(t2) {
- return this.attributes.get(t2);
- }
- getAttributesHash() {
- return this.attributes;
- }
- getAttributes() {
- return this.attributes.toObject();
- }
- hasAttribute(t2) {
- return this.attributes.has(t2);
- }
- hasSameStringValueAsPiece(t2) {
- return t2 && this.toString() === t2.toString();
- }
- hasSameAttributesAsPiece(t2) {
- return t2 && (this.attributes === t2.attributes || this.attributes.isEqualTo(t2.attributes));
- }
- isBlockBreak() {
- return false;
- }
- isEqualTo(t2) {
- return super.isEqualTo(...arguments) || this.hasSameConstructorAs(t2) && this.hasSameStringValueAsPiece(t2) && this.hasSameAttributesAsPiece(t2);
- }
- isEmpty() {
- return 0 === this.length;
- }
- isSerializable() {
- return true;
- }
- toJSON() {
- return { type: this.constructor.type, attributes: this.getAttributes() };
- }
- contentsForInspection() {
- return { type: this.constructor.type, attributes: this.attributes.inspect() };
- }
- canBeGrouped() {
- return this.hasAttribute("href");
- }
- canBeGroupedWith(t2) {
- return this.getAttribute("href") === t2.getAttribute("href");
- }
- getLength() {
- return this.length;
- }
- canBeConsolidatedWith(t2) {
- return false;
- }
- };
- Ae(ye, "types", {});
- var Ce = class extends te {
- constructor(t2) {
- super(...arguments), this.url = t2;
- }
- perform(t2) {
- const e2 = new Image();
- e2.onload = () => (e2.width = this.width = e2.naturalWidth, e2.height = this.height = e2.naturalHeight, t2(true, e2)), e2.onerror = () => t2(false), e2.src = this.url;
- }
- };
- var Re = class extends nt {
- static attachmentForFile(t2) {
- const e2 = new this(this.attributesForFile(t2));
- return e2.setFile(t2), e2;
- }
- static attributesForFile(t2) {
- return new _t({ filename: t2.name, filesize: t2.size, contentType: t2.type });
- }
- static fromJSON(t2) {
- return new this(t2);
- }
- constructor() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
- super(t2), this.releaseFile = this.releaseFile.bind(this), this.attributes = _t.box(t2), this.didChangeAttributes();
- }
- getAttribute(t2) {
- return this.attributes.get(t2);
- }
- hasAttribute(t2) {
- return this.attributes.has(t2);
- }
- getAttributes() {
- return this.attributes.toObject();
- }
- setAttributes() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
- const e2 = this.attributes.merge(t2);
- var i2, n2, r2, o2;
- if (!this.attributes.isEqualTo(e2))
- return this.attributes = e2, this.didChangeAttributes(), null === (i2 = this.previewDelegate) || void 0 === i2 || null === (n2 = i2.attachmentDidChangeAttributes) || void 0 === n2 || n2.call(i2, this), null === (r2 = this.delegate) || void 0 === r2 || null === (o2 = r2.attachmentDidChangeAttributes) || void 0 === o2 ? void 0 : o2.call(r2, this);
- }
- didChangeAttributes() {
- if (this.isPreviewable())
- return this.preloadURL();
- }
- isPending() {
- return null != this.file && !(this.getURL() || this.getHref());
- }
- isPreviewable() {
- return this.attributes.has("previewable") ? this.attributes.get("previewable") : Re.previewablePattern.test(this.getContentType());
- }
- getType() {
- return this.hasContent() ? "content" : this.isPreviewable() ? "preview" : "file";
- }
- getURL() {
- return this.attributes.get("url");
- }
- getHref() {
- return this.attributes.get("href");
- }
- getFilename() {
- return this.attributes.get("filename") || "";
- }
- getFilesize() {
- return this.attributes.get("filesize");
- }
- getFormattedFilesize() {
- const t2 = this.attributes.get("filesize");
- return "number" == typeof t2 ? h.formatter(t2) : "";
- }
- getExtension() {
- var t2;
- return null === (t2 = this.getFilename().match(/\.(\w+)$/)) || void 0 === t2 ? void 0 : t2[1].toLowerCase();
- }
- getContentType() {
- return this.attributes.get("contentType");
- }
- hasContent() {
- return this.attributes.has("content");
- }
- getContent() {
- return this.attributes.get("content");
- }
- getWidth() {
- return this.attributes.get("width");
- }
- getHeight() {
- return this.attributes.get("height");
- }
- getFile() {
- return this.file;
- }
- setFile(t2) {
- if (this.file = t2, this.isPreviewable())
- return this.preloadFile();
- }
- releaseFile() {
- this.releasePreloadedFile(), this.file = null;
- }
- getUploadProgress() {
- return null != this.uploadProgress ? this.uploadProgress : 0;
- }
- setUploadProgress(t2) {
- var e2, i2;
- if (this.uploadProgress !== t2)
- return this.uploadProgress = t2, null === (e2 = this.uploadProgressDelegate) || void 0 === e2 || null === (i2 = e2.attachmentDidChangeUploadProgress) || void 0 === i2 ? void 0 : i2.call(e2, this);
- }
- toJSON() {
- return this.getAttributes();
- }
- getCacheKey() {
- return [super.getCacheKey(...arguments), this.attributes.getCacheKey(), this.getPreviewURL()].join("/");
- }
- getPreviewURL() {
- return this.previewURL || this.preloadingURL;
- }
- setPreviewURL(t2) {
- var e2, i2, n2, r2;
- if (t2 !== this.getPreviewURL())
- return this.previewURL = t2, null === (e2 = this.previewDelegate) || void 0 === e2 || null === (i2 = e2.attachmentDidChangeAttributes) || void 0 === i2 || i2.call(e2, this), null === (n2 = this.delegate) || void 0 === n2 || null === (r2 = n2.attachmentDidChangePreviewURL) || void 0 === r2 ? void 0 : r2.call(n2, this);
- }
- preloadURL() {
- return this.preload(this.getURL(), this.releaseFile);
- }
- preloadFile() {
- if (this.file)
- return this.fileObjectURL = URL.createObjectURL(this.file), this.preload(this.fileObjectURL);
- }
- releasePreloadedFile() {
- this.fileObjectURL && (URL.revokeObjectURL(this.fileObjectURL), this.fileObjectURL = null);
- }
- preload(t2, e2) {
- if (t2 && t2 !== this.getPreviewURL()) {
- this.preloadingURL = t2;
- return new Ce(t2).then((i2) => {
- let { width: n2, height: r2 } = i2;
- return this.getWidth() && this.getHeight() || this.setAttributes({ width: n2, height: r2 }), this.preloadingURL = null, this.setPreviewURL(t2), null == e2 ? void 0 : e2();
- }).catch(() => (this.preloadingURL = null, null == e2 ? void 0 : e2()));
- }
- }
- };
- Ae(Re, "previewablePattern", /^image(\/(gif|png|webp|jpe?g)|$)/);
- var Se = class extends ye {
- static fromJSON(t2) {
- return new this(Re.fromJSON(t2.attachment), t2.attributes);
- }
- constructor(t2) {
- super(...arguments), this.attachment = t2, this.length = 1, this.ensureAttachmentExclusivelyHasAttribute("href"), this.attachment.hasContent() || this.removeProhibitedAttributes();
- }
- ensureAttachmentExclusivelyHasAttribute(t2) {
- this.hasAttribute(t2) && (this.attachment.hasAttribute(t2) || this.attachment.setAttributes(this.attributes.slice([t2])), this.attributes = this.attributes.remove(t2));
- }
- removeProhibitedAttributes() {
- const t2 = this.attributes.slice(Se.permittedAttributes);
- t2.isEqualTo(this.attributes) || (this.attributes = t2);
- }
- getValue() {
- return this.attachment;
- }
- isSerializable() {
- return !this.attachment.isPending();
- }
- getCaption() {
- return this.attributes.get("caption") || "";
- }
- isEqualTo(t2) {
- var e2;
- return super.isEqualTo(t2) && this.attachment.id === (null == t2 || null === (e2 = t2.attachment) || void 0 === e2 ? void 0 : e2.id);
- }
- toString() {
- return "\uFFFC";
- }
- toJSON() {
- const t2 = super.toJSON(...arguments);
- return t2.attachment = this.attachment, t2;
- }
- getCacheKey() {
- return [super.getCacheKey(...arguments), this.attachment.getCacheKey()].join("/");
- }
- toConsole() {
- return JSON.stringify(this.toString());
- }
- };
- Ae(Se, "permittedAttributes", ["caption", "presentation"]), ye.registerType("attachment", Se);
- var Ee = class extends ye {
- static fromJSON(t2) {
- return new this(t2.string, t2.attributes);
- }
- constructor(t2) {
- super(...arguments), this.string = ((t3) => t3.replace(/\r\n?/g, "\n"))(t2), this.length = this.string.length;
- }
- getValue() {
- return this.string;
- }
- toString() {
- return this.string.toString();
- }
- isBlockBreak() {
- return "\n" === this.toString() && true === this.getAttribute("blockBreak");
- }
- toJSON() {
- const t2 = super.toJSON(...arguments);
- return t2.string = this.string, t2;
- }
- canBeConsolidatedWith(t2) {
- return t2 && this.hasSameConstructorAs(t2) && this.hasSameAttributesAsPiece(t2);
- }
- consolidateWith(t2) {
- return new this.constructor(this.toString() + t2.toString(), this.attributes);
- }
- splitAtOffset(t2) {
- let e2, i2;
- return 0 === t2 ? (e2 = null, i2 = this) : t2 === this.length ? (e2 = this, i2 = null) : (e2 = new this.constructor(this.string.slice(0, t2), this.attributes), i2 = new this.constructor(this.string.slice(t2), this.attributes)), [e2, i2];
- }
- toConsole() {
- let { string: t2 } = this;
- return t2.length > 15 && (t2 = t2.slice(0, 14) + "\u2026"), JSON.stringify(t2.toString());
- }
- };
- ye.registerType("string", Ee);
- var ke = class extends nt {
- static box(t2) {
- return t2 instanceof this ? t2 : new this(t2);
- }
- constructor() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
- super(...arguments), this.objects = t2.slice(0), this.length = this.objects.length;
- }
- indexOf(t2) {
- return this.objects.indexOf(t2);
- }
- splice() {
- for (var t2 = arguments.length, e2 = new Array(t2), i2 = 0; i2 < t2; i2++)
- e2[i2] = arguments[i2];
- return new this.constructor(ot(this.objects, ...e2));
- }
- eachObject(t2) {
- return this.objects.map((e2, i2) => t2(e2, i2));
- }
- insertObjectAtIndex(t2, e2) {
- return this.splice(e2, 0, t2);
- }
- insertSplittableListAtIndex(t2, e2) {
- return this.splice(e2, 0, ...t2.objects);
- }
- insertSplittableListAtPosition(t2, e2) {
- const [i2, n2] = this.splitObjectAtPosition(e2);
- return new this.constructor(i2).insertSplittableListAtIndex(t2, n2);
- }
- editObjectAtIndex(t2, e2) {
- return this.replaceObjectAtIndex(e2(this.objects[t2]), t2);
- }
- replaceObjectAtIndex(t2, e2) {
- return this.splice(e2, 1, t2);
- }
- removeObjectAtIndex(t2) {
- return this.splice(t2, 1);
- }
- getObjectAtIndex(t2) {
- return this.objects[t2];
- }
- getSplittableListInRange(t2) {
- const [e2, i2, n2] = this.splitObjectsAtRange(t2);
- return new this.constructor(e2.slice(i2, n2 + 1));
- }
- selectSplittableList(t2) {
- const e2 = this.objects.filter((e3) => t2(e3));
- return new this.constructor(e2);
- }
- removeObjectsInRange(t2) {
- const [e2, i2, n2] = this.splitObjectsAtRange(t2);
- return new this.constructor(e2).splice(i2, n2 - i2 + 1);
- }
- transformObjectsInRange(t2, e2) {
- const [i2, n2, r2] = this.splitObjectsAtRange(t2), o2 = i2.map((t3, i3) => n2 <= i3 && i3 <= r2 ? e2(t3) : t3);
- return new this.constructor(o2);
- }
- splitObjectsAtRange(t2) {
- let e2, [i2, n2, r2] = this.splitObjectAtPosition(De(t2));
- return [i2, e2] = new this.constructor(i2).splitObjectAtPosition(we(t2) + r2), [i2, n2, e2 - 1];
- }
- getObjectAtPosition(t2) {
- const { index: e2 } = this.findIndexAndOffsetAtPosition(t2);
- return this.objects[e2];
- }
- splitObjectAtPosition(t2) {
- let e2, i2;
- const { index: n2, offset: r2 } = this.findIndexAndOffsetAtPosition(t2), o2 = this.objects.slice(0);
- if (null != n2)
- if (0 === r2)
- e2 = n2, i2 = 0;
- else {
- const t3 = this.getObjectAtIndex(n2), [s2, a2] = t3.splitAtOffset(r2);
- o2.splice(n2, 1, s2, a2), e2 = n2 + 1, i2 = s2.getLength() - r2;
- }
- else
- e2 = o2.length, i2 = 0;
- return [o2, e2, i2];
- }
- consolidate() {
- const t2 = [];
- let e2 = this.objects[0];
- return this.objects.slice(1).forEach((i2) => {
- var n2, r2;
- null !== (n2 = (r2 = e2).canBeConsolidatedWith) && void 0 !== n2 && n2.call(r2, i2) ? e2 = e2.consolidateWith(i2) : (t2.push(e2), e2 = i2);
- }), e2 && t2.push(e2), new this.constructor(t2);
- }
- consolidateFromIndexToIndex(t2, e2) {
- const i2 = this.objects.slice(0).slice(t2, e2 + 1), n2 = new this.constructor(i2).consolidate().toArray();
- return this.splice(t2, i2.length, ...n2);
- }
- findIndexAndOffsetAtPosition(t2) {
- let e2, i2 = 0;
- for (e2 = 0; e2 < this.objects.length; e2++) {
- const n2 = i2 + this.objects[e2].getLength();
- if (i2 <= t2 && t2 < n2)
- return { index: e2, offset: t2 - i2 };
- i2 = n2;
- }
- return { index: null, offset: null };
- }
- findPositionAtIndexAndOffset(t2, e2) {
- let i2 = 0;
- for (let n2 = 0; n2 < this.objects.length; n2++) {
- const r2 = this.objects[n2];
- if (n2 < t2)
- i2 += r2.getLength();
- else if (n2 === t2) {
- i2 += e2;
- break;
- }
- }
- return i2;
- }
- getEndPosition() {
- return null == this.endPosition && (this.endPosition = 0, this.objects.forEach((t2) => this.endPosition += t2.getLength())), this.endPosition;
- }
- toString() {
- return this.objects.join("");
- }
- toArray() {
- return this.objects.slice(0);
- }
- toJSON() {
- return this.toArray();
- }
- isEqualTo(t2) {
- return super.isEqualTo(...arguments) || Le(this.objects, null == t2 ? void 0 : t2.objects);
- }
- contentsForInspection() {
- return { objects: "[".concat(this.objects.map((t2) => t2.inspect()).join(", "), "]") };
- }
- };
- var Le = function(t2) {
- let e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : [];
- if (t2.length !== e2.length)
- return false;
- let i2 = true;
- for (let n2 = 0; n2 < t2.length; n2++) {
- const r2 = t2[n2];
- i2 && !r2.isEqualTo(e2[n2]) && (i2 = false);
- }
- return i2;
- };
- var De = (t2) => t2[0];
- var we = (t2) => t2[1];
- var Te = class extends nt {
- static textForAttachmentWithAttributes(t2, e2) {
- return new this([new Se(t2, e2)]);
- }
- static textForStringWithAttributes(t2, e2) {
- return new this([new Ee(t2, e2)]);
- }
- static fromJSON(t2) {
- return new this(Array.from(t2).map((t3) => ye.fromJSON(t3)));
- }
- constructor() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
- super(...arguments);
- const e2 = t2.filter((t3) => !t3.isEmpty());
- this.pieceList = new ke(e2);
- }
- copy() {
- return this.copyWithPieceList(this.pieceList);
- }
- copyWithPieceList(t2) {
- return new this.constructor(t2.consolidate().toArray());
- }
- copyUsingObjectMap(t2) {
- const e2 = this.getPieces().map((e3) => t2.find(e3) || e3);
- return new this.constructor(e2);
- }
- appendText(t2) {
- return this.insertTextAtPosition(t2, this.getLength());
- }
- insertTextAtPosition(t2, e2) {
- return this.copyWithPieceList(this.pieceList.insertSplittableListAtPosition(t2.pieceList, e2));
- }
- removeTextAtRange(t2) {
- return this.copyWithPieceList(this.pieceList.removeObjectsInRange(t2));
- }
- replaceTextAtRange(t2, e2) {
- return this.removeTextAtRange(e2).insertTextAtPosition(t2, e2[0]);
- }
- moveTextFromRangeToPosition(t2, e2) {
- if (t2[0] <= e2 && e2 <= t2[1])
- return;
- const i2 = this.getTextAtRange(t2), n2 = i2.getLength();
- return t2[0] < e2 && (e2 -= n2), this.removeTextAtRange(t2).insertTextAtPosition(i2, e2);
- }
- addAttributeAtRange(t2, e2, i2) {
- const n2 = {};
- return n2[t2] = e2, this.addAttributesAtRange(n2, i2);
- }
- addAttributesAtRange(t2, e2) {
- return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e2, (e3) => e3.copyWithAdditionalAttributes(t2)));
- }
- removeAttributeAtRange(t2, e2) {
- return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e2, (e3) => e3.copyWithoutAttribute(t2)));
- }
- setAttributesAtRange(t2, e2) {
- return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e2, (e3) => e3.copyWithAttributes(t2)));
- }
- getAttributesAtPosition(t2) {
- var e2;
- return (null === (e2 = this.pieceList.getObjectAtPosition(t2)) || void 0 === e2 ? void 0 : e2.getAttributes()) || {};
- }
- getCommonAttributes() {
- const t2 = Array.from(this.pieceList.toArray()).map((t3) => t3.getAttributes());
- return _t.fromCommonAttributesOfObjects(t2).toObject();
- }
- getCommonAttributesAtRange(t2) {
- return this.getTextAtRange(t2).getCommonAttributes() || {};
- }
- getExpandedRangeForAttributeAtOffset(t2, e2) {
- let i2, n2 = i2 = e2;
- const r2 = this.getLength();
- for (; n2 > 0 && this.getCommonAttributesAtRange([n2 - 1, i2])[t2]; )
- n2--;
- for (; i2 < r2 && this.getCommonAttributesAtRange([e2, i2 + 1])[t2]; )
- i2++;
- return [n2, i2];
- }
- getTextAtRange(t2) {
- return this.copyWithPieceList(this.pieceList.getSplittableListInRange(t2));
- }
- getStringAtRange(t2) {
- return this.pieceList.getSplittableListInRange(t2).toString();
- }
- getStringAtPosition(t2) {
- return this.getStringAtRange([t2, t2 + 1]);
- }
- startsWithString(t2) {
- return this.getStringAtRange([0, t2.length]) === t2;
- }
- endsWithString(t2) {
- const e2 = this.getLength();
- return this.getStringAtRange([e2 - t2.length, e2]) === t2;
- }
- getAttachmentPieces() {
- return this.pieceList.toArray().filter((t2) => !!t2.attachment);
- }
- getAttachments() {
- return this.getAttachmentPieces().map((t2) => t2.attachment);
- }
- getAttachmentAndPositionById(t2) {
- let e2 = 0;
- for (const n2 of this.pieceList.toArray()) {
- var i2;
- if ((null === (i2 = n2.attachment) || void 0 === i2 ? void 0 : i2.id) === t2)
- return { attachment: n2.attachment, position: e2 };
- e2 += n2.length;
- }
- return { attachment: null, position: null };
- }
- getAttachmentById(t2) {
- const { attachment: e2 } = this.getAttachmentAndPositionById(t2);
- return e2;
- }
- getRangeOfAttachment(t2) {
- const e2 = this.getAttachmentAndPositionById(t2.id), i2 = e2.position;
- if (t2 = e2.attachment)
- return [i2, i2 + 1];
- }
- updateAttributesForAttachment(t2, e2) {
- const i2 = this.getRangeOfAttachment(e2);
- return i2 ? this.addAttributesAtRange(t2, i2) : this;
- }
- getLength() {
- return this.pieceList.getEndPosition();
- }
- isEmpty() {
- return 0 === this.getLength();
- }
- isEqualTo(t2) {
- var e2;
- return super.isEqualTo(t2) || (null == t2 || null === (e2 = t2.pieceList) || void 0 === e2 ? void 0 : e2.isEqualTo(this.pieceList));
- }
- isBlockBreak() {
- return 1 === this.getLength() && this.pieceList.getObjectAtIndex(0).isBlockBreak();
- }
- eachPiece(t2) {
- return this.pieceList.eachObject(t2);
- }
- getPieces() {
- return this.pieceList.toArray();
- }
- getPieceAtPosition(t2) {
- return this.pieceList.getObjectAtPosition(t2);
- }
- contentsForInspection() {
- return { pieceList: this.pieceList.inspect() };
- }
- toSerializableText() {
- const t2 = this.pieceList.selectSplittableList((t3) => t3.isSerializable());
- return this.copyWithPieceList(t2);
- }
- toString() {
- return this.pieceList.toString();
- }
- toJSON() {
- return this.pieceList.toJSON();
- }
- toConsole() {
- return JSON.stringify(this.pieceList.toArray().map((t2) => JSON.parse(t2.toConsole())));
- }
- getDirection() {
- return at(this.toString());
- }
- isRTL() {
- return "rtl" === this.getDirection();
- }
- };
- var Be = class extends nt {
- static fromJSON(t2) {
- return new this(Te.fromJSON(t2.text), t2.attributes);
- }
- constructor(t2, e2) {
- super(...arguments), this.text = Fe(t2 || new Te()), this.attributes = e2 || [];
- }
- isEmpty() {
- return this.text.isBlockBreak();
- }
- isEqualTo(t2) {
- return !!super.isEqualTo(t2) || this.text.isEqualTo(null == t2 ? void 0 : t2.text) && rt(this.attributes, null == t2 ? void 0 : t2.attributes);
- }
- copyWithText(t2) {
- return new Be(t2, this.attributes);
- }
- copyWithoutText() {
- return this.copyWithText(null);
- }
- copyWithAttributes(t2) {
- return new Be(this.text, t2);
- }
- copyWithoutAttributes() {
- return this.copyWithAttributes(null);
- }
- copyUsingObjectMap(t2) {
- const e2 = t2.find(this.text);
- return e2 ? this.copyWithText(e2) : this.copyWithText(this.text.copyUsingObjectMap(t2));
- }
- addAttribute(t2) {
- const e2 = this.attributes.concat(je(t2));
- return this.copyWithAttributes(e2);
- }
- removeAttribute(t2) {
- const { listAttribute: e2 } = gt(t2), i2 = Ue(Ue(this.attributes, t2), e2);
- return this.copyWithAttributes(i2);
- }
- removeLastAttribute() {
- return this.removeAttribute(this.getLastAttribute());
- }
- getLastAttribute() {
- return We(this.attributes);
- }
- getAttributes() {
- return this.attributes.slice(0);
- }
- getAttributeLevel() {
- return this.attributes.length;
- }
- getAttributeAtLevel(t2) {
- return this.attributes[t2 - 1];
- }
- hasAttribute(t2) {
- return this.attributes.includes(t2);
- }
- hasAttributes() {
- return this.getAttributeLevel() > 0;
- }
- getLastNestableAttribute() {
- return We(this.getNestableAttributes());
- }
- getNestableAttributes() {
- return this.attributes.filter((t2) => gt(t2).nestable);
- }
- getNestingLevel() {
- return this.getNestableAttributes().length;
- }
- decreaseNestingLevel() {
- const t2 = this.getLastNestableAttribute();
- return t2 ? this.removeAttribute(t2) : this;
- }
- increaseNestingLevel() {
- const t2 = this.getLastNestableAttribute();
- if (t2) {
- const e2 = this.attributes.lastIndexOf(t2), i2 = ot(this.attributes, e2 + 1, 0, ...je(t2));
- return this.copyWithAttributes(i2);
- }
- return this;
- }
- getListItemAttributes() {
- return this.attributes.filter((t2) => gt(t2).listAttribute);
- }
- isListItem() {
- var t2;
- return null === (t2 = gt(this.getLastAttribute())) || void 0 === t2 ? void 0 : t2.listAttribute;
- }
- isTerminalBlock() {
- var t2;
- return null === (t2 = gt(this.getLastAttribute())) || void 0 === t2 ? void 0 : t2.terminal;
- }
- breaksOnReturn() {
- var t2;
- return null === (t2 = gt(this.getLastAttribute())) || void 0 === t2 ? void 0 : t2.breakOnReturn;
- }
- findLineBreakInDirectionFromPosition(t2, e2) {
- const i2 = this.toString();
- let n2;
- switch (t2) {
- case "forward":
- n2 = i2.indexOf("\n", e2);
- break;
- case "backward":
- n2 = i2.slice(0, e2).lastIndexOf("\n");
- }
- if (-1 !== n2)
- return n2;
- }
- contentsForInspection() {
- return { text: this.text.inspect(), attributes: this.attributes };
- }
- toString() {
- return this.text.toString();
- }
- toJSON() {
- return { text: this.text, attributes: this.attributes };
- }
- getDirection() {
- return this.text.getDirection();
- }
- isRTL() {
- return this.text.isRTL();
- }
- getLength() {
- return this.text.getLength();
- }
- canBeConsolidatedWith(t2) {
- return !this.hasAttributes() && !t2.hasAttributes() && this.getDirection() === t2.getDirection();
- }
- consolidateWith(t2) {
- const e2 = Te.textForStringWithAttributes("\n"), i2 = this.getTextWithoutBlockBreak().appendText(e2);
- return this.copyWithText(i2.appendText(t2.text));
- }
- splitAtOffset(t2) {
- let e2, i2;
- return 0 === t2 ? (e2 = null, i2 = this) : t2 === this.getLength() ? (e2 = this, i2 = null) : (e2 = this.copyWithText(this.text.getTextAtRange([0, t2])), i2 = this.copyWithText(this.text.getTextAtRange([t2, this.getLength()]))), [e2, i2];
- }
- getBlockBreakPosition() {
- return this.text.getLength() - 1;
- }
- getTextWithoutBlockBreak() {
- return Oe(this.text) ? this.text.getTextAtRange([0, this.getBlockBreakPosition()]) : this.text.copy();
- }
- canBeGrouped(t2) {
- return this.attributes[t2];
- }
- canBeGroupedWith(t2, e2) {
- const i2 = t2.getAttributes(), r2 = i2[e2], o2 = this.attributes[e2];
- return o2 === r2 && !(false === gt(o2).group && !(() => {
- if (!ut) {
- ut = [];
- for (const t3 in n) {
- const { listAttribute: e3 } = n[t3];
- null != e3 && ut.push(e3);
- }
- }
- return ut;
- })().includes(i2[e2 + 1])) && (this.getDirection() === t2.getDirection() || t2.isEmpty());
- }
- };
- var Fe = function(t2) {
- return t2 = Ie(t2), t2 = Ne(t2);
- };
- var Ie = function(t2) {
- let e2 = false;
- const i2 = t2.getPieces();
- let n2 = i2.slice(0, i2.length - 1);
- const r2 = i2[i2.length - 1];
- return r2 ? (n2 = n2.map((t3) => t3.isBlockBreak() ? (e2 = true, Me(t3)) : t3), e2 ? new Te([...n2, r2]) : t2) : t2;
- };
- var Pe = Te.textForStringWithAttributes("\n", { blockBreak: true });
- var Ne = function(t2) {
- return Oe(t2) ? t2 : t2.appendText(Pe);
- };
- var Oe = function(t2) {
- const e2 = t2.getLength();
- if (0 === e2)
- return false;
- return t2.getTextAtRange([e2 - 1, e2]).isBlockBreak();
- };
- var Me = (t2) => t2.copyWithoutAttribute("blockBreak");
- var je = function(t2) {
- const { listAttribute: e2 } = gt(t2);
- return e2 ? [e2, t2] : [t2];
- };
- var We = (t2) => t2.slice(-1)[0];
- var Ue = function(t2, e2) {
- const i2 = t2.lastIndexOf(e2);
- return -1 === i2 ? t2 : ot(t2, i2, 1);
- };
- var qe = class extends nt {
- static fromJSON(t2) {
- return new this(Array.from(t2).map((t3) => Be.fromJSON(t3)));
- }
- static fromString(t2, e2) {
- const i2 = Te.textForStringWithAttributes(t2, e2);
- return new this([new Be(i2)]);
- }
- constructor() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
- super(...arguments), 0 === t2.length && (t2 = [new Be()]), this.blockList = ke.box(t2);
- }
- isEmpty() {
- const t2 = this.getBlockAtIndex(0);
- return 1 === this.blockList.length && t2.isEmpty() && !t2.hasAttributes();
- }
- copy() {
- const t2 = (arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}).consolidateBlocks ? this.blockList.consolidate().toArray() : this.blockList.toArray();
- return new this.constructor(t2);
- }
- copyUsingObjectsFromDocument(t2) {
- const e2 = new Yt(t2.getObjects());
- return this.copyUsingObjectMap(e2);
- }
- copyUsingObjectMap(t2) {
- const e2 = this.getBlocks().map((e3) => t2.find(e3) || e3.copyUsingObjectMap(t2));
- return new this.constructor(e2);
- }
- copyWithBaseBlockAttributes() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [];
- const e2 = this.getBlocks().map((e3) => {
- const i2 = t2.concat(e3.getAttributes());
- return e3.copyWithAttributes(i2);
- });
- return new this.constructor(e2);
- }
- replaceBlock(t2, e2) {
- const i2 = this.blockList.indexOf(t2);
- return -1 === i2 ? this : new this.constructor(this.blockList.replaceObjectAtIndex(e2, i2));
- }
- insertDocumentAtRange(t2, e2) {
- const { blockList: i2 } = t2;
- e2 = Lt(e2);
- let [n2] = e2;
- const { index: r2, offset: o2 } = this.locationFromPosition(n2);
- let s2 = this;
- const a2 = this.getBlockAtPosition(n2);
- return Dt(e2) && a2.isEmpty() && !a2.hasAttributes() ? s2 = new this.constructor(s2.blockList.removeObjectAtIndex(r2)) : a2.getBlockBreakPosition() === o2 && n2++, s2 = s2.removeTextAtRange(e2), new this.constructor(s2.blockList.insertSplittableListAtPosition(i2, n2));
- }
- mergeDocumentAtRange(t2, e2) {
- let i2, n2;
- e2 = Lt(e2);
- const [r2] = e2, o2 = this.locationFromPosition(r2), s2 = this.getBlockAtIndex(o2.index).getAttributes(), a2 = t2.getBaseBlockAttributes(), l2 = s2.slice(-a2.length);
- if (rt(a2, l2)) {
- const e3 = s2.slice(0, -a2.length);
- i2 = t2.copyWithBaseBlockAttributes(e3);
- } else
- i2 = t2.copy({ consolidateBlocks: true }).copyWithBaseBlockAttributes(s2);
- const c2 = i2.getBlockCount(), h2 = i2.getBlockAtIndex(0);
- if (rt(s2, h2.getAttributes())) {
- const t3 = h2.getTextWithoutBlockBreak();
- if (n2 = this.insertTextAtRange(t3, e2), c2 > 1) {
- i2 = new this.constructor(i2.getBlocks().slice(1));
- const e3 = r2 + t3.getLength();
- n2 = n2.insertDocumentAtRange(i2, e3);
- }
- } else
- n2 = this.insertDocumentAtRange(i2, e2);
- return n2;
- }
- insertTextAtRange(t2, e2) {
- e2 = Lt(e2);
- const [i2] = e2, { index: n2, offset: r2 } = this.locationFromPosition(i2), o2 = this.removeTextAtRange(e2);
- return new this.constructor(o2.blockList.editObjectAtIndex(n2, (e3) => e3.copyWithText(e3.text.insertTextAtPosition(t2, r2))));
- }
- removeTextAtRange(t2) {
- let e2;
- t2 = Lt(t2);
- const [i2, n2] = t2;
- if (Dt(t2))
- return this;
- const [r2, o2] = Array.from(this.locationRangeFromRange(t2)), s2 = r2.index, a2 = r2.offset, l2 = this.getBlockAtIndex(s2), c2 = o2.index, h2 = o2.offset, u2 = this.getBlockAtIndex(c2);
- if (n2 - i2 == 1 && l2.getBlockBreakPosition() === a2 && u2.getBlockBreakPosition() !== h2 && "\n" === u2.text.getStringAtPosition(h2))
- e2 = this.blockList.editObjectAtIndex(c2, (t3) => t3.copyWithText(t3.text.removeTextAtRange([h2, h2 + 1])));
- else {
- let t3;
- const i3 = l2.text.getTextAtRange([0, a2]), n3 = u2.text.getTextAtRange([h2, u2.getLength()]), r3 = i3.appendText(n3);
- t3 = s2 !== c2 && 0 === a2 && l2.getAttributeLevel() >= u2.getAttributeLevel() ? u2.copyWithText(r3) : l2.copyWithText(r3);
- const o3 = c2 + 1 - s2;
- e2 = this.blockList.splice(s2, o3, t3);
- }
- return new this.constructor(e2);
- }
- moveTextFromRangeToPosition(t2, e2) {
- let i2;
- t2 = Lt(t2);
- const [n2, r2] = t2;
- if (n2 <= e2 && e2 <= r2)
- return this;
- let o2 = this.getDocumentAtRange(t2), s2 = this.removeTextAtRange(t2);
- const a2 = n2 < e2;
- a2 && (e2 -= o2.getLength());
- const [l2, ...c2] = o2.getBlocks();
- return 0 === c2.length ? (i2 = l2.getTextWithoutBlockBreak(), a2 && (e2 += 1)) : i2 = l2.text, s2 = s2.insertTextAtRange(i2, e2), 0 === c2.length ? s2 : (o2 = new this.constructor(c2), e2 += i2.getLength(), s2.insertDocumentAtRange(o2, e2));
- }
- addAttributeAtRange(t2, e2, i2) {
- let { blockList: n2 } = this;
- return this.eachBlockAtRange(i2, (i3, r2, o2) => n2 = n2.editObjectAtIndex(o2, function() {
- return gt(t2) ? i3.addAttribute(t2, e2) : r2[0] === r2[1] ? i3 : i3.copyWithText(i3.text.addAttributeAtRange(t2, e2, r2));
- })), new this.constructor(n2);
- }
- addAttribute(t2, e2) {
- let { blockList: i2 } = this;
- return this.eachBlock((n2, r2) => i2 = i2.editObjectAtIndex(r2, () => n2.addAttribute(t2, e2))), new this.constructor(i2);
- }
- removeAttributeAtRange(t2, e2) {
- let { blockList: i2 } = this;
- return this.eachBlockAtRange(e2, function(e3, n2, r2) {
- gt(t2) ? i2 = i2.editObjectAtIndex(r2, () => e3.removeAttribute(t2)) : n2[0] !== n2[1] && (i2 = i2.editObjectAtIndex(r2, () => e3.copyWithText(e3.text.removeAttributeAtRange(t2, n2))));
- }), new this.constructor(i2);
- }
- updateAttributesForAttachment(t2, e2) {
- const i2 = this.getRangeOfAttachment(e2), [n2] = Array.from(i2), { index: r2 } = this.locationFromPosition(n2), o2 = this.getTextAtIndex(r2);
- return new this.constructor(this.blockList.editObjectAtIndex(r2, (i3) => i3.copyWithText(o2.updateAttributesForAttachment(t2, e2))));
- }
- removeAttributeForAttachment(t2, e2) {
- const i2 = this.getRangeOfAttachment(e2);
- return this.removeAttributeAtRange(t2, i2);
- }
- insertBlockBreakAtRange(t2) {
- let e2;
- t2 = Lt(t2);
- const [i2] = t2, { offset: n2 } = this.locationFromPosition(i2), r2 = this.removeTextAtRange(t2);
- return 0 === n2 && (e2 = [new Be()]), new this.constructor(r2.blockList.insertSplittableListAtPosition(new ke(e2), i2));
- }
- applyBlockAttributeAtRange(t2, e2, i2) {
- const n2 = this.expandRangeToLineBreaksAndSplitBlocks(i2);
- let r2 = n2.document;
- i2 = n2.range;
- const o2 = gt(t2);
- if (o2.listAttribute) {
- r2 = r2.removeLastListAttributeAtRange(i2, { exceptAttributeName: t2 });
- const e3 = r2.convertLineBreaksToBlockBreaksInRange(i2);
- r2 = e3.document, i2 = e3.range;
- } else
- r2 = o2.exclusive ? r2.removeBlockAttributesAtRange(i2) : o2.terminal ? r2.removeLastTerminalAttributeAtRange(i2) : r2.consolidateBlocksAtRange(i2);
- return r2.addAttributeAtRange(t2, e2, i2);
- }
- removeLastListAttributeAtRange(t2) {
- let e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, { blockList: i2 } = this;
- return this.eachBlockAtRange(t2, function(t3, n2, r2) {
- const o2 = t3.getLastAttribute();
- o2 && gt(o2).listAttribute && o2 !== e2.exceptAttributeName && (i2 = i2.editObjectAtIndex(r2, () => t3.removeAttribute(o2)));
- }), new this.constructor(i2);
- }
- removeLastTerminalAttributeAtRange(t2) {
- let { blockList: e2 } = this;
- return this.eachBlockAtRange(t2, function(t3, i2, n2) {
- const r2 = t3.getLastAttribute();
- r2 && gt(r2).terminal && (e2 = e2.editObjectAtIndex(n2, () => t3.removeAttribute(r2)));
- }), new this.constructor(e2);
- }
- removeBlockAttributesAtRange(t2) {
- let { blockList: e2 } = this;
- return this.eachBlockAtRange(t2, function(t3, i2, n2) {
- t3.hasAttributes() && (e2 = e2.editObjectAtIndex(n2, () => t3.copyWithoutAttributes()));
- }), new this.constructor(e2);
- }
- expandRangeToLineBreaksAndSplitBlocks(t2) {
- let e2;
- t2 = Lt(t2);
- let [i2, n2] = t2;
- const r2 = this.locationFromPosition(i2), o2 = this.locationFromPosition(n2);
- let s2 = this;
- const a2 = s2.getBlockAtIndex(r2.index);
- if (r2.offset = a2.findLineBreakInDirectionFromPosition("backward", r2.offset), null != r2.offset && (e2 = s2.positionFromLocation(r2), s2 = s2.insertBlockBreakAtRange([e2, e2 + 1]), o2.index += 1, o2.offset -= s2.getBlockAtIndex(r2.index).getLength(), r2.index += 1), r2.offset = 0, 0 === o2.offset && o2.index > r2.index)
- o2.index -= 1, o2.offset = s2.getBlockAtIndex(o2.index).getBlockBreakPosition();
- else {
- const t3 = s2.getBlockAtIndex(o2.index);
- "\n" === t3.text.getStringAtRange([o2.offset - 1, o2.offset]) ? o2.offset -= 1 : o2.offset = t3.findLineBreakInDirectionFromPosition("forward", o2.offset), o2.offset !== t3.getBlockBreakPosition() && (e2 = s2.positionFromLocation(o2), s2 = s2.insertBlockBreakAtRange([e2, e2 + 1]));
- }
- return i2 = s2.positionFromLocation(r2), n2 = s2.positionFromLocation(o2), { document: s2, range: t2 = Lt([i2, n2]) };
- }
- convertLineBreaksToBlockBreaksInRange(t2) {
- t2 = Lt(t2);
- let [e2] = t2;
- const i2 = this.getStringAtRange(t2).slice(0, -1);
- let n2 = this;
- return i2.replace(/.*?\n/g, function(t3) {
- e2 += t3.length, n2 = n2.insertBlockBreakAtRange([e2 - 1, e2]);
- }), { document: n2, range: t2 };
- }
- consolidateBlocksAtRange(t2) {
- t2 = Lt(t2);
- const [e2, i2] = t2, n2 = this.locationFromPosition(e2).index, r2 = this.locationFromPosition(i2).index;
- return new this.constructor(this.blockList.consolidateFromIndexToIndex(n2, r2));
- }
- getDocumentAtRange(t2) {
- t2 = Lt(t2);
- const e2 = this.blockList.getSplittableListInRange(t2).toArray();
- return new this.constructor(e2);
- }
- getStringAtRange(t2) {
- let e2;
- const i2 = t2 = Lt(t2);
- return i2[i2.length - 1] !== this.getLength() && (e2 = -1), this.getDocumentAtRange(t2).toString().slice(0, e2);
- }
- getBlockAtIndex(t2) {
- return this.blockList.getObjectAtIndex(t2);
- }
- getBlockAtPosition(t2) {
- const { index: e2 } = this.locationFromPosition(t2);
- return this.getBlockAtIndex(e2);
- }
- getTextAtIndex(t2) {
- var e2;
- return null === (e2 = this.getBlockAtIndex(t2)) || void 0 === e2 ? void 0 : e2.text;
- }
- getTextAtPosition(t2) {
- const { index: e2 } = this.locationFromPosition(t2);
- return this.getTextAtIndex(e2);
- }
- getPieceAtPosition(t2) {
- const { index: e2, offset: i2 } = this.locationFromPosition(t2);
- return this.getTextAtIndex(e2).getPieceAtPosition(i2);
- }
- getCharacterAtPosition(t2) {
- const { index: e2, offset: i2 } = this.locationFromPosition(t2);
- return this.getTextAtIndex(e2).getStringAtRange([i2, i2 + 1]);
- }
- getLength() {
- return this.blockList.getEndPosition();
- }
- getBlocks() {
- return this.blockList.toArray();
- }
- getBlockCount() {
- return this.blockList.length;
- }
- getEditCount() {
- return this.editCount;
- }
- eachBlock(t2) {
- return this.blockList.eachObject(t2);
- }
- eachBlockAtRange(t2, e2) {
- let i2, n2;
- t2 = Lt(t2);
- const [r2, o2] = t2, s2 = this.locationFromPosition(r2), a2 = this.locationFromPosition(o2);
- if (s2.index === a2.index)
- return i2 = this.getBlockAtIndex(s2.index), n2 = [s2.offset, a2.offset], e2(i2, n2, s2.index);
- for (let t3 = s2.index; t3 <= a2.index; t3++)
- if (i2 = this.getBlockAtIndex(t3), i2) {
- switch (t3) {
- case s2.index:
- n2 = [s2.offset, i2.text.getLength()];
- break;
- case a2.index:
- n2 = [0, a2.offset];
- break;
- default:
- n2 = [0, i2.text.getLength()];
- }
- e2(i2, n2, t3);
- }
- }
- getCommonAttributesAtRange(t2) {
- t2 = Lt(t2);
- const [e2] = t2;
- if (Dt(t2))
- return this.getCommonAttributesAtPosition(e2);
- {
- const e3 = [], i2 = [];
- return this.eachBlockAtRange(t2, function(t3, n2) {
- if (n2[0] !== n2[1])
- return e3.push(t3.text.getCommonAttributesAtRange(n2)), i2.push(Ve(t3));
- }), _t.fromCommonAttributesOfObjects(e3).merge(_t.fromCommonAttributesOfObjects(i2)).toObject();
- }
- }
- getCommonAttributesAtPosition(t2) {
- let e2, i2;
- const { index: n2, offset: r2 } = this.locationFromPosition(t2), o2 = this.getBlockAtIndex(n2);
- if (!o2)
- return {};
- const s2 = Ve(o2), a2 = o2.text.getAttributesAtPosition(r2), l2 = o2.text.getAttributesAtPosition(r2 - 1), c2 = Object.keys(W).filter((t3) => W[t3].inheritable);
- for (e2 in l2)
- i2 = l2[e2], (i2 === a2[e2] || c2.includes(e2)) && (s2[e2] = i2);
- return s2;
- }
- getRangeOfCommonAttributeAtPosition(t2, e2) {
- const { index: i2, offset: n2 } = this.locationFromPosition(e2), r2 = this.getTextAtIndex(i2), [o2, s2] = Array.from(r2.getExpandedRangeForAttributeAtOffset(t2, n2)), a2 = this.positionFromLocation({ index: i2, offset: o2 }), l2 = this.positionFromLocation({ index: i2, offset: s2 });
- return Lt([a2, l2]);
- }
- getBaseBlockAttributes() {
- let t2 = this.getBlockAtIndex(0).getAttributes();
- for (let e2 = 1; e2 < this.getBlockCount(); e2++) {
- const i2 = this.getBlockAtIndex(e2).getAttributes(), n2 = Math.min(t2.length, i2.length);
- t2 = (() => {
- const e3 = [];
- for (let r2 = 0; r2 < n2 && i2[r2] === t2[r2]; r2++)
- e3.push(i2[r2]);
- return e3;
- })();
- }
- return t2;
- }
- getAttachmentById(t2) {
- for (const e2 of this.getAttachments())
- if (e2.id === t2)
- return e2;
- }
- getAttachmentPieces() {
- let t2 = [];
- return this.blockList.eachObject((e2) => {
- let { text: i2 } = e2;
- return t2 = t2.concat(i2.getAttachmentPieces());
- }), t2;
- }
- getAttachments() {
- return this.getAttachmentPieces().map((t2) => t2.attachment);
- }
- getRangeOfAttachment(t2) {
- let e2 = 0;
- const i2 = this.blockList.toArray();
- for (let n2 = 0; n2 < i2.length; n2++) {
- const { text: r2 } = i2[n2], o2 = r2.getRangeOfAttachment(t2);
- if (o2)
- return Lt([e2 + o2[0], e2 + o2[1]]);
- e2 += r2.getLength();
- }
- }
- getLocationRangeOfAttachment(t2) {
- const e2 = this.getRangeOfAttachment(t2);
- return this.locationRangeFromRange(e2);
- }
- getAttachmentPieceForAttachment(t2) {
- for (const e2 of this.getAttachmentPieces())
- if (e2.attachment === t2)
- return e2;
- }
- findRangesForBlockAttribute(t2) {
- let e2 = 0;
- const i2 = [];
- return this.getBlocks().forEach((n2) => {
- const r2 = n2.getLength();
- n2.hasAttribute(t2) && i2.push([e2, e2 + r2]), e2 += r2;
- }), i2;
- }
- findRangesForTextAttribute(t2) {
- let { withValue: e2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, i2 = 0, n2 = [];
- const r2 = [];
- return this.getPieces().forEach((o2) => {
- const s2 = o2.getLength();
- (function(i3) {
- return e2 ? i3.getAttribute(t2) === e2 : i3.hasAttribute(t2);
- })(o2) && (n2[1] === i2 ? n2[1] = i2 + s2 : r2.push(n2 = [i2, i2 + s2])), i2 += s2;
- }), r2;
- }
- locationFromPosition(t2) {
- const e2 = this.blockList.findIndexAndOffsetAtPosition(Math.max(0, t2));
- if (null != e2.index)
- return e2;
- {
- const t3 = this.getBlocks();
- return { index: t3.length - 1, offset: t3[t3.length - 1].getLength() };
- }
- }
- positionFromLocation(t2) {
- return this.blockList.findPositionAtIndexAndOffset(t2.index, t2.offset);
- }
- locationRangeFromPosition(t2) {
- return Lt(this.locationFromPosition(t2));
- }
- locationRangeFromRange(t2) {
- if (!(t2 = Lt(t2)))
- return;
- const [e2, i2] = Array.from(t2), n2 = this.locationFromPosition(e2), r2 = this.locationFromPosition(i2);
- return Lt([n2, r2]);
- }
- rangeFromLocationRange(t2) {
- let e2;
- t2 = Lt(t2);
- const i2 = this.positionFromLocation(t2[0]);
- return Dt(t2) || (e2 = this.positionFromLocation(t2[1])), Lt([i2, e2]);
- }
- isEqualTo(t2) {
- return this.blockList.isEqualTo(null == t2 ? void 0 : t2.blockList);
- }
- getTexts() {
- return this.getBlocks().map((t2) => t2.text);
- }
- getPieces() {
- const t2 = [];
- return Array.from(this.getTexts()).forEach((e2) => {
- t2.push(...Array.from(e2.getPieces() || []));
- }), t2;
- }
- getObjects() {
- return this.getBlocks().concat(this.getTexts()).concat(this.getPieces());
- }
- toSerializableDocument() {
- const t2 = [];
- return this.blockList.eachObject((e2) => t2.push(e2.copyWithText(e2.text.toSerializableText()))), new this.constructor(t2);
- }
- toString() {
- return this.blockList.toString();
- }
- toJSON() {
- return this.blockList.toJSON();
- }
- toConsole() {
- return JSON.stringify(this.blockList.toArray().map((t2) => JSON.parse(t2.text.toConsole())));
- }
- };
- var Ve = function(t2) {
- const e2 = {}, i2 = t2.getLastAttribute();
- return i2 && (e2[i2] = true), e2;
- };
- var ze = "style href src width height class".split(" ");
- var _e = "javascript:".split(" ");
- var He = "script iframe form".split(" ");
- var Je = class extends z {
- static sanitize(t2, e2) {
- const i2 = new this(t2, e2);
- return i2.sanitize(), i2;
- }
- constructor(t2) {
- let { allowedAttributes: e2, forbiddenProtocols: i2, forbiddenElements: n2 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
- super(...arguments), this.allowedAttributes = e2 || ze, this.forbiddenProtocols = i2 || _e, this.forbiddenElements = n2 || He, this.body = Ke(t2);
- }
- sanitize() {
- return this.sanitizeElements(), this.normalizeListElementNesting();
- }
- getHTML() {
- return this.body.innerHTML;
- }
- getBody() {
- return this.body;
- }
- sanitizeElements() {
- const t2 = S(this.body), e2 = [];
- for (; t2.nextNode(); ) {
- const i2 = t2.currentNode;
- switch (i2.nodeType) {
- case Node.ELEMENT_NODE:
- this.elementIsRemovable(i2) ? e2.push(i2) : this.sanitizeElement(i2);
- break;
- case Node.COMMENT_NODE:
- e2.push(i2);
- }
- }
- return e2.forEach((t3) => R(t3)), this.body;
- }
- sanitizeElement(t2) {
- return t2.hasAttribute("href") && this.forbiddenProtocols.includes(t2.protocol) && t2.removeAttribute("href"), Array.from(t2.attributes).forEach((e2) => {
- let { name: i2 } = e2;
- this.allowedAttributes.includes(i2) || 0 === i2.indexOf("data-trix") || t2.removeAttribute(i2);
- }), t2;
- }
- normalizeListElementNesting() {
- return Array.from(this.body.querySelectorAll("ul,ol")).forEach((t2) => {
- const e2 = t2.previousElementSibling;
- e2 && "li" === E(e2) && e2.appendChild(t2);
- }), this.body;
- }
- elementIsRemovable(t2) {
- if ((null == t2 ? void 0 : t2.nodeType) === Node.ELEMENT_NODE)
- return this.elementIsForbidden(t2) || this.elementIsntSerializable(t2);
- }
- elementIsForbidden(t2) {
- return this.forbiddenElements.includes(E(t2));
- }
- elementIsntSerializable(t2) {
- return "false" === t2.getAttribute("data-trix-serialize") && !P(t2);
- }
- };
- var Ke = function() {
- let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "";
- t2 = t2.replace(/<\/html[^>]*>[^]*$/i, "