Skip to content

Made some modifications #9

@kctang

Description

@kctang

Hi,

Thanks for this.

I made some changes for my TypeScript based application as the provided TS definitions was not good for me.

The only minor issue I have is the promise will never resolve or reject if user clicks cancel when the file input dialog is opened - potential memory leak if done repeatedly.

Sharing here FWIW:

// modified based on alnorris/file-dialog
// https://github.com/alnorris/file-dialog/blob/master/file-dialog.d.ts
// - removed support for callback
// - improved TypeScript type definitions
// - directly click() on input
// - do not add input to DOM (seems to work in Chrome - no plans to support MSIE)
export const fileDialog = (options?: { multiple?: boolean, accept?: string }) => {
  const input = document.createElement('input')

  // Set config
  if (options) {
    if (options.multiple) {
      input.setAttribute('multiple', '')
    }
    if (options.accept !== undefined) {
      input.setAttribute('accept', options.accept)
    }
  }

  input.setAttribute('type', 'file')

  // Return promise
  return new Promise<FileList | null>(resolve => {
    input.addEventListener('change', () => resolve(input.files))
    input.click()
  })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions