package.dist.cdn.js Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of alpinejs Show documentation
Show all versions of alpinejs Show documentation
The rugged, minimal JavaScript framework
The newest version!
(() => {
// packages/alpinejs/src/scheduler.js
var flushPending = false;
var flushing = false;
var queue = [];
var lastFlushedIndex = -1;
function scheduler(callback) {
queueJob(callback);
}
function queueJob(job) {
if (!queue.includes(job))
queue.push(job);
queueFlush();
}
function dequeueJob(job) {
let index = queue.indexOf(job);
if (index !== -1 && index > lastFlushedIndex)
queue.splice(index, 1);
}
function queueFlush() {
if (!flushing && !flushPending) {
flushPending = true;
queueMicrotask(flushJobs);
}
}
function flushJobs() {
flushPending = false;
flushing = true;
for (let i = 0; i < queue.length; i++) {
queue[i]();
lastFlushedIndex = i;
}
queue.length = 0;
lastFlushedIndex = -1;
flushing = false;
}
// packages/alpinejs/src/reactivity.js
var reactive;
var effect;
var release;
var raw;
var shouldSchedule = true;
function disableEffectScheduling(callback) {
shouldSchedule = false;
callback();
shouldSchedule = true;
}
function setReactivityEngine(engine) {
reactive = engine.reactive;
release = engine.release;
effect = (callback) => engine.effect(callback, { scheduler: (task) => {
if (shouldSchedule) {
scheduler(task);
} else {
task();
}
} });
raw = engine.raw;
}
function overrideEffect(override) {
effect = override;
}
function elementBoundEffect(el) {
let cleanup2 = () => {
};
let wrappedEffect = (callback) => {
let effectReference = effect(callback);
if (!el._x_effects) {
el._x_effects = /* @__PURE__ */ new Set();
el._x_runEffects = () => {
el._x_effects.forEach((i) => i());
};
}
el._x_effects.add(effectReference);
cleanup2 = () => {
if (effectReference === void 0)
return;
el._x_effects.delete(effectReference);
release(effectReference);
};
return effectReference;
};
return [wrappedEffect, () => {
cleanup2();
}];
}
function watch(getter, callback) {
let firstTime = true;
let oldValue;
let effectReference = effect(() => {
let value = getter();
JSON.stringify(value);
if (!firstTime) {
queueMicrotask(() => {
callback(value, oldValue);
oldValue = value;
});
} else {
oldValue = value;
}
firstTime = false;
});
return () => release(effectReference);
}
// packages/alpinejs/src/mutation.js
var onAttributeAddeds = [];
var onElRemoveds = [];
var onElAddeds = [];
function onElAdded(callback) {
onElAddeds.push(callback);
}
function onElRemoved(el, callback) {
if (typeof callback === "function") {
if (!el._x_cleanups)
el._x_cleanups = [];
el._x_cleanups.push(callback);
} else {
callback = el;
onElRemoveds.push(callback);
}
}
function onAttributesAdded(callback) {
onAttributeAddeds.push(callback);
}
function onAttributeRemoved(el, name, callback) {
if (!el._x_attributeCleanups)
el._x_attributeCleanups = {};
if (!el._x_attributeCleanups[name])
el._x_attributeCleanups[name] = [];
el._x_attributeCleanups[name].push(callback);
}
function cleanupAttributes(el, names) {
if (!el._x_attributeCleanups)
return;
Object.entries(el._x_attributeCleanups).forEach(([name, value]) => {
if (names === void 0 || names.includes(name)) {
value.forEach((i) => i());
delete el._x_attributeCleanups[name];
}
});
}
function cleanupElement(el) {
el._x_effects?.forEach(dequeueJob);
while (el._x_cleanups?.length)
el._x_cleanups.pop()();
}
var observer = new MutationObserver(onMutate);
var currentlyObserving = false;
function startObservingMutations() {
observer.observe(document, { subtree: true, childList: true, attributes: true, attributeOldValue: true });
currentlyObserving = true;
}
function stopObservingMutations() {
flushObserver();
observer.disconnect();
currentlyObserving = false;
}
var queuedMutations = [];
function flushObserver() {
let records = observer.takeRecords();
queuedMutations.push(() => records.length > 0 && onMutate(records));
let queueLengthWhenTriggered = queuedMutations.length;
queueMicrotask(() => {
if (queuedMutations.length === queueLengthWhenTriggered) {
while (queuedMutations.length > 0)
queuedMutations.shift()();
}
});
}
function mutateDom(callback) {
if (!currentlyObserving)
return callback();
stopObservingMutations();
let result = callback();
startObservingMutations();
return result;
}
var isCollecting = false;
var deferredMutations = [];
function deferMutations() {
isCollecting = true;
}
function flushAndStopDeferringMutations() {
isCollecting = false;
onMutate(deferredMutations);
deferredMutations = [];
}
function onMutate(mutations) {
if (isCollecting) {
deferredMutations = deferredMutations.concat(mutations);
return;
}
let addedNodes = [];
let removedNodes = /* @__PURE__ */ new Set();
let addedAttributes = /* @__PURE__ */ new Map();
let removedAttributes = /* @__PURE__ */ new Map();
for (let i = 0; i < mutations.length; i++) {
if (mutations[i].target._x_ignoreMutationObserver)
continue;
if (mutations[i].type === "childList") {
mutations[i].removedNodes.forEach((node) => {
if (node.nodeType !== 1)
return;
if (!node._x_marker)
return;
removedNodes.add(node);
});
mutations[i].addedNodes.forEach((node) => {
if (node.nodeType !== 1)
return;
if (removedNodes.has(node)) {
removedNodes.delete(node);
return;
}
if (node._x_marker)
return;
addedNodes.push(node);
});
}
if (mutations[i].type === "attributes") {
let el = mutations[i].target;
let name = mutations[i].attributeName;
let oldValue = mutations[i].oldValue;
let add2 = () => {
if (!addedAttributes.has(el))
addedAttributes.set(el, []);
addedAttributes.get(el).push({ name, value: el.getAttribute(name) });
};
let remove = () => {
if (!removedAttributes.has(el))
removedAttributes.set(el, []);
removedAttributes.get(el).push(name);
};
if (el.hasAttribute(name) && oldValue === null) {
add2();
} else if (el.hasAttribute(name)) {
remove();
add2();
} else {
remove();
}
}
}
removedAttributes.forEach((attrs, el) => {
cleanupAttributes(el, attrs);
});
addedAttributes.forEach((attrs, el) => {
onAttributeAddeds.forEach((i) => i(el, attrs));
});
for (let node of removedNodes) {
if (addedNodes.some((i) => i.contains(node)))
continue;
onElRemoveds.forEach((i) => i(node));
}
for (let node of addedNodes) {
if (!node.isConnected)
continue;
onElAddeds.forEach((i) => i(node));
}
addedNodes = null;
removedNodes = null;
addedAttributes = null;
removedAttributes = null;
}
// packages/alpinejs/src/scope.js
function scope(node) {
return mergeProxies(closestDataStack(node));
}
function addScopeToNode(node, data2, referenceNode) {
node._x_dataStack = [data2, ...closestDataStack(referenceNode || node)];
return () => {
node._x_dataStack = node._x_dataStack.filter((i) => i !== data2);
};
}
function closestDataStack(node) {
if (node._x_dataStack)
return node._x_dataStack;
if (typeof ShadowRoot === "function" && node instanceof ShadowRoot) {
return closestDataStack(node.host);
}
if (!node.parentNode) {
return [];
}
return closestDataStack(node.parentNode);
}
function mergeProxies(objects) {
return new Proxy({ objects }, mergeProxyTrap);
}
var mergeProxyTrap = {
ownKeys({ objects }) {
return Array.from(
new Set(objects.flatMap((i) => Object.keys(i)))
);
},
has({ objects }, name) {
if (name == Symbol.unscopables)
return false;
return objects.some(
(obj) => Object.prototype.hasOwnProperty.call(obj, name) || Reflect.has(obj, name)
);
},
get({ objects }, name, thisProxy) {
if (name == "toJSON")
return collapseProxies;
return Reflect.get(
objects.find(
(obj) => Reflect.has(obj, name)
) || {},
name,
thisProxy
);
},
set({ objects }, name, value, thisProxy) {
const target = objects.find(
(obj) => Object.prototype.hasOwnProperty.call(obj, name)
) || objects[objects.length - 1];
const descriptor = Object.getOwnPropertyDescriptor(target, name);
if (descriptor?.set && descriptor?.get)
return descriptor.set.call(thisProxy, value) || true;
return Reflect.set(target, name, value);
}
};
function collapseProxies() {
let keys = Reflect.ownKeys(this);
return keys.reduce((acc, key) => {
acc[key] = Reflect.get(this, key);
return acc;
}, {});
}
// packages/alpinejs/src/interceptor.js
function initInterceptors(data2) {
let isObject2 = (val) => typeof val === "object" && !Array.isArray(val) && val !== null;
let recurse = (obj, basePath = "") => {
Object.entries(Object.getOwnPropertyDescriptors(obj)).forEach(([key, { value, enumerable }]) => {
if (enumerable === false || value === void 0)
return;
if (typeof value === "object" && value !== null && value.__v_skip)
return;
let path = basePath === "" ? key : `${basePath}.${key}`;
if (typeof value === "object" && value !== null && value._x_interceptor) {
obj[key] = value.initialize(data2, path, key);
} else {
if (isObject2(value) && value !== obj && !(value instanceof Element)) {
recurse(value, path);
}
}
});
};
return recurse(data2);
}
function interceptor(callback, mutateObj = () => {
}) {
let obj = {
initialValue: void 0,
_x_interceptor: true,
initialize(data2, path, key) {
return callback(this.initialValue, () => get(data2, path), (value) => set(data2, path, value), path, key);
}
};
mutateObj(obj);
return (initialValue) => {
if (typeof initialValue === "object" && initialValue !== null && initialValue._x_interceptor) {
let initialize = obj.initialize.bind(obj);
obj.initialize = (data2, path, key) => {
let innerValue = initialValue.initialize(data2, path, key);
obj.initialValue = innerValue;
return initialize(data2, path, key);
};
} else {
obj.initialValue = initialValue;
}
return obj;
};
}
function get(obj, path) {
return path.split(".").reduce((carry, segment) => carry[segment], obj);
}
function set(obj, path, value) {
if (typeof path === "string")
path = path.split(".");
if (path.length === 1)
obj[path[0]] = value;
else if (path.length === 0)
throw error;
else {
if (obj[path[0]])
return set(obj[path[0]], path.slice(1), value);
else {
obj[path[0]] = {};
return set(obj[path[0]], path.slice(1), value);
}
}
}
// packages/alpinejs/src/magics.js
var magics = {};
function magic(name, callback) {
magics[name] = callback;
}
function injectMagics(obj, el) {
let memoizedUtilities = getUtilities(el);
Object.entries(magics).forEach(([name, callback]) => {
Object.defineProperty(obj, `$${name}`, {
get() {
return callback(el, memoizedUtilities);
},
enumerable: false
});
});
return obj;
}
function getUtilities(el) {
let [utilities, cleanup2] = getElementBoundUtilities(el);
let utils = { interceptor, ...utilities };
onElRemoved(el, cleanup2);
return utils;
}
// packages/alpinejs/src/utils/error.js
function tryCatch(el, expression, callback, ...args) {
try {
return callback(...args);
} catch (e) {
handleError(e, el, expression);
}
}
function handleError(error2, el, expression = void 0) {
error2 = Object.assign(
error2 ?? { message: "No error message given." },
{ el, expression }
);
console.warn(`Alpine Expression Error: ${error2.message}
${expression ? 'Expression: "' + expression + '"\n\n' : ""}`, el);
setTimeout(() => {
throw error2;
}, 0);
}
// packages/alpinejs/src/evaluator.js
var shouldAutoEvaluateFunctions = true;
function dontAutoEvaluateFunctions(callback) {
let cache = shouldAutoEvaluateFunctions;
shouldAutoEvaluateFunctions = false;
let result = callback();
shouldAutoEvaluateFunctions = cache;
return result;
}
function evaluate(el, expression, extras = {}) {
let result;
evaluateLater(el, expression)((value) => result = value, extras);
return result;
}
function evaluateLater(...args) {
return theEvaluatorFunction(...args);
}
var theEvaluatorFunction = normalEvaluator;
function setEvaluator(newEvaluator) {
theEvaluatorFunction = newEvaluator;
}
function normalEvaluator(el, expression) {
let overriddenMagics = {};
injectMagics(overriddenMagics, el);
let dataStack = [overriddenMagics, ...closestDataStack(el)];
let evaluator = typeof expression === "function" ? generateEvaluatorFromFunction(dataStack, expression) : generateEvaluatorFromString(dataStack, expression, el);
return tryCatch.bind(null, el, expression, evaluator);
}
function generateEvaluatorFromFunction(dataStack, func) {
return (receiver = () => {
}, { scope: scope2 = {}, params = [] } = {}) => {
let result = func.apply(mergeProxies([scope2, ...dataStack]), params);
runIfTypeOfFunction(receiver, result);
};
}
var evaluatorMemo = {};
function generateFunctionFromString(expression, el) {
if (evaluatorMemo[expression]) {
return evaluatorMemo[expression];
}
let AsyncFunction = Object.getPrototypeOf(async function() {
}).constructor;
let rightSideSafeExpression = /^[\n\s]*if.*\(.*\)/.test(expression.trim()) || /^(let|const)\s/.test(expression.trim()) ? `(async()=>{ ${expression} })()` : expression;
const safeAsyncFunction = () => {
try {
let func2 = new AsyncFunction(
["__self", "scope"],
`with (scope) { __self.result = ${rightSideSafeExpression} }; __self.finished = true; return __self.result;`
);
Object.defineProperty(func2, "name", {
value: `[Alpine] ${expression}`
});
return func2;
} catch (error2) {
handleError(error2, el, expression);
return Promise.resolve();
}
};
let func = safeAsyncFunction();
evaluatorMemo[expression] = func;
return func;
}
function generateEvaluatorFromString(dataStack, expression, el) {
let func = generateFunctionFromString(expression, el);
return (receiver = () => {
}, { scope: scope2 = {}, params = [] } = {}) => {
func.result = void 0;
func.finished = false;
let completeScope = mergeProxies([scope2, ...dataStack]);
if (typeof func === "function") {
let promise = func(func, completeScope).catch((error2) => handleError(error2, el, expression));
if (func.finished) {
runIfTypeOfFunction(receiver, func.result, completeScope, params, el);
func.result = void 0;
} else {
promise.then((result) => {
runIfTypeOfFunction(receiver, result, completeScope, params, el);
}).catch((error2) => handleError(error2, el, expression)).finally(() => func.result = void 0);
}
}
};
}
function runIfTypeOfFunction(receiver, value, scope2, params, el) {
if (shouldAutoEvaluateFunctions && typeof value === "function") {
let result = value.apply(scope2, params);
if (result instanceof Promise) {
result.then((i) => runIfTypeOfFunction(receiver, i, scope2, params)).catch((error2) => handleError(error2, el, value));
} else {
receiver(result);
}
} else if (typeof value === "object" && value instanceof Promise) {
value.then((i) => receiver(i));
} else {
receiver(value);
}
}
// packages/alpinejs/src/directives.js
var prefixAsString = "x-";
function prefix(subject = "") {
return prefixAsString + subject;
}
function setPrefix(newPrefix) {
prefixAsString = newPrefix;
}
var directiveHandlers = {};
function directive(name, callback) {
directiveHandlers[name] = callback;
return {
before(directive2) {
if (!directiveHandlers[directive2]) {
console.warn(String.raw`Cannot find directive \`${directive2}\`. \`${name}\` will use the default order of execution`);
return;
}
const pos = directiveOrder.indexOf(directive2);
directiveOrder.splice(pos >= 0 ? pos : directiveOrder.indexOf("DEFAULT"), 0, name);
}
};
}
function directiveExists(name) {
return Object.keys(directiveHandlers).includes(name);
}
function directives(el, attributes, originalAttributeOverride) {
attributes = Array.from(attributes);
if (el._x_virtualDirectives) {
let vAttributes = Object.entries(el._x_virtualDirectives).map(([name, value]) => ({ name, value }));
let staticAttributes = attributesOnly(vAttributes);
vAttributes = vAttributes.map((attribute) => {
if (staticAttributes.find((attr) => attr.name === attribute.name)) {
return {
name: `x-bind:${attribute.name}`,
value: `"${attribute.value}"`
};
}
return attribute;
});
attributes = attributes.concat(vAttributes);
}
let transformedAttributeMap = {};
let directives2 = attributes.map(toTransformedAttributes((newName, oldName) => transformedAttributeMap[newName] = oldName)).filter(outNonAlpineAttributes).map(toParsedDirectives(transformedAttributeMap, originalAttributeOverride)).sort(byPriority);
return directives2.map((directive2) => {
return getDirectiveHandler(el, directive2);
});
}
function attributesOnly(attributes) {
return Array.from(attributes).map(toTransformedAttributes()).filter((attr) => !outNonAlpineAttributes(attr));
}
var isDeferringHandlers = false;
var directiveHandlerStacks = /* @__PURE__ */ new Map();
var currentHandlerStackKey = Symbol();
function deferHandlingDirectives(callback) {
isDeferringHandlers = true;
let key = Symbol();
currentHandlerStackKey = key;
directiveHandlerStacks.set(key, []);
let flushHandlers = () => {
while (directiveHandlerStacks.get(key).length)
directiveHandlerStacks.get(key).shift()();
directiveHandlerStacks.delete(key);
};
let stopDeferring = () => {
isDeferringHandlers = false;
flushHandlers();
};
callback(flushHandlers);
stopDeferring();
}
function getElementBoundUtilities(el) {
let cleanups = [];
let cleanup2 = (callback) => cleanups.push(callback);
let [effect3, cleanupEffect] = elementBoundEffect(el);
cleanups.push(cleanupEffect);
let utilities = {
Alpine: alpine_default,
effect: effect3,
cleanup: cleanup2,
evaluateLater: evaluateLater.bind(evaluateLater, el),
evaluate: evaluate.bind(evaluate, el)
};
let doCleanup = () => cleanups.forEach((i) => i());
return [utilities, doCleanup];
}
function getDirectiveHandler(el, directive2) {
let noop = () => {
};
let handler4 = directiveHandlers[directive2.type] || noop;
let [utilities, cleanup2] = getElementBoundUtilities(el);
onAttributeRemoved(el, directive2.original, cleanup2);
let fullHandler = () => {
if (el._x_ignore || el._x_ignoreSelf)
return;
handler4.inline && handler4.inline(el, directive2, utilities);
handler4 = handler4.bind(handler4, el, directive2, utilities);
isDeferringHandlers ? directiveHandlerStacks.get(currentHandlerStackKey).push(handler4) : handler4();
};
fullHandler.runCleanups = cleanup2;
return fullHandler;
}
var startingWith = (subject, replacement) => ({ name, value }) => {
if (name.startsWith(subject))
name = name.replace(subject, replacement);
return { name, value };
};
var into = (i) => i;
function toTransformedAttributes(callback = () => {
}) {
return ({ name, value }) => {
let { name: newName, value: newValue } = attributeTransformers.reduce((carry, transform) => {
return transform(carry);
}, { name, value });
if (newName !== name)
callback(newName, name);
return { name: newName, value: newValue };
};
}
var attributeTransformers = [];
function mapAttributes(callback) {
attributeTransformers.push(callback);
}
function outNonAlpineAttributes({ name }) {
return alpineAttributeRegex().test(name);
}
var alpineAttributeRegex = () => new RegExp(`^${prefixAsString}([^:^.]+)\\b`);
function toParsedDirectives(transformedAttributeMap, originalAttributeOverride) {
return ({ name, value }) => {
let typeMatch = name.match(alpineAttributeRegex());
let valueMatch = name.match(/:([a-zA-Z0-9\-_:]+)/);
let modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || [];
let original = originalAttributeOverride || transformedAttributeMap[name] || name;
return {
type: typeMatch ? typeMatch[1] : null,
value: valueMatch ? valueMatch[1] : null,
modifiers: modifiers.map((i) => i.replace(".", "")),
expression: value,
original
};
};
}
var DEFAULT = "DEFAULT";
var directiveOrder = [
"ignore",
"ref",
"data",
"id",
"anchor",
"bind",
"init",
"for",
"model",
"modelable",
"transition",
"show",
"if",
DEFAULT,
"teleport"
];
function byPriority(a, b) {
let typeA = directiveOrder.indexOf(a.type) === -1 ? DEFAULT : a.type;
let typeB = directiveOrder.indexOf(b.type) === -1 ? DEFAULT : b.type;
return directiveOrder.indexOf(typeA) - directiveOrder.indexOf(typeB);
}
// packages/alpinejs/src/utils/dispatch.js
function dispatch(el, name, detail = {}) {
el.dispatchEvent(
new CustomEvent(name, {
detail,
bubbles: true,
// Allows events to pass the shadow DOM barrier.
composed: true,
cancelable: true
})
);
}
// packages/alpinejs/src/utils/walk.js
function walk(el, callback) {
if (typeof ShadowRoot === "function" && el instanceof ShadowRoot) {
Array.from(el.children).forEach((el2) => walk(el2, callback));
return;
}
let skip = false;
callback(el, () => skip = true);
if (skip)
return;
let node = el.firstElementChild;
while (node) {
walk(node, callback, false);
node = node.nextElementSibling;
}
}
// packages/alpinejs/src/utils/warn.js
function warn(message, ...args) {
console.warn(`Alpine Warning: ${message}`, ...args);
}
// packages/alpinejs/src/lifecycle.js
var started = false;
function start() {
if (started)
warn("Alpine has already been initialized on this page. Calling Alpine.start() more than once can cause problems.");
started = true;
if (!document.body)
warn("Unable to initialize. Trying to load Alpine before `` is available. Did you forget to add `defer` in Alpine's `