mirror of https://github.com/msgbyte/tailchat
feat: add tianji script environment
parent
d45793496c
commit
125df13976
@ -0,0 +1,27 @@
|
||||
import { DependencyList, useLayoutEffect, useRef } from 'react';
|
||||
import { useEvent } from './useEvent';
|
||||
|
||||
/**
|
||||
* Call once on data ready(validator return true)
|
||||
*/
|
||||
export function useDataReady(
|
||||
validator: () => boolean,
|
||||
cb: () => void,
|
||||
deps?: DependencyList
|
||||
) {
|
||||
const isReadyRef = useRef(false);
|
||||
|
||||
const _validator = useEvent(validator);
|
||||
const _callback = useEvent(cb);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (isReadyRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_validator() === true) {
|
||||
_callback();
|
||||
isReadyRef.current = true;
|
||||
}
|
||||
}, deps);
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
import { useDataReady, useGlobalConfigStore } from 'tailchat-shared';
|
||||
|
||||
export function useInjectTianjiScript() {
|
||||
const { tianji } = useGlobalConfigStore();
|
||||
|
||||
useDataReady(
|
||||
() =>
|
||||
typeof tianji.scriptUrl === 'string' &&
|
||||
typeof tianji.websiteId === 'string' &&
|
||||
tianji.websiteId.length > 0,
|
||||
() => {
|
||||
if (!tianji.scriptUrl) {
|
||||
console.error(
|
||||
'Cannot inject Tianji script because of scriptUrl not cool:',
|
||||
tianji.scriptUrl
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const el = document.createElement('script');
|
||||
el.src = tianji.scriptUrl;
|
||||
el.setAttribute('data-website-id', String(tianji.websiteId));
|
||||
el.setAttribute('async', 'async');
|
||||
el.setAttribute('defer', 'defer');
|
||||
document.head.append(el);
|
||||
}
|
||||
);
|
||||
}
|
Loading…
Reference in New Issue