Skip to content

Commit

Permalink
馃悶 fix: some webui exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhUyU1997 committed Apr 10, 2023
1 parent 88819a8 commit 55a4156
Show file tree
Hide file tree
Showing 4 changed files with 138 additions and 10 deletions.
4 changes: 3 additions & 1 deletion src/components/PopupOver/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ function GetCameraParamControlor(editor: BodyEditor) {
name,
range,
getValue() {
return editor[paramName as keyof typeof CameraParamsInit]
const value = editor[paramName as keyof typeof CameraParamsInit]
// webui exception in launch
return isNaN(value) ? range[0] : value
},
onChange(value: number) {
editor[paramName as keyof typeof CameraParamsInit] = value
Expand Down
6 changes: 3 additions & 3 deletions src/environments/online/helper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getImage } from '../../utils/image'
import { uploadImage } from '../../utils/transfer'
import { CopyTextToClipboard, uploadImage } from '../../utils/transfer'
import { DetectPosefromImage } from '../../utils/detect'

import { BodyControlor } from '../../body'
Expand Down Expand Up @@ -76,7 +76,7 @@ export class Helper {
}
try {
const data = new BodyControlor(body).Get18keyPointsData()
await navigator.clipboard.writeText(JSON.stringify(data, null, 4))
await CopyTextToClipboard(JSON.stringify(data, null, 4))
ShowToast({ title: i18n.t('Copied to Clipboard') })
} catch (error) {
Oops(error)
Expand All @@ -92,7 +92,7 @@ export class Helper {
)
const url_base = location.href.replace(/#$/, '')
const url = `${url_base}#${d}`
await navigator.clipboard.writeText(url)
await CopyTextToClipboard(url)
ShowToast({ title: i18n.t('Copied to Clipboard') })
} catch (error) {
Oops(error)
Expand Down
136 changes: 131 additions & 5 deletions src/utils/transfer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { fileOpen, fileSave } from 'browser-fs-access'
import {
fileOpen,
fileSave,
FileWithHandle,
FirstFileOpenOptions,
} from 'browser-fs-access'

export function download(href: string, title: string) {
const a = document.createElement('a')
Expand All @@ -14,10 +19,85 @@ export function downloadJson(data: string, fileName: string) {
URL.revokeObjectURL(href)
}

async function fileOpenLegacy<M extends boolean | undefined = false>(
_options: FirstFileOpenOptions<M> = {}
): Promise<FileWithHandle | FileWithHandle[]> {
let options: FirstFileOpenOptions<M>[]
if (!Array.isArray(_options)) {
options = [_options]
} else options = _options
return new Promise((resolve, reject) => {
const input = document.createElement('input') as HTMLInputElement
input.type = 'file'
const accept = [
...options.map((option) => option.mimeTypes || []),
...options.map((option) => option.extensions || []),
].join()
input.multiple = options[0].multiple || false
// Empty string allows everything.
input.accept = accept || ''
// Append to the DOM, else Safari on iOS won't fire the `change` event
// reliably.
input.style.display = 'none'
document.body.append(input)

const _reject = () => cleanupListenersAndMaybeReject?.(reject)
const _resolve = (value: FileWithHandle | FileWithHandle[]) => {
if (typeof cleanupListenersAndMaybeReject === 'function') {
cleanupListenersAndMaybeReject()
}
resolve(value)
}
// ToDo: Remove this workaround once
// https://github.com/whatwg/html/issues/6376 is specified and supported.
const cleanupListenersAndMaybeReject =
options[0].legacySetup &&
options[0].legacySetup(_resolve, _reject, input)

const cancelDetector = () => {
window.removeEventListener('focus', cancelDetector)
input.remove()
}

input.addEventListener('click', () => {
window.addEventListener('focus', cancelDetector)
})

input.addEventListener('change', () => {
window.removeEventListener('focus', cancelDetector)
input.remove()

if (input.files)
_resolve(
input.multiple ? Array.from(input.files) : input.files[0]
)
else {
_reject()
}
})

if ('showPicker' in HTMLInputElement.prototype) {
input.showPicker()
} else {
input.click()
}
})
}

export async function uploadJson() {
try {
const file = await fileOpen({
const file = await fileOpenLegacy({
mimeTypes: ['application/json'],
legacySetup: (_, rejectionHandler) => {
const timeoutId = setTimeout(rejectionHandler, 10_000)
return (reject) => {
clearTimeout(timeoutId)
if (reject) {
console.error('reject')
reject('Failed to Open file')
}
}
},
})

return await new Promise<string>((resolve, reject) => {
Expand All @@ -29,7 +109,10 @@ export async function uploadJson() {
reader.onerror = function () {
reject(reader.error)
}
reader.readAsText(file)

if (Array.isArray(file) == false)
reader.readAsText(file as FileWithHandle)
else reject("Don't select multiple files")
})
} catch (error) {
console.log(error)
Expand All @@ -39,8 +122,18 @@ export async function uploadJson() {

export async function uploadImage() {
try {
const file = await fileOpen({
const file = await fileOpenLegacy({
mimeTypes: ['image/*'],
legacySetup: (_, rejectionHandler) => {
const timeoutId = setTimeout(rejectionHandler, 10_000)
return (reject) => {
clearTimeout(timeoutId)
console.log('reject')
if (reject) {
reject('Open file timeout')
}
}
},
})

return await new Promise<string>((resolve, reject) => {
Expand All @@ -52,10 +145,43 @@ export async function uploadImage() {
reader.onerror = function () {
reject(reader.error)
}
reader.readAsDataURL(file)

if (Array.isArray(file) == false)
reader.readAsDataURL(file as FileWithHandle)
else reject("Don't select multiple files")
})
} catch (error) {
console.log(error)
return null
}
}

export async function CopyTextToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text)
} catch (error) {
// https://github.com/sudodoki/copy-to-clipboard/blob/main/index.js
const input = document.createElement('input') as HTMLInputElement
input.type = 'text'
input.style.display = 'none'
input.value = text
input.ariaHidden = 'true'
// reset user styles for span element
input.style.all = 'unset'
// prevents scrolling to the end of the page
input.style.position = 'fixed'
input.style.top = '0'
input.style.clip = 'rect(0, 0, 0, 0)'

document.body.append(input)

input.select()
const successful = document.execCommand('copy')

input.remove()

if (!successful) {
throw new Error('copy command was unsuccessful')
}
}
}
2 changes: 1 addition & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const config: UserConfigFn = ({ command, mode, ssrBuild }) => {
base: mode === 'singlefile' ? './' : '/open-pose-editor/',
define: {
global: {},
__APP_VERSION__: JSON.stringify('0.1.14'),
__APP_VERSION__: JSON.stringify('0.1.15'),
__APP_BUILD_TIME__: Date.now(),
},
build: {
Expand Down

0 comments on commit 55a4156

Please sign in to comment.