66 lines
2 KiB
JavaScript
66 lines
2 KiB
JavaScript
|
|
import { useScript as useScript$1 } from 'unhead/scripts';
|
||
|
|
import { getCurrentInstance, onMounted, isRef, watch, onScopeDispose, ref } from 'vue';
|
||
|
|
import { i as injectHead } from './vue.Cd6dkybA.mjs';
|
||
|
|
|
||
|
|
function registerVueScopeHandlers(script, scope) {
|
||
|
|
if (!scope) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
const bind = (base) => (cb) => {
|
||
|
|
const off = base(cb) ?? (() => {
|
||
|
|
});
|
||
|
|
onScopeDispose(off);
|
||
|
|
return off;
|
||
|
|
};
|
||
|
|
const baseOnLoaded = script.onLoaded;
|
||
|
|
const baseOnError = script.onError;
|
||
|
|
script.onLoaded = bind(baseOnLoaded);
|
||
|
|
script.onError = bind(baseOnError);
|
||
|
|
const triggerAbortController = script._triggerAbortController;
|
||
|
|
onScopeDispose(() => {
|
||
|
|
triggerAbortController?.abort();
|
||
|
|
});
|
||
|
|
}
|
||
|
|
function useScript(_input, _options) {
|
||
|
|
const input = typeof _input === "string" ? { src: _input } : _input;
|
||
|
|
const options = _options || {};
|
||
|
|
const head = options?.head || injectHead();
|
||
|
|
options.head = head;
|
||
|
|
const scope = getCurrentInstance();
|
||
|
|
options.eventContext = scope;
|
||
|
|
if (scope && typeof options.trigger === "undefined") {
|
||
|
|
options.trigger = onMounted;
|
||
|
|
} else if (isRef(options.trigger) || typeof options.trigger === "function" && options.trigger.length === 0) {
|
||
|
|
const trigger = options.trigger;
|
||
|
|
let off;
|
||
|
|
options.trigger = new Promise((resolve) => {
|
||
|
|
off = watch(trigger, (val) => {
|
||
|
|
if (val) {
|
||
|
|
resolve(true);
|
||
|
|
}
|
||
|
|
}, {
|
||
|
|
immediate: true
|
||
|
|
});
|
||
|
|
onScopeDispose(() => resolve(false), true);
|
||
|
|
}).then((val) => {
|
||
|
|
off?.();
|
||
|
|
return val;
|
||
|
|
});
|
||
|
|
}
|
||
|
|
head._scriptStatusWatcher = head._scriptStatusWatcher || head.hooks.hook("script:updated", ({ script: s }) => {
|
||
|
|
if (s._statusRef) {
|
||
|
|
s._statusRef.value = s.status;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
const script = useScript$1(head, input, options);
|
||
|
|
script._statusRef = script._statusRef || ref(script.status);
|
||
|
|
registerVueScopeHandlers(script, scope);
|
||
|
|
return new Proxy(script, {
|
||
|
|
get(_, key, a) {
|
||
|
|
return Reflect.get(_, key === "status" ? "_statusRef" : key, a);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
export { useScript as u };
|