-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbraid-view.js
More file actions
412 lines (361 loc) · 18 KB
/
braid-view.js
File metadata and controls
412 lines (361 loc) · 18 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
// ============================================================
// <braid-view> — view and edit any braid-http resource
// ============================================================
//
// A web component that auto-detects the type of a braid-http resource
// and renders the appropriate UI: text editor, image viewer, or JSON editor.
//
// Depends on:
// braid-http-client.js — braid_fetch
// simpleton.js, text-client.js, cursor-sync.js,
// textarea-highlights.js, syncarea.js, myers-diff.js — text editing
// client.js (braid-blob) — blob/image viewing
// json-patch.js — JSON editing
//
// Usage:
// <braid-view src="https://some-braid-server/resource"></braid-view>
//
// Attributes:
// src — the URL of the braid resource
// bearer — Bearer token for Authorization header
// accept — Accept (and Content-Type) for the resource
// (e.g. "text/markdown"). Threaded through to the
// inner viewer.
// controls-only — don't render a viewer; just provide controls
// (drag-drop upload, delete icon) and emit events.
// Useful when the host page handles display itself
// (e.g. braid-chrome's native media rendering).
//
// Events:
// 'remoteupdate' — fired when a remote update arrives
// 'delete' — fired when the resource is deleted (via subscription)
//
;(function() {
var BRAID_VIEW_ATTRS = ['src', 'bearer', 'accept', 'controls-only']
class BraidView extends HTMLElement {
static observedAttributes = [...BRAID_VIEW_ATTRS]
connectedCallback() { this.connect() }
disconnectedCallback() { this.disconnect() }
attributeChangedCallback(name, oldValue, newValue) {
if (!this.isConnected || oldValue === newValue) return
if (BRAID_VIEW_ATTRS.includes(name)) {
this.disconnect()
this.connect()
}
}
async connect() {
var url = this.getAttribute('src')
if (!url) return
this.innerHTML = ''
this.ac = new AbortController()
var headers = {}
var bearer = this.getAttribute('bearer')
if (bearer) headers['Authorization'] = 'Bearer ' + bearer
// Default Accept prioritizes the resource types we know how to render.
// Markdown first (since hedgedoc & similar route on this), then plain
// text, then common image formats, then anything as a fallback.
var accept = this.getAttribute('accept')
|| 'text/markdown, text/plain;q=0.9, image/jpeg;q=0.8, image/png;q=0.8, image/gif;q=0.8, */*;q=0.1'
headers['Accept'] = accept
var controls_only = this.hasAttribute('controls-only')
// Always set up drag-drop upload and delete icon
this.setup_controls(url, headers)
if (controls_only) {
// Subscribe just for events (so host page knows about updates)
this.subscribe_for_events(url, headers)
return
}
// Probe the resource to detect its type
try {
var res = await braid_fetch(url, {
method: 'HEAD',
headers,
signal: this.ac.signal
})
} catch (e) {
// HEAD failed — try connecting anyway as simpleton text
this.content_type = 'text/plain'
this.connect_text(url, headers)
return
}
var content_type = (res.headers.get('content-type') || '').split(/[;,]/)[0].trim()
var merge_type = res.headers.get('merge-type')
this.content_type = content_type
this.merge_type = merge_type
// Route to the appropriate handler
if (content_type.match(/^image\//) ||
content_type.match(/^video\//) ||
content_type.match(/^audio\//)) {
this.connect_blob(url, headers, content_type)
} else if (content_type === 'application/json' && !merge_type) {
this.connect_json(url, headers)
} else {
// Default: text editor (simpleton or dt). Pass the exact
// content-type we got from HEAD so syncarea sends Accept and
// Content-Type matching the resource (PUTs need exact, not
// a priority list).
this.connect_text(url, headers, merge_type, content_type)
}
}
// ════════════════════════════════════════════════════════════
// Controls: drag-drop upload + delete icon (always present)
// ════════════════════════════════════════════════════════════
setup_controls(url, headers) {
var self = this
// Delete icon
var delete_btn = document.createElement('div')
delete_btn.style.cssText = 'position:fixed; top:0; right:0; width:25px; height:25px; padding:5px; cursor:pointer; display:flex; align-items:center; justify-content:center; z-index:9999;'
delete_btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width:100%;height:100%;fill:rgba(255,255,255,0.5)"><path d="M22 5a1 1 0 0 1-1 1H3a1 1 0 0 1 0-2h5V3a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v1h5a1 1 0 0 1 1 1zM4.934 21.071 4 8h16l-.934 13.071a1 1 0 0 1-1 .929H5.931a1 1 0 0 1-.997-.929zM15 18a1 1 0 0 0 2 0v-6a1 1 0 0 0-2 0zm-4 0a1 1 0 0 0 2 0v-6a1 1 0 0 0-2 0zm-4 0a1 1 0 0 0 2 0v-6a1 1 0 0 0-2 0z"/></svg>'
delete_btn.onclick = async () => {
if (!confirm('Are you sure you want to DELETE this resource from the server?')) return
try {
var r = await braid_fetch(url, { method: 'DELETE', headers })
if (!r.ok) alert('Error deleting (' + r.status + '): ' + await r.text())
else {
self.dispatchEvent(new CustomEvent('delete'))
location.reload()
}
} catch (e) { alert('Error deleting: ' + e) }
}
this.appendChild(delete_btn)
// Drag-and-drop upload overlay
var overlay = document.createElement('div')
overlay.style.cssText = 'position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,123,255,0.1); border:3px dashed #007bff; display:none; z-index:9998; pointer-events:none; align-items:center; justify-content:center; font-family:monospace; font-size:16px; color:#007bff;'
overlay.textContent = 'Drop file here to upload'
this.appendChild(overlay)
function prevent(e) { e.preventDefault(); e.stopPropagation() }
function show() { overlay.style.display = 'flex' }
function hide() { overlay.style.display = 'none' }
// Use document-level listeners so drag-drop works even in controls-only
// mode where braid-view might not cover the whole page
document.addEventListener('dragenter', prevent)
document.addEventListener('dragover', prevent)
document.addEventListener('dragleave', prevent)
document.addEventListener('drop', prevent)
document.addEventListener('dragenter', show)
document.addEventListener('dragover', show)
document.addEventListener('dragleave', hide)
document.addEventListener('drop', hide)
document.addEventListener('drop', async (e) => {
var files = e.dataTransfer.files
if (files.length === 0) return
var file = files[0]
// Show upload indicator
var indicator = document.createElement('div')
indicator.style.cssText = 'position:fixed; top:5px; right:5px; z-index:9999; background:rgba(255,165,0,0.8); color:white; padding:4px 8px; border-radius:3px; font-size:12px; font-family:monospace;'
indicator.textContent = '\u2022 Uploading...'
document.body.appendChild(indicator)
try {
var buf = await file.arrayBuffer()
var r = await braid_fetch(url, {
method: 'PUT',
headers: { ...headers, 'Content-Type': file.type },
body: buf,
retry: true
})
indicator.remove()
if (!r.ok) alert('Upload failed with status: ' + r.status)
else location.reload()
} catch (e) {
indicator.remove()
alert('Upload failed: ' + e)
}
})
// Store cleanup references
this._controls_cleanup = () => {
document.removeEventListener('dragenter', prevent)
document.removeEventListener('dragover', prevent)
document.removeEventListener('dragleave', prevent)
document.removeEventListener('drop', prevent)
}
}
// ════════════════════════════════════════════════════════════
// Subscribe just for events (controls-only mode)
// ════════════════════════════════════════════════════════════
subscribe_for_events(url, headers) {
var self = this
// Use braid-blob client for subscription — it handles AWW merge-type
// and gives us update/delete events.
// Skip the first update (initial state) — only fire for actual changes.
var got_first_update = false
this.blob_client = braid_blob_client(url, {
signal: this.ac.signal,
on_update: (body, ct, version) => {
if (!got_first_update) { got_first_update = true; return }
self.dispatchEvent(new CustomEvent('remoteupdate', {
detail: { body, content_type: ct, version }
}))
},
on_delete: () => {
self.dispatchEvent(new CustomEvent('delete'))
},
on_error: (e) => {
console.error('braid-view subscription error:', e)
}
})
}
// ════════════════════════════════════════════════════════════
// Text editing (simpleton via <sync-area>)
// ════════════════════════════════════════════════════════════
connect_text(url, headers, merge_type, content_type) {
// For now, always use simpleton via <sync-area>
// Future: add DT handler when merge_type === 'dt'
var textarea = document.createElement('sync-area')
textarea.style.width = '100%'
textarea.style.height = '100%'
textarea.setAttribute('src', url)
var bearer = this.getAttribute('bearer')
if (bearer) textarea.setAttribute('bearer', bearer)
// Use the user's `accept` if set, otherwise the exact content-type
// we got from the HEAD probe.
var accept = this.getAttribute('accept') || content_type
if (accept) textarea.setAttribute('accept', accept)
this.appendChild(textarea)
this.syncarea = textarea
}
// ════════════════════════════════════════════════════════════
// Blob/image viewing (via braid-blob client)
// ════════════════════════════════════════════════════════════
connect_blob(url, headers, content_type) {
var self = this
// Container for the media element
var container = document.createElement('div')
container.style.cssText = 'position:relative; width:100%; height:100%; display:flex; align-items:center; justify-content:center; background:#111;'
this.appendChild(container)
// Media element (img, video, or audio)
var media
if (content_type.match(/^image\//)) {
media = document.createElement('img')
media.style.maxWidth = '100%'
media.style.maxHeight = '100%'
} else if (content_type.match(/^video\//)) {
media = document.createElement('video')
media.controls = true
media.style.maxWidth = '100%'
media.style.maxHeight = '100%'
} else {
media = document.createElement('audio')
media.controls = true
}
container.appendChild(media)
// Subscribe via braid-blob client
this.blob_client = braid_blob_client(url, {
signal: this.ac.signal,
on_update: (body, ct, version) => {
if (body) {
var blob = new Blob([body], { type: ct || content_type })
var obj_url = URL.createObjectURL(blob)
if (media.src && media.src.startsWith('blob:'))
URL.revokeObjectURL(media.src)
media.src = obj_url
}
self.dispatchEvent(new CustomEvent('remoteupdate', {
detail: { body, content_type: ct, version }
}))
},
on_delete: () => {
media.src = ''
self.dispatchEvent(new CustomEvent('delete'))
},
on_error: (e) => {
console.error('braid-blob error:', e)
}
})
}
// ════════════════════════════════════════════════════════════
// JSON editing
// ════════════════════════════════════════════════════════════
connect_json(url, headers) {
var self = this
var textarea = document.createElement('textarea')
textarea.style.cssText = 'width:100%; height:100%; padding:13px 8px; font-size:13px; font-family:monospace; border:0; box-sizing:border-box; background:transparent;'
textarea.readOnly = true
textarea.disabled = true
this.appendChild(textarea)
var doc = null
var last_version = []
var outstanding_changes = 0
var peer = Math.random().toString(36).slice(2)
var default_version_count = 1
function set_style_good(good) {
textarea.style.background = good ? '' : 'pink'
textarea.style.caretColor = good ? '' : 'red'
}
// Subscribe
braid_fetch(url, {
subscribe: true,
headers: { ...headers, Accept: 'application/json' },
retry: () => true,
signal: this.ac.signal,
peer
}).then(res => {
res.subscribe(update => {
var body = update.body ? update.body_text : null
var patches = update.patches
if (patches) for (var p of patches) p.content = p.content_text
textarea.readOnly = false
textarea.disabled = false
var version = update.version || ['default-' + default_version_count++]
var parents = update.parents || last_version
if (body != null) {
doc = JSON.parse(body)
} else if (patches) {
for (var p of patches)
doc = apply_patch(doc, p.range, JSON.parse(p.content))
}
last_version = version
textarea.value = JSON.stringify(doc, null, 2)
set_style_good(true)
self.dispatchEvent(new CustomEvent('remoteupdate', {
detail: { version, parents, patches }
}))
}, e => {
console.error('JSON subscription error:', e)
textarea.style.border = '4px red solid'
textarea.style.background = '#fee'
})
}).catch(e => {
console.error('JSON fetch error:', e)
})
// Local edits
textarea.oninput = async () => {
try {
doc = JSON.parse(textarea.value)
set_style_good(true)
var version = ['default-' + default_version_count++]
outstanding_changes++
textarea.style.caretColor = 'red'
try {
await braid_fetch(url, {
method: 'PUT',
headers: { ...headers, 'Content-Type': 'application/json' },
version,
parents: last_version,
patches: [{ unit: 'json', range: '', content: JSON.stringify(doc) }],
peer,
retry: true
})
last_version = version
} catch (e) {
console.error('JSON PUT error:', e)
}
outstanding_changes--
if (!outstanding_changes) textarea.style.caretColor = ''
} catch (e) {
set_style_good(false)
}
}
}
// ════════════════════════════════════════════════════════════
// Cleanup
// ════════════════════════════════════════════════════════════
disconnect() {
if (this.ac) { this.ac.abort(); this.ac = null }
if (this._controls_cleanup) { this._controls_cleanup(); this._controls_cleanup = null }
if (this.syncarea) { this.syncarea.remove(); this.syncarea = null }
this.blob_client = null
this.innerHTML = ''
}
}
customElements.define('braid-view', BraidView)
})();