-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.html
executable file
·298 lines (240 loc) · 8.62 KB
/
ui.html
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
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/thomas-lowry/figma-plugin-ds/dist/figma-plugin-ds.css">
<style>
body {
padding: 2em;
}
div {
margin: 0em;
}
input {
display: block;
}
/* Optional styling for the container element */
#table-container {
max-height: 350px;
overflow-y: auto;
}
/* Styling for the table */
table {
border-collapse: collapse;
width: 100%;
}
/* Styling for table header cells */
th, tr:nth-last-child(1) {
background-color: #f2f2f2;
font-weight: bold;
padding: 8px;
text-align: left;
font-size: 11px;
}
/* Styling for table data cells */
td {
border: 1px solid #ddd;
padding: 8px;
font-size: 11px;
}
/* Alternating row background color */
tr:nth-child(even) {
background-color: #f9f9f9;
}
/* Hover effect on rows */
tr:hover {
background-color: #f5f5f5;
}
</style>
<h1>Compress & Export</h1>
<label for="quality" class="type--small">Compression:</label>
<input type="number" id="quality" name="quality" min="1" max="100" step="0.5" value="100" style="display: inline-block">
<input type="range" min="1" max="100" value="100" class="slider" step="0.5" id="myRange" value="100" style="accent-color: rgb(0, 85, 35);">
<div id="table-container" ></div>
<div id="total-container"></div>
<div style="text-align: center; margin-top: 10px;">
<button class="button button--primary" id="reload" style="display: inline-block;">Reload</button>
<button class="button button--primary" id="calculate" style="display: inline-block">Calculate</button>
<button class="button button--primary" id="export" style="display: inline-block;">Export</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
<script>
const qualityInput = document.getElementById('quality');
const rangeInput = document.getElementById('myRange');
document.getElementById('reload').onclick = () => {
parent.postMessage({pluginMessage: ''}, '*')
}
// Update the input number when the range input changes
rangeInput.addEventListener('input', () => {
qualityInput.value = rangeInput.value;
});
// Update the range input when the input number changes
qualityInput.addEventListener('input', () => {
rangeInput.value = qualityInput.value;
});
window.onmessage = (event) => {
const arrayData = event.data.pluginMessage;
const arrayBlob = []
let compressedArray
if (arrayData.length) {
for (data of arrayData) {
arrayBlob.push([data[0], data[1], createBlob(data[2])])
}
}
updateTable(arrayBlob)
document.getElementById('export').onclick = () => {
if (compressedArray) {
handleBlobs(compressedArray)
} else {
handleBlobs(arrayBlob)
}
}
document.getElementById('calculate').onclick = () => {
quality = document.getElementById('quality').value
quality = (parseFloat(quality)) / 100
// if quality === 100
// do nothing and export arrayBlob
//else
compressData(quality, arrayBlob)
.then((newBlobs) => {
updateTable(newBlobs)
compressedArray = newBlobs
})
.catch((error) => {
console.error('Error compressing blobs:', error);
});
};
}
// function to compress
function compressData(quality, arrayBlob) {
const compressionPromises = arrayBlob.map(([name, scale, blob]) =>
compressBlob(quality, blob).then((compressedBlob) => [name, scale, compressedBlob])
);
return Promise.all(compressionPromises);
}
// function to update the UI with data from array
function updateTable(blobsArray) {
blobsArray.sort((a, b) => {
const layerA = a[0];
const layerB = b[0];
return naturalSort(layerA, layerB);
});
const container = document.getElementById("table-container");
// Clear the container
container.innerHTML = '';
const table = document.createElement("table");
const headerRow = document.createElement("tr");
const headerCell1 = document.createElement("th");
headerCell1.textContent = "Node Name";
headerRow.appendChild(headerCell1);
const headerCell2 = document.createElement("th");
headerCell2.textContent = "Scale";
headerRow.appendChild(headerCell2);
const headerCell3 = document.createElement("th");
headerCell3.textContent = "File Size";
headerRow.appendChild(headerCell3);
table.appendChild(headerRow);
let totalSelectionSize = 0;
blobsArray.forEach((blob) => {
const layer = shortenString(blob[0]);
const scale = blob[1]
const arraySize = blob[2].size;
const row = document.createElement("tr");
const layerCell = document.createElement("td");
layerCell.textContent = layer;
row.appendChild(layerCell);
const scaleCell = document.createElement("td");
scaleCell.textContent = scale;
row.appendChild(scaleCell);
const arraySizeCell = document.createElement("td");
arraySizeCell.textContent = formatBytes(arraySize);
row.appendChild(arraySizeCell);
table.appendChild(row);
totalSelectionSize += arraySize;
});
const totalRow = document.createElement("tr");
const totalCell = document.createElement("td");
totalCell.textContent = "Total";
totalRow.appendChild(totalCell);
const emptyCell = document.createElement("td");
totalRow.appendChild(emptyCell);
const totalSelectionSizeCell = document.createElement("td");
totalSelectionSizeCell.textContent = formatBytes(totalSelectionSize);
totalRow.appendChild(totalSelectionSizeCell);
table.appendChild(totalRow);
container.appendChild(table);
}
function compressBlob(quality, blob) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
canvas.toBlob((compressedBlob) => {
// Clean up the object URL after the blob is created
URL.revokeObjectURL(img.src);
resolve(compressedBlob);
}, blob.type, quality);
};
img.onerror = (error) => {
// Clean up the object URL in case of an error
URL.revokeObjectURL(img.src);
reject(error);
};
img.src = URL.createObjectURL(blob);
});
}
function typedArrayToBuffer(array) {
return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset)
}
// function to create a blob from the Uint8Array
function createBlob(data) {
const cleanBytes = typedArrayToBuffer(data)
const blob = new Blob([ cleanBytes ], { type: 'image/jpeg' });
// updateComponent(cleanBytes)
return blob
}
// function to create, zip and download files
function handleBlobs(inputBlobs) {
let zip = new JSZip();
for (let blob of inputBlobs) {
zip.file(`${blob[0]}.jpeg`, blob[2], {base64: true})
}
zip.generateAsync({ type: 'blob' })
.then(function(content) {
const link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.innerText = 'Download All Images';
link.download = 'documents.zip'; // Specify the desired filename for the zip file
document.body.appendChild(link);
link.click();
document.body.removeChild(link)
// Clean up the object URL
URL.revokeObjectURL(link.href);
});
}
// function to sort the array in a natural way
function naturalSort(a, b) {
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
return collator.compare(a, b);
}
function shortenString(str) {
const maxLength = 50
if (str.length <= maxLength) {
return str; // Return the original string if it's already within the desired length
}
const ellipsis = '...'; // The ellipsis to indicate that the string has been shortened
const visibleChars = maxLength - ellipsis.length; // Calculate the number of visible characters
const firstChars = str.slice(0, visibleChars / 2); // Extract the first half of visible characters
const lastChars = str.slice(-visibleChars / 2); // Extract the last half of visible characters
return `${firstChars}${ellipsis}${lastChars}`; // Combine the shortened string with the ellipsis
}
function formatBytes(bytes) {
if (bytes < 1024) {
return bytes + ' B';
} else if (bytes < 1024 * 1024) {
return (bytes / 1024).toFixed(1) + ' KB';
} else {
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
}
</script>