Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/__tests__/io.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { pickJsonFile } from '../io'

describe('pickJsonFile', () => {
const originalCreateElement = document.createElement.bind(document)
let createdInput: HTMLInputElement

beforeEach(() => {
vi.spyOn(document, 'createElement').mockImplementation((tag: string) => {
const el = originalCreateElement(tag)
if (tag === 'input') {
createdInput = el as HTMLInputElement
vi.spyOn(createdInput, 'click').mockImplementation(() => {})
}
return el
})
})

afterEach(() => {
vi.restoreAllMocks()
})

it('resolves with file contents when a file is selected', async () => {
const promise = pickJsonFile()

const file = new File(['{"hello":"world"}'], 'test.json', {
type: 'application/json',
})
Object.defineProperty(createdInput, 'files', {
value: [file],
configurable: true,
})
createdInput.dispatchEvent(new Event('change'))

await expect(promise).resolves.toBe('{"hello":"world"}')
})

it('resolves with null when the user cancels the file picker', async () => {
const promise = pickJsonFile()

createdInput.dispatchEvent(new Event('cancel'))

await expect(promise).resolves.toBeNull()
})
})
1 change: 1 addition & 0 deletions src/hooks/useShareImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export function useShareImport({ getFramework, navigate, addRaw, replace, addImp
(onImported: (fw: Framework) => void) => {
pickJsonFile()
.then((text) => {
if (text === null) return
const fw = JSON.parse(text)
if (fw.name && fw.quadrants && fw.quadrants.length === 4) {
const imported: Framework = {
Expand Down
3 changes: 2 additions & 1 deletion src/io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function downloadJson(filename: string, data: string): void {
URL.revokeObjectURL(url)
}

export function pickJsonFile(): Promise<string> {
export function pickJsonFile(): Promise<string | null> {
return new Promise((resolve, reject) => {
const input = document.createElement('input')
input.type = 'file'
Expand All @@ -24,6 +24,7 @@ export function pickJsonFile(): Promise<string> {
reader.onerror = () => reject(new Error('Failed to read file'))
reader.readAsText(file)
}
input.oncancel = () => resolve(null)
input.click()
})
}