/
index.ts
357 lines (315 loc) · 10.4 KB
/
index.ts
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import 'promise-polyfill/dist/polyfill'
import { EventEmitter } from 'eventemitter3'
import whenDomReady from 'when-dom-ready'
import insertCss from 'insert-css'
import elementClass from 'element-class'
import Penpal from 'penpal'
import registerDocumentContainsPolyfill from './document.contains.polyfill'
import FlatfileResults from './results'
import Meta from './obj.meta'
import RecordObject from './obj.record'
import CustomerObject from './obj.customer'
import LoadOptionsObject from './obj.load-options'
import IValidationResponse, { IDataHookRecord, IDataHookResponse } from './obj.validation-response'
registerDocumentContainsPolyfill()
export default class FlatfileImporter extends EventEmitter {
public static Promise = Promise
private static MOUNT_URL: string = 'https://portal-2.flatfile.io/?key=:key'
/**
* Promise that resolves when the handshake is completed between Flatfile.io and the adapter
*/
public $ready: Promise<any>
private apiKey: string
private options: object
private customer?: CustomerObject
private uuid: string
// @ts-ignore
private handshake: Penpal.IChildConnectionObject
private $resolver: (data: any) => any
private $rejecter: (err: any) => any
private $validatorCallback?: (row: { [key: string]: string | number }) => Array<IValidationResponse> | Promise<Array<IValidationResponse>>
private $networkErrorCallback?: (err: string) => void
private $recordHook?: (row: { [key: string]: string | number }, index: number, mode: string) => IDataHookResponse | Promise<IDataHookResponse>
private $fieldHooks: Array<{ field: string, cb: FieldHookCallback }> = []
constructor (apiKey: string, options: object, customer?: CustomerObject) {
super()
this.apiKey = apiKey
this.options = options
this.customer = customer
this.uuid = this.$generateUuid()
this.$ready = new FlatfileImporter.Promise((resolve, reject) => {
this.$resolver = resolve
this.$rejecter = reject
})
whenDomReady(() => {
this.initialize()
})
}
/**
* This will by default always be `https://www.flatfile.io/importer/:key` unless you are
* an enterprise customer that is self-hosting the application. In which case, this
* will be the URL of your enterprise installd Flatfile importer index page
*/
public static setMountUrl (url: string): void {
this.MOUNT_URL = url
}
/**
* This allows you to opt into or out of specific versions of the Flatfile SDK
*/
public static setVersion (version: 1 | 2): void {
switch (version) {
case 1:
this.MOUNT_URL = 'https://kiosk-lite.flatfile.io/?key=:key'
break
case 2:
this.MOUNT_URL = 'https://portal-2.flatfile.io/?key=:key'
break
default:
throw new Error(`${version} is not a valid version`)
}
}
/**
* Call open() to activate the importer overlay dialog.
*/
open (options = {}): void {
options = {
...options,
hasRecordHook: !!this.$recordHook,
fieldHooks: this.$fieldHooks.map(v => v.field),
endUser: this.customer
}
this.$ready.then((child) => {
elementClass(document.body).add('flatfile-active')
let el = document.getElementById(`flatfile-${this.uuid}`)
if (el) {
el.style.display = 'block'
}
child.open(options)
})
}
/**
* Use load() when you want a promise returned. This is necessary if you want to use
* async/await for an es6 implementation
* @deprecated
*/
load (): Promise<Array<Object>> {
return new FlatfileImporter.Promise((resolve, reject) => {
this.open()
const cleanup = () => {
this.removeListener('close', loadRejectHandler)
this.removeListener('complete', loadResolveHandler)
}
function loadResolveHandler (rows: Array<Object>) {
resolve(rows)
cleanup()
}
function loadRejectHandler (err) {
reject(err)
cleanup()
}
this.on('close', loadRejectHandler)
this.on('complete', loadResolveHandler)
})
}
/**
* Use requestDataFromUser() when you want a promise returned. This is necessary if you want to use
* async/await for an es6 implementation
*/
requestDataFromUser (options: LoadOptionsObject = {}): Promise<FlatfileResults> {
this.open({...options, inChunks: options.inChunks || null, expectsExpandedResults: true})
return this.responsePromise()
}
/**
* This will display a progress indicator inside the importer if you anticipate that handling
* the output of the importer may take some time.
*/
displayLoader (msg?: string): void {
this.$ready.then((child) => {
child.displayLoader(msg)
})
}
/**
* This will display a dialog inside of the importer with an error icon and the message you
* pass. The user will be able to acknowledge the error and be returned to the import data
* spreadsheet to ideally fix any issues or attempt submitting again.
* @deprecated
*/
displayError (msg: string): void {
this.$ready.then((child) => {
child.displayError(msg)
})
}
/**
* This will display a dialog inside of the importer with an error icon and the message you
* pass. The user will be able to acknowledge the error and be returned to the import data
* spreadsheet to ideally fix any issues or attempt submitting again.
*/
requestCorrectionsFromUser (msg): Promise<FlatfileResults> {
this.$ready.then((child) => {
child.displayError(msg)
})
return this.responsePromise()
}
/**
* This will display a dialog inside of the importer with a success icon and the message you
* pass.
*/
displaySuccess (msg: string): void {
this.$ready.then((child) => {
child.displaySuccess(msg)
})
}
/**
* This will fetch the data from the importer
*/
getMeta (): object {
return new Promise((resolve, reject) => {
this.$ready.then((child) => {
child.getMeta()
.then(resolve)
.catch(reject)
}).catch(reject)
})
}
/**
* Set the customer information for this import
*/
setCustomer (customer: CustomerObject): void {
this.customer = customer
}
/**
* Set the customer information for this import
*/
registerValidatorCallback (callback: FlatfileImporter['$validatorCallback']): void {
this.$validatorCallback = callback
this.$ready.then((child) => {
child.parentHasValidator()
})
}
/**
* Set the customer information for this import
*/
registerRecordHook (callback: FlatfileImporter['$recordHook']): void {
this.$recordHook = callback
}
registerNetworkErrorCallback (callback: FlatfileImporter['$networkErrorCallback']): void {
this.$networkErrorCallback = callback
}
/**
* Set the customer information for this import
*/
registerFieldHook (field: string, cb: FieldHookCallback): void {
this.$fieldHooks.push({field, cb})
}
/**
* Call close() from the parent window in order to hide the importer. You can do this after
* handling the import callback so your users don't have to click the confirmation button
*/
close () {
this.$ready.then((child) => {
child.close()
})
}
private handleClose () {
elementClass(document.body).remove('flatfile-active')
let el = document.getElementById(`flatfile-${this.uuid}`)
if (el) {
el.style.display = 'none'
}
}
private initialize () {
insertCss(`
.flatfile-component {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
display: none;
z-index: 100000;
}
.flatfile-component iframe {
width: 100%;
height: 100%;
position: absolute;
border-width: 0;
}
body.flatfile-active {
overflow: hidden;
overscroll-behavior-x: none;
}
`)
document.body.insertAdjacentHTML('beforeend', `<div id="flatfile-${this.uuid}" class="flatfile-component"></div>`)
this.handshake = Penpal.connectToChild({
appendTo: document.getElementById(`flatfile-${this.uuid}`) || undefined,
url: FlatfileImporter.MOUNT_URL.replace(':key', this.apiKey),
methods: {
results: (data) => {
this.emit('results', data.results, data.meta)
},
complete: (data) => {
this.emit('complete', data.rows, data.meta)
},
close: () => {
this.emit('close')
this.handleClose()
},
networkErrorCallback: (error) => {
return this.$networkErrorCallback ? this.$networkErrorCallback(error) : undefined
},
validatorCallback: (row) => {
return this.$validatorCallback ? this.$validatorCallback(row) : undefined
},
dataHookCallback: (row, index, mode) => {
return this.$recordHook ? this.$recordHook(row, index, mode) : undefined
},
fieldHookCallback: (values, meta) => {
const fieldHook = this.$fieldHooks.find(v => v.field === meta.field)
if (!fieldHook) {
return undefined
}
return fieldHook.cb(values, meta)
},
ready: () => {
this.handshake.promise.then((child) => {
this.$resolver(child)
if (this.customer) {
child.setUser(this.customer)
}
}).catch((err) => {
console.error(err)
})
return this.options
}
}
})
this.handshake.promise.catch((err) => {
this.$rejecter(err)
})
}
private $generateUuid (): string {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}
private responsePromise (): Promise<FlatfileResults> {
return new Promise((resolve, reject) => {
const loadResolveHandler = async (rows: Array<RecordObject>, meta: object) => {
const results = new FlatfileResults(rows, meta as Meta, this)
resolve(results)
cleanup()
}
function loadRejectHandler (err) {
reject(err)
cleanup()
}
const self = this
function cleanup () {
self.removeListener('close', loadRejectHandler)
self.removeListener('results', loadResolveHandler)
}
this.on('close', loadRejectHandler)
this.on('results', loadResolveHandler)
})
}
}
export type Scalar = string | number | boolean | null | undefined
export type FieldHookCallback = (values: [Scalar, number][], meta: any) => [IDataHookRecord, number][] | Promise<[IDataHookRecord, number][]>