-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsourcePane.js
More file actions
419 lines (390 loc) · 14.9 KB
/
sourcePane.js
File metadata and controls
419 lines (390 loc) · 14.9 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/* Source editor Pane
**
** This pane allows the original source of a resource to be edited by hand
**
*/
const $rdf = require('rdflib')
const UI = require('solid-ui')
const mime = require('mime-types')
module.exports = {
icon: UI.icons.iconBase + 'noun_109873.svg', // noun_109873_51A7F9.svg
name: 'source',
label: function (subject, context) {
const kb = context.session.store
const typeURIs = kb.findTypeURIs(subject)
const prefix = $rdf.Util.mediaTypeClass('text/*').uri.split('*')[0]
for (const t in typeURIs) {
if (t.startsWith(prefix)) return 'Source'
if (t.includes('xml')) return 'XML Source'
if (t.includes('json')) return 'JSON Source' // Like eg application/ld+json
if (t.includes('javascript')) return 'Javascript Source'
}
return null
},
// Create a new text file in a Solid system,
mintNew: function (context, newPaneOptions) {
const kb = context.session.store
let newInstance = newPaneOptions.newInstance
if (!newInstance) {
let uri = newPaneOptions.newBase
if (uri.endsWith('/')) {
uri = uri.slice(0, -1)
newPaneOptions.newBase = uri
}
newInstance = kb.sym(uri)
newPaneOptions.newInstance = newInstance
}
const contentType = mime.lookup(newInstance.uri)
if (
!contentType ||
!(contentType.startsWith('text') || contentType.includes('xml') || contentType.includes('json') || contentType.includes('javascript'))
) {
const msg =
'A new text file has to have an file extension like .txt .ttl .json etc.'
alert(msg)
throw new Error(msg)
}
function contentForNew (contentType) {
let content = '\n'
if (contentType.includes('json')) content = '{}\n'
else if (contentType.includes('rdf+xml')) content = '<rdf:RDF\n xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n\n</rdf:RDF>'
return content
}
return new Promise(function (resolve, reject) {
kb.fetcher
.webOperation('PUT', newInstance.uri, {
data: contentForNew(contentType),
contentType: contentType
})
.then(
function (_response) {
console.log('New text file created: ' + newInstance.uri)
newPaneOptions.newInstance = newInstance
resolve(newPaneOptions)
},
err => {
alert('Cant make new file: ' + err)
reject(err)
}
)
})
},
render: function (subject, context) {
const dom = context.dom
const kb = context.session.store
const fetcher = kb.fetcher
const editStyle = UI.style.sourcePaneStyle ||
'font-family: monospace; font-size: 100%; min-width:60em; margin: 1em 0.2em 1em 0.2em; padding: var(--sui-space-lg, 1em); border: 0.1em solid var(--sui-border-color, #888); border-radius: var(--sui-border-radius, 0.5em);'
let readonly = true
let editing = false
let broken = false
// Set in refresh()
let contentType, allowed, eTag // Note it when we read and use it when we save
const div = dom.createElement('div')
div.setAttribute('class', 'sourcePane')
const table = div.appendChild(dom.createElement('table'))
const main = table.appendChild(dom.createElement('tr'))
const statusRow = table.appendChild(dom.createElement('tr'))
const controls = table.appendChild(dom.createElement('tr'))
controls.setAttribute('style', 'text-align: right;')
const textArea = main.appendChild(dom.createElement('textarea'))
textArea.setAttribute('style', editStyle)
function editButton (dom) {
return UI.widgets.button(
dom,
UI.icons.iconBase + 'noun_253504.svg',
'Edit'
)
}
function compactButton (dom) {
return UI.widgets.button(
dom,
undefined,
'Compact',
compactHandler,
{ needsBorder: true }
)
}
const myCompactButton = controls.appendChild(compactButton(dom))
const cancelButton = controls.appendChild(UI.widgets.cancelButton(dom))
const saveButton = controls.appendChild(UI.widgets.continueButton(dom))
const myEditButton = controls.appendChild(editButton(dom))
function setUnedited () {
if (broken) return
editing = false
myEditButton.style.visibility = subject.uri.endsWith('/') ? 'collapse' : 'visible'
textArea.style.color = '#888'
cancelButton.style.visibility = 'visible'
saveButton.style.visibility = 'collapse'
myCompactButton['style'] = 'visibility: visible; width: 100px; padding: 10.2px; transform: translate(0, -30%)'
if (!compactable[contentType.split(';')]) { myCompactButton.style.visibility = 'collapse' }
textArea.setAttribute('readonly', 'true')
}
function setEditable () {
if (broken) return
editing = true
textArea.style.color = 'black'
cancelButton.style.visibility = 'visible' // not logically needed but may be comforting
saveButton.style.visibility = 'collapse'
myEditButton.style.visibility = 'collapse'
myCompactButton.style.visibility = 'collapse' // do not allow compact while editing
textArea.removeAttribute('readonly')
}
function setEdited (_event) {
if (broken || !editing) return
textArea.style.color = 'green'
cancelButton.style.visibility = 'visible'
saveButton.style.visibility = 'visible'
myEditButton.style.visibility = 'collapse'
myCompactButton.style.visibility = 'collapse'
textArea.removeAttribute('readonly')
}
const parseable = {
'text/n3': true,
'text/turtle': true,
'application/rdf+xml': true,
'application/xhtml+xml': true, // For RDFa?
'text/html': true, // For data island
// 'application/sparql-update': true,
'application/json': true,
'application/ld+json': true
// 'application/nquads' : true,
// 'application/n-quads' : true
}
/** Set Caret position in a text box
* @param {Element} elem - the element to be tweaked
* @param {Integer} caretPos - the poisition starting at zero
* @credit https://stackoverflow.com/questions/512528/set-keyboard-caret-position-in-html-textbox
*/
function setCaretPosition (elem, cause) {
if (elem != null) {
if (cause.characterInFile === -1 && cause.lineNo) cause.lineNo += 1
const pos = cause.lineNo ? elem.value.split('\n', cause.lineNo).join('\n').length : 0
const caretPos = pos + cause.characterInFile
if (elem.createTextRange) {
const range = elem.createTextRange()
range.move('character', caretPos)
range.select()
} else {
elem.focus()
if (elem.selectionStart) {
elem.setSelectionRange(caretPos, caretPos)
}
}
}
}
function HTMLDataIsland (data) {
let dataIslandContentType = ''
let dataIsland = ''
let pos = 0
const scripts = data.split('</script')
if (scripts && scripts.length) {
for (let script of scripts) {
script = '<script' + script.split('<script')[1] + '</script>'
const RDFType = ['text/turtle', 'text/n3', 'application/ld+json', 'application/rdf+xml']
const contentType = RDFType.find(type => script.includes(`type="${type}"`))
if (contentType) {
dataIsland = script.replace(/^<script(.*?)>/gm, '').replace(/<\/script>$/gm, '')
dataIslandContentType = contentType
break
}
}
}
return [dataIsland, dataIslandContentType, pos]
}
function checkSyntax (data, contentType, base) {
if (!parseable[contentType]) return true // don't check things we don't understand
let pos
if (contentType === 'text/html') {
[data, contentType, pos] = HTMLDataIsland(data)
if (!contentType) return true
}
try {
statusRow.innerHTML = ''
if (contentType === 'application/json') return JSON.parse(data)
else {
try {
kb.removeDocument(subject)
} catch (err) {
// this is a hack until issue is resolved in rdflib
if (!err.message.includes('Statement to be removed is not on store')) throw err
console.log(err)
}
delete fetcher.requested[subject.value]
// rdflib parse jsonld do not return parsing errors
if (contentType === 'application/ld+json') {
JSON.parse(data)
$rdf.parse(data, kb, base.uri, contentType, (err, res) => {
if (err) throw err
const serialized = $rdf.serialize(base, res, base.uri, contentType)
if (data.includes('@id') && !serialized.includes('@id')) {
const e = new Error('Invalid jsonld : predicate do not expand to an absolute IRI')
statusRow.appendChild(UI.widgets.errorMessageBlock(dom, e))
// throw e
return false
}
return true
})
} else {
$rdf.parse(data, kb, base.uri, contentType)
}
}
return true
} catch (e) {
statusRow.appendChild(UI.widgets.errorMessageBlock(dom, e))
for (let cause = e; (cause = cause.cause); cause) {
if (cause.characterInFile) {
setCaretPosition(textArea, cause)
}
}
return false
}
return true
}
async function saveBack (_event) {
const data = textArea.value
if (!checkSyntax(data, contentType, subject)) {
setEdited() // failed to save -> different from web
textArea.style.color = 'red'
return
}
const options = { data, contentType }
if (eTag) options.headers = { 'if-match': eTag } // avoid overwriting changed files -> status 412
try {
const response = await fetcher.webOperation('PUT', subject.uri, options)
if (!happy(response, 'PUT')) return
/// @@ show edited: make save button disabled until edited again.
try {
const response = await fetcher.webOperation('HEAD', subject.uri) // , defaultFetchHeaders())
if (!happy(response, 'HEAD')) return
getResponseHeaders(response) // get new eTag
setUnedited() // used to be setEdited()
} catch (err) {
throw err
}
} catch (err) {
div.appendChild(
UI.widgets.errorMessageBlock(dom, 'Error saving back: ' + err))
}
}
function happy (response, method) {
if (!response.ok) {
let msg = 'HTTP error on ' + method + '! Status: ' + response.status
console.log(msg)
if (response.status === 412) msg = 'Error: File changed by someone else'
statusRow.appendChild(UI.widgets.errorMessageBlock(dom, msg))
}
return response.ok
}
const compactable = {
'text/n3': true,
'text/turtle': true,
'application/ld+json': true
}
function compactHandler (_event) {
if (compactable[contentType]) {
try {
$rdf.parse(textArea.value, kb, subject.uri, contentType)
// for jsonld serialize which is a Promise. New rdflib
const serialized = Promise.resolve($rdf.serialize(kb.sym(subject.uri), kb, subject.uri, contentType))
serialized.then(result => { textArea.value = result /*return div*/ })
cancelButton.style.visibility = 'visible'
} catch (e) {
statusRow.appendChild(UI.widgets.errorMessageBlock(dom, e))
}
}
}
// function refresh (_event) {
// Use default fetch headers (such as Accept)
/* function defaultFetchHeaders () {
const options = fetcher.initFetchOptions(subject.uri, {})
const { headers } = options
options.headers = new Headers()
for (const header in headers) {
if (typeof headers[header] === 'string') {
options.headers.set(header, headers[header])
}
}
return options
} */
// get response headers
function getResponseHeaders (response) {
if (response.headers && response.headers.get('content-type')) {
contentType = response.headers.get('content-type').split(';')[0] // Should work but headers may be empty
allowed = response.headers.get('allow') // const cts = kb.fetcher.getHeader(subject.doc(), 'content-type')
eTag = response.headers.get('etag')
} else {
const reqs = kb.each(
null,
kb.sym('http://www.w3.org/2007/ont/link#requestedURI'),
subject.uri
)
reqs.forEach(req => {
const rrr = kb.any(
req,
kb.sym('http://www.w3.org/2007/ont/link#response')
)
if (rrr && rrr.termType === 'NamedNode') {
contentType = kb.anyValue(rrr, UI.ns.httph('content-type'))
allowed = kb.anyValue(rrr, UI.ns.httph('allow'))
eTag = kb.anyValue(rrr, UI.ns.httph('etag'))
if (!eTag) console.log('sourcePane: No eTag on GET')
}
})
}
}
function refresh (_event) {
// see https://github.com/linkeddata/rdflib.js/issues/629
// const options = defaultFetchHeaders()
fetcher
.webOperation('GET', subject.uri) // , options)
.then(function (response) {
if (!happy(response, 'GET')) return
const desc = response.responseText
if (desc === undefined) { // Defensive https://github.com/linkeddata/rdflib.js/issues/506
const msg = 'source pane: No text in response object!!'
statusRow.appendChild(UI.widgets.errorMessageBlock(dom, msg))
return // Never mis-represent the contents of the file.
}
textArea.rows = desc.split('\n').length + 2
textArea.cols = 80
textArea.value = desc
getResponseHeaders (response)
if (!contentType) {
readonly = true
broken = true
statusRow.appendChild(
UI.widgets.errorMessageBlock(
dom,
'Error: No content-type available!'
)
)
return
}
setUnedited()
// console.log(' source content-type ' + contentType)
// let allowed = response.headers['allow']
if (!allowed) {
console.log('@@@@@@@@@@ No Allow: header from this server')
readonly = false // better allow just in case
} else {
readonly = allowed.indexOf('PUT') < 0 // In future more info re ACL allow?
}
textArea.readonly = readonly
})
.catch(err => {
div.appendChild(
UI.widgets.errorMessageBlock(dom, 'Error reading file: ' + err)
)
})
}
textArea.addEventListener('keyup', setEdited)
myCompactButton.addEventListener('click', compactHandler)
myEditButton.addEventListener('click', setEditable)
cancelButton.addEventListener('click', refresh)
saveButton.addEventListener('click', saveBack)
refresh()
return div
}
}
// ENDS