Skip to content

Commit

Permalink
feat(chooseFile): image 默认为 image/*;支持 afterElementReady 回调
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 28, 2024
1 parent d73d61c commit c1eade5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/utils/__snapshots__/chooseFile.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

exports[`chooseFile 多选其他 1`] = `".doc,.docx__true.txt"`;

exports[`chooseFile 多选图片 1`] = `".jpg,.jpeg,.png,.gif__true.txt"`;
exports[`chooseFile 多选图片 1`] = `"image/*__true.txt"`;

exports[`chooseFile 选择其他 1`] = `".doc,.docx__false.txt"`;

exports[`chooseFile 选择图片 1`] = `".jpg,.jpeg,.png,.gif__false.txt"`;
exports[`chooseFile 选择图片 1`] = `"image/*__false.txt"`;
43 changes: 39 additions & 4 deletions src/utils/chooseFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,52 @@ import { LiteralUnion } from '../types'
import { bindEvent } from './bindEvent'
import { wait } from './wait'

export interface ChooseFileOptions {
/**
* 是否多选
*
* @default false
*/
multiple?: boolean

/**
* 元素准备好后的回调
*/
afterElementReady?: (payload: { el: HTMLInputElement }) => any
}

/**
* 选择文件。
*
* @param accept 接受的文件类型
* @param accept 接受的文件类型,其中默认的 `image` 表示 `image/*`
* @param multiple 是否多选
* @returns 返回选中的文件列表
*/
export function chooseFile(
accept: LiteralUnion<'image', string>,
multiple = false,
multiple?: boolean,
): Promise<ReadonlyArray<File>>
/**
* 选择文件。
*
* @param accept 接受的文件类型,其中默认的 `image` 表示 `image/*`
* @param options 选项
* @returns 返回选中的文件列表
*/
export function chooseFile(
accept: LiteralUnion<'image', string>,
options?: ChooseFileOptions,
): Promise<ReadonlyArray<File>>
export function chooseFile(
accept: LiteralUnion<'image', string>,
multipleOrOptions?: boolean | ChooseFileOptions,
): Promise<ReadonlyArray<File>> {
return new Promise(resolve => {
const options: ChooseFileOptions =
typeof multipleOrOptions === 'boolean'
? { multiple: multipleOrOptions }
: multipleOrOptions || {}

let input = document.createElement('input')
input.style.all = 'unset'
input.style.position = 'fixed'
Expand All @@ -27,8 +61,9 @@ export function chooseFile(
input.style.msUserSelect = 'text'
input.style.userSelect = 'text'
input.type = 'file'
input.accept = accept === 'image' ? '.jpg,.jpeg,.png,.gif' : accept
input.multiple = multiple
input.accept = accept === 'image' ? 'image/*' : accept
input.multiple = !!options.multiple
options.afterElementReady?.({ el: input })
document.body.appendChild(input)

const handleChange = () => {
Expand Down

0 comments on commit c1eade5

Please sign in to comment.