-
Notifications
You must be signed in to change notification settings - Fork 286
/
file-support.js
158 lines (149 loc) · 5.37 KB
/
file-support.js
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
/****************************************************************************
** @license
** This demo file is part of yFiles for HTML 2.6.
** Copyright (c) 2000-2024 by yWorks GmbH, Vor dem Kreuzberg 28,
** 72070 Tuebingen, Germany. All rights reserved.
**
** yFiles demo files exhibit yFiles for HTML functionalities. Any redistribution
** of demo files in source code or binary form, with or without
** modification, is not permitted.
**
** Owners of a valid software license for a yFiles for HTML version that this
** demo is shipped with are allowed to use the demo source code as basis
** for their own yFiles for HTML powered applications. Use of such programs is
** governed by the rights and conditions as set out in the yFiles for HTML
** license agreement.
**
** THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED
** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
** NO EVENT SHALL yWorks BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***************************************************************************/
/**
* This file provides functions to {@link openFile open} and {@link downloadFile download}
* a text file.
*/
/**
* The returned data of the {@link openFile} function.
* @typedef {Object} FileData
* @property {string} filename
* @property {string} content
*/
/**
* Opens the file the user selected in a file input element.
* @returns {!Promise.<FileData>} - A Promise that resolves with the file content and filename.
* @param {!'utf-8'} [encoding=utf-8]
*/
export function openFile(encoding = 'utf-8') {
const fileInputElement = document.createElement('input')
fileInputElement.type = 'file'
fileInputElement.multiple = false
fileInputElement.style.display = 'none'
document.querySelector('body').appendChild(fileInputElement)
return new Promise((resolve, reject) => {
fileInputElement.addEventListener(
'change',
() => {
const file = fileInputElement.files?.item(0)
if (!file) {
reject(new Error('There is no file to open'))
return
}
const reader = new FileReader()
reader.addEventListener('loadend', (evt) => {
const fileReader = evt.target
if (fileReader.error == null) {
resolve({
filename: file.name,
content: fileReader.result
})
} else {
reject(fileReader.error)
}
})
reader.readAsText(file, encoding)
},
false
)
fileInputElement.click()
document.querySelector('body').removeChild(fileInputElement)
})
}
/**
* Downloads the given content as a file.
* @param {!string} content - The file content.
* @param {!string} filename - The proposed filename.
* @param contentType - An optional content type for the download.
* @param {!string} [contentType]
*/
export function downloadFile(content, filename, contentType) {
const type = contentType ?? determineContentType(filename)
const objectURL = URL.createObjectURL(createBlob(content, type))
const aElement = document.createElement('a')
aElement.setAttribute('href', objectURL)
aElement.setAttribute('download', filename)
aElement.style.display = 'none'
document.body.appendChild(aElement)
aElement.click()
document.body.removeChild(aElement)
}
/**
* @param {!string} content
* @param {!string} type
*/
function createBlob(content, type) {
switch (type) {
case 'application/pdf': {
const uint8Array = new Uint8Array(content.length)
for (let i = 0; i < content.length; i++) {
uint8Array[i] = content.charCodeAt(i)
}
return new Blob([uint8Array], { type })
}
case 'application/png': {
const dataUrlParts = content.split(',')
const bString = window.atob(dataUrlParts[1])
const byteArray = []
for (let i = 0; i < bString.length; i++) {
byteArray.push(bString.charCodeAt(i))
}
return new Blob([new Uint8Array(byteArray)], { type })
}
default:
return new Blob([content], { type })
}
}
/**
* Returns the file extension of the given {@link filename}.
* This is the filename part after the last dot.
* @param {!string} [filename]
* @returns {!string}
*/
export function getFileExtension(filename) {
return filename?.match(/\.(?<extension>\w+)$/)?.groups?.extension
}
/**
* Determines the content type of the given {@link filename} based on the file extension.
* This implementation only knows some extensions that are used in the demos.
* @param {!string} filename
* @returns {!string}
*/
export function determineContentType(filename) {
const knownTypes = {
graphml: 'application/graphml+xml',
json: 'application/json',
pdf: 'application/pdf',
png: 'application/png',
svg: 'image/svg+xml',
txt: 'text/plain'
}
const extension = getFileExtension(filename)?.toLowerCase() ?? ''
return knownTypes[extension] ?? 'text/plain'
}