File size: 5,957 Bytes
0070fce |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
import { t } from '@/i18n'
import { message } from 'ant-design-vue'
import { reactive } from 'vue'
import { Modal } from 'ant-design-vue'
import { FetchQueue, idKey, typedEventEmitter, type UniqueId} from 'vue3-ts-util'
import { useLocalStorage } from '@vueuse/core'
export * from './file'
import { prefix } from './const'
export const parentWindow = () => {
return parent.window as any as Window & {
switch_to_img2img(): void
switch_to_txt2img(): void
}
}
/**
* 勿删
* @returns
*/
export function gradioApp(): Window & Document {
try {
return (parent.window as any).gradioApp()
} catch (error) {
//
}
const elems = parent.document.getElementsByTagName('gradio-app')
const gradioShadowRoot = elems.length == 0 ? null : elems[0].shadowRoot
return (gradioShadowRoot ? gradioShadowRoot : document) as any
}
export const getTabIdxInSDWebui = () => {
const tabList = gradioApp().querySelectorAll('#tabs > .tabitem[id^=tab_]')
return Array.from(tabList).findIndex((v) => v.id.includes('infinite-image-browsing'))
}
export const switch2IIB = () => {
try {
gradioApp().querySelector('#tabs')!.querySelectorAll('button')[getTabIdxInSDWebui()].click()
} catch (error) {
console.error(error)
}
}
export const asyncCheck = async <T>(getter: () => T, checkSize = 100, timeout = 1000) => {
return new Promise<T>((x) => {
const check = (num = 0) => {
const target = getter()
if (target !== undefined && target !== null) {
x(target)
} else if (num > timeout / checkSize) {
// 超时
x(target)
} else {
setTimeout(() => check(++num), checkSize)
}
}
check()
})
}
export const key = (obj: UniqueId) => obj[idKey]
export type Dict<T = any> = Record<string, T>
/**
* 推导比loadsh好
* @param v
* @param keys
*/
export const pick = <T extends Dict, keys extends Array<keyof T>>(v: T, ...keys: keys) => {
return keys.reduce((p, c) => {
p[c] = v?.[c]
return p
}, {} as Pick<T, keys[number]>)
}
/**
* 获取一个异步函数的返回类型,
*
* ReturnTypeAsync\<typeof fn\>
*/
export type ReturnTypeAsync<T extends (...arg: any) => Promise<any>> = Awaited<ReturnType<T>>
export const createReactiveQueue = () => reactive(new FetchQueue(-1, 0, -1, 'throw'))
export const copy2clipboardI18n = async (text: string, msg?: string) => {
try {
if (navigator.clipboard) {
await navigator.clipboard.writeText(text)
} else {
const input = document.createElement('input')
input.value = text
document.body.appendChild(input)
input.select()
document.execCommand('copy')
document.body.removeChild(input)
}
message.success(msg ?? t('copied'))
} catch (error) {
message.error('copy failed. maybe it\'s non-secure environment')
}
}
export const { useEventListen: useGlobalEventListen, eventEmitter: globalEvents } =
typedEventEmitter<{
returnToIIB(): void
updateGlobalSetting(): void
searchIndexExpired(): void
closeTabPane(tabIdx: number, key: string): void
updateGlobalSettingDone(): void
}>()
type AsyncFunction<T> = (...args: any[]) => Promise<T>
export function makeAsyncFunctionSingle<T>(fn: AsyncFunction<T>): AsyncFunction<T> {
let promise: Promise<T> | null = null
let isExecuting = false
return async function (this: any, ...args: any[]): Promise<T> {
if (isExecuting) {
// 如果当前有其他调用正在执行,直接返回上一个 Promise 对象
return promise as Promise<T>
}
isExecuting = true
try {
// 执行异步函数并等待结果
promise = fn.apply(this, args)
const result = await promise
return result
} finally {
isExecuting = false
}
}
}
export function removeQueryParams(keys: string[]): string {
// 获取当前 URL
const url: string = parent.location.href
// 解析 URL,获取查询参数部分
const searchParams: URLSearchParams = new URLSearchParams(parent.location.search)
// 删除指定的键
keys.forEach((key: string) => {
searchParams.delete(key)
})
// 构建新的 URL
const newUrl: string = `${url.split('?')[0]}${
searchParams.size ? '?' : ''
}${searchParams.toString()}`
// 使用 pushState() 方法将新 URL 添加到浏览器历史记录中
parent.history.pushState(null, '', newUrl)
// 返回新的 URL
return newUrl
}
export const createImage = (src: string) => {
return new Promise<HTMLImageElement>((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = (err) => reject(err)
img.src = src
})
}
export const safeJsonParse = <T>(str: string) => {
try {
return JSON.parse(str) as T
} catch (error) {
return null
}
}
export const formatDuration = (duration: number) => {
if (duration >= 3600) {
const hour = Math.floor(duration / 3600);
const min = Math.floor((duration % 3600) / 60);
const sec = duration % 60;
return `${hour}:${min.toString().padStart(2, '0')}:${sec.toFixed(0).padStart(2, '0')}`;
} else {
const min = Math.floor(duration / 60);
const sec = duration % 60;
return `${min}:${sec.toFixed(0).padStart(2, '0')}`;
}
}
export function unescapeHtml (string: string) {
return `${string}`
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"',)
.replace(/'/g, '\'')
}
export const actionConfirm = <T extends (...args: any[]) => void> (fn: T, msg ?: string) => {
if (!msg) {
msg = t('confirmThisAction')
}
return (...args: Parameters<T>) => Modal.confirm({ content: msg, onOk: () => fn(...args) })
}
export const settingSyncKey = prefix + 'sync'
export const isSync = () => {
const r = localStorage.getItem(settingSyncKey)
return r === 'true' || r === null
}
export const useSettingSync = () => {
const sync = useLocalStorage(settingSyncKey, true)
return sync
} |