2023-05-16 10:30:26 +00:00
|
|
|
/*
|
|
|
|
* Ported from useStyleTag in @vueuse/core
|
|
|
|
* https://github.com/vueuse
|
|
|
|
*/
|
|
|
|
import { DomHandler } from 'primevue/utils';
|
|
|
|
import { getCurrentInstance, nextTick, onMounted, readonly, ref, watch } from 'vue';
|
|
|
|
|
|
|
|
function tryOnMounted(fn, sync = true) {
|
|
|
|
if (getCurrentInstance()) onMounted(fn);
|
|
|
|
else if (sync) fn();
|
|
|
|
else nextTick(fn);
|
|
|
|
}
|
|
|
|
|
|
|
|
let _id = 0;
|
|
|
|
|
|
|
|
export function useStyle(css, options = {}) {
|
|
|
|
const isLoaded = ref(false);
|
|
|
|
|
|
|
|
const defaultDocument = DomHandler.isClient() ? window.document : undefined;
|
2023-07-03 22:20:35 +00:00
|
|
|
const { document = defaultDocument, immediate = true, manual = false, name = `style_${++_id}`, id = undefined, media = undefined } = options;
|
2023-05-16 10:30:26 +00:00
|
|
|
|
|
|
|
const cssRef = ref(css);
|
|
|
|
|
|
|
|
let stop = () => {};
|
|
|
|
|
|
|
|
const load = () => {
|
|
|
|
if (!document) return;
|
|
|
|
|
2023-07-03 22:20:35 +00:00
|
|
|
const el = document.querySelector(`style[data-primevue-style-id="${name}"]`) || document.getElementById(id) || document.createElement('style');
|
2023-05-16 10:30:26 +00:00
|
|
|
|
|
|
|
if (!el.isConnected) {
|
|
|
|
el.type = 'text/css';
|
2023-07-03 22:20:35 +00:00
|
|
|
id && (el.id = id);
|
|
|
|
media && (el.media = media);
|
2023-05-16 10:30:26 +00:00
|
|
|
document.head.appendChild(el);
|
2023-07-03 22:20:35 +00:00
|
|
|
name && el.setAttribute('data-primevue-style-id', name);
|
2023-05-16 10:30:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (isLoaded.value) return;
|
|
|
|
|
|
|
|
stop = watch(
|
|
|
|
cssRef,
|
|
|
|
(value) => {
|
|
|
|
el.textContent = value;
|
|
|
|
},
|
|
|
|
{ immediate: true }
|
|
|
|
);
|
|
|
|
|
|
|
|
isLoaded.value = true;
|
|
|
|
};
|
|
|
|
|
|
|
|
const unload = () => {
|
|
|
|
if (!document || !isLoaded.value) return;
|
|
|
|
stop();
|
|
|
|
document.head.removeChild(document.getElementById(id));
|
|
|
|
isLoaded.value = false;
|
|
|
|
};
|
|
|
|
|
|
|
|
if (immediate && !manual) tryOnMounted(load);
|
|
|
|
|
|
|
|
/*if (!manual)
|
|
|
|
tryOnScopeDispose(unload)*/
|
|
|
|
|
|
|
|
return {
|
|
|
|
id,
|
|
|
|
css: cssRef,
|
|
|
|
unload,
|
|
|
|
load,
|
|
|
|
isLoaded: readonly(isLoaded)
|
|
|
|
};
|
|
|
|
}
|