-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ext-opensave.js
272 lines (261 loc) · 10.1 KB
/
ext-opensave.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
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
/* globals seConfirm */
/**
* @file ext-opensave.js
*
* @license MIT
*
* @copyright 2020 OptimistikSAS
*
*/
/**
* @type {module:svgcanvas.EventHandler}
* @param {external:Window} wind
* @param {module:svgcanvas.SvgCanvas#event:saved} svg The SVG source
* @listens module:svgcanvas.SvgCanvas#event:saved
* @returns {void}
*/
import { fileOpen, fileSave } from 'browser-fs-access'
const name = 'opensave'
let handle = null
const loadExtensionTranslation = async function (svgEditor) {
let translationModule
const lang = svgEditor.configObj.pref('lang')
try {
translationModule = await import(`./locale/${lang}.js`)
} catch (_error) {
console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
translationModule = await import('./locale/en.js')
}
svgEditor.i18next.addResourceBundle(lang, 'translation', translationModule.default, true, true)
}
export default {
name,
async init (_S) {
const svgEditor = this
const { svgCanvas } = svgEditor
const { $id, $click } = svgCanvas
await loadExtensionTranslation(svgEditor)
/**
* @param {Event} e
* @returns {void}
*/
const importImage = (e) => {
$id('se-prompt-dialog').title = this.i18next.t('notification.loadingImage')
$id('se-prompt-dialog').setAttribute('close', false)
e.stopPropagation()
e.preventDefault()
const file = (e.type === 'drop') ? e.dataTransfer.files[0] : e.currentTarget.files[0]
if (!file) {
$id('se-prompt-dialog').setAttribute('close', true)
return
}
if (!file.type.includes('image')) {
return
}
// Detected an image
// svg handling
let reader
if (file.type.includes('svg')) {
reader = new FileReader()
reader.onloadend = (ev) => {
// imgImport.shiftKey (shift key pressed or not) will determine if import should preserve dimension)
const newElement = this.svgCanvas.importSvgString(ev.target.result, imgImport.shiftKey)
this.svgCanvas.alignSelectedElements('m', 'page')
this.svgCanvas.alignSelectedElements('c', 'page')
// highlight imported element, otherwise we get strange empty selectbox
this.svgCanvas.selectOnly([newElement])
$id('se-prompt-dialog').setAttribute('close', true)
}
reader.readAsText(file)
} else {
// bitmap handling
reader = new FileReader()
reader.onloadend = ({ target: { result } }) => {
/**
* Insert the new image until we know its dimensions.
* @param {Float} imageWidth
* @param {Float} imageHeight
* @returns {void}
*/
const insertNewImage = (imageWidth, imageHeight) => {
const newImage = this.svgCanvas.addSVGElementsFromJson({
element: 'image',
attr: {
x: 0,
y: 0,
width: imageWidth,
height: imageHeight,
id: this.svgCanvas.getNextId(),
style: 'pointer-events:inherit'
}
})
this.svgCanvas.setHref(newImage, result)
this.svgCanvas.selectOnly([newImage])
this.svgCanvas.alignSelectedElements('m', 'page')
this.svgCanvas.alignSelectedElements('c', 'page')
this.topPanel.updateContextPanel()
$id('se-prompt-dialog').setAttribute('close', true)
}
// create dummy img so we know the default dimensions
let imgWidth = 100
let imgHeight = 100
const img = new Image()
img.style.opacity = 0
img.addEventListener('load', () => {
imgWidth = img.offsetWidth || img.naturalWidth || img.width
imgHeight = img.offsetHeight || img.naturalHeight || img.height
insertNewImage(imgWidth, imgHeight)
})
img.src = result
}
reader.readAsDataURL(file)
}
}
// create an input with type file to open the filesystem dialog
const imgImport = document.createElement('input')
imgImport.type = 'file'
imgImport.addEventListener('change', importImage)
// dropping a svg file will import it in the svg as well
this.workarea.addEventListener('drop', importImage)
const clickClear = async function () {
const [x, y] = svgEditor.configObj.curConfig.dimensions
const ok = await seConfirm(svgEditor.i18next.t('notification.QwantToClear'))
if (ok === 'Cancel') {
return
}
svgEditor.leftPanel.clickSelect()
svgEditor.svgCanvas.clear()
svgEditor.svgCanvas.setResolution(x, y)
svgEditor.updateCanvas(true)
svgEditor.zoomImage()
svgEditor.layersPanel.populateLayers()
svgEditor.topPanel.updateContextPanel()
svgEditor.topPanel.updateTitle('untitled.svg')
}
/**
* By default, this.editor.svgCanvas.open() is a no-op. It is up to an extension
* mechanism (opera widget, etc.) to call `setCustomHandlers()` which
* will make it do something.
* @returns {void}
*/
const clickOpen = async function () {
// ask user before clearing an unsaved SVG
const response = await svgEditor.openPrep()
if (response === 'Cancel') { return }
svgCanvas.clear()
try {
const blob = await fileOpen({
mimeTypes: ['image/*']
})
const svgContent = await blob.text()
await svgEditor.loadSvgString(svgContent)
svgEditor.updateCanvas()
handle = blob.handle
svgEditor.topPanel.updateTitle(blob.name)
svgEditor.svgCanvas.runExtensions('onOpenedDocument', {
name: blob.name,
lastModified: blob.lastModified,
size: blob.size,
type: blob.type
})
} catch (err) {
if (err.name !== 'AbortError') {
return console.error(err)
}
}
}
const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data)
const byteArrays = []
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize)
const byteNumbers = new Array(slice.length)
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i)
}
const byteArray = new Uint8Array(byteNumbers)
byteArrays.push(byteArray)
}
const blob = new Blob(byteArrays, { type: contentType })
return blob
}
/**
*
* @returns {void}
*/
const clickSave = async function (type) {
const $editorDialog = $id('se-svg-editor-dialog')
const editingsource = $editorDialog.getAttribute('dialog') === 'open'
if (editingsource) {
svgEditor.saveSourceEditor()
} else {
// In the future, more options can be provided here
const saveOpts = {
images: svgEditor.configObj.pref('img_save'),
round_digits: 2
}
// remove the selected outline before serializing
svgCanvas.clearSelection()
// Update save options if provided
if (saveOpts) {
const saveOptions = svgCanvas.mergeDeep(svgCanvas.getSvgOption(), saveOpts)
for (const [key, value] of Object.entries(saveOptions)) {
svgCanvas.setSvgOption(key, value)
}
}
svgCanvas.setSvgOption('apply', true)
// no need for doctype, see https://jwatt.org/svg/authoring/#doctype-declaration
const svg = '<?xml version="1.0"?>\n' + svgCanvas.svgCanvasToString()
const b64Data = svgCanvas.encode64(svg)
const blob = b64toBlob(b64Data, 'image/svg+xml')
try {
if (type === 'save' && handle !== null) {
const throwIfExistingHandleNotGood = false
handle = await fileSave(blob, {
fileName: 'untitled.svg',
extensions: ['.svg']
}, handle, throwIfExistingHandleNotGood)
} else {
handle = await fileSave(blob, {
fileName: svgEditor.title,
extensions: ['.svg']
})
}
svgEditor.topPanel.updateTitle(handle.name)
svgCanvas.runExtensions('onSavedDocument', {
name: handle.name,
kind: handle.kind
})
} catch (err) {
if (err.name !== 'AbortError') {
return console.error(err)
}
}
}
}
return {
name: svgEditor.i18next.t(`${name}:name`),
// The callback should be used to load the DOM with the appropriate UI items
callback () {
const buttonTemplate = `
<se-menu-item id="tool_clear" label="opensave.new_doc" shortcut="N" src="new.svg"></se-menu-item>`
svgCanvas.insertChildAtIndex($id('main_button'), buttonTemplate, 0)
const openButtonTemplate = '<se-menu-item id="tool_open" label="opensave.open_image_doc" src="open.svg"></se-menu-item>'
svgCanvas.insertChildAtIndex($id('main_button'), openButtonTemplate, 1)
const saveButtonTemplate = '<se-menu-item id="tool_save" label="opensave.save_doc" shortcut="S" src="saveImg.svg"></se-menu-item>'
svgCanvas.insertChildAtIndex($id('main_button'), saveButtonTemplate, 2)
const saveAsButtonTemplate = '<se-menu-item id="tool_save_as" label="opensave.save_as_doc" src="saveImg.svg"></se-menu-item>'
svgCanvas.insertChildAtIndex($id('main_button'), saveAsButtonTemplate, 3)
const importButtonTemplate = '<se-menu-item id="tool_import" label="tools.import_doc" src="importImg.svg"></se-menu-item>'
svgCanvas.insertChildAtIndex($id('main_button'), importButtonTemplate, 4)
// handler
$click($id('tool_clear'), clickClear.bind(this))
$click($id('tool_open'), clickOpen.bind(this))
$click($id('tool_save'), clickSave.bind(this, 'save'))
$click($id('tool_save_as'), clickSave.bind(this, 'saveas'))
// tool_import pressed with shiftKey will not scale the SVG
$click($id('tool_import'), (ev) => { imgImport.shiftKey = ev.shiftKey; imgImport.click() })
}
}
}
}