71 lines
2.0 KiB
JavaScript
71 lines
2.0 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.Bm-NbY4b.mjs';
|
|
|
|
function registerVueScopeHandlers(script, scope) {
|
|
if (!scope) {
|
|
return;
|
|
}
|
|
const _registerCb = (key, cb) => {
|
|
if (!script._cbs[key]) {
|
|
cb(script.instance);
|
|
return () => {
|
|
};
|
|
}
|
|
let i = script._cbs[key].push(cb);
|
|
const destroy = () => {
|
|
if (i) {
|
|
script._cbs[key]?.splice(i - 1, 1);
|
|
i = null;
|
|
}
|
|
};
|
|
onScopeDispose(destroy);
|
|
return destroy;
|
|
};
|
|
script.onLoaded = (cb) => _registerCb("loaded", cb);
|
|
script.onError = (cb) => _registerCb("error", cb);
|
|
onScopeDispose(() => {
|
|
script._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)) {
|
|
const refTrigger = options.trigger;
|
|
let off;
|
|
options.trigger = new Promise((resolve) => {
|
|
off = watch(refTrigger, (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 }) => {
|
|
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 };
|