-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
262 lines (252 loc) · 14 KB
/
Copy pathindex.html
File metadata and controls
262 lines (252 loc) · 14 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>markmap</title>
<link rel="icon" href="favicon.svg">
<link rel="manifest" href="manifest.json">
<style>
:root{--acc:#7c3aed;--ink:#1a1a2e;--line:#ece9f3;--bg:#faf9fc}
*{box-sizing:border-box} html,body{height:100%}
body{margin:0;background:var(--bg);font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Inter,sans-serif;color:var(--ink);display:flex;flex-direction:column}
header{display:flex;align-items:center;gap:10px;padding:9px 14px;background:#fff;border-bottom:1px solid var(--line)}
.brand{display:flex;align-items:center;gap:8px;font-weight:700}
.brand svg{display:block}
.title{font-weight:600;color:#4b3f63;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.spacer{flex:1}
.chip{font-size:12px;color:#6b7280;text-decoration:none;border:1px solid var(--line);padding:3px 10px;border-radius:999px;background:#fff;font-family:inherit}
.chip:hover{border-color:var(--acc);color:var(--acc)}
button.chip{cursor:pointer}
.chip.primary{background:var(--acc);border-color:var(--acc);color:#fff}
.chip.primary:hover{filter:brightness(1.08);color:#fff}
#saveBtn{display:none}
body.editing #saveBtn{display:inline-block}
#wrap{flex:1;display:flex;min-height:0}
#editorPane{display:none;flex-direction:column;width:0;background:#fff}
body.editing #editorPane{display:flex;width:42%;min-width:280px;border-right:1px solid var(--line)}
#editor{flex:1;border:0;outline:0;resize:none;padding:14px;font:13px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:#2a2440;background:#fff}
#map{flex:1;min-width:0}
svg#mm{width:100%;height:100%;display:block}
.err{padding:30px;color:#9b2c2c;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap}
.toast{position:fixed;left:50%;bottom:26px;transform:translateX(-50%) translateY(20px);background:#241d3d;color:#fff;padding:9px 16px;border-radius:10px;font-size:13px;opacity:0;pointer-events:none;transition:all .25s;z-index:50;max-width:86vw}
.toast.show{opacity:1;transform:translateX(-50%)}
@media (max-width:700px){
body.editing #wrap{flex-direction:column}
body.editing #editorPane{width:100%;min-width:0;height:45%;border-right:0;border-bottom:1px solid var(--line)}
}
</style>
</head>
<body>
<header>
<span class="brand">
<svg width="20" height="20" viewBox="0 0 24 24"><rect width="24" height="24" rx="6" fill="#7c3aed"/><g stroke="#fff" stroke-width="1.6" fill="none" stroke-linecap="round"><path d="M6 12h4M13.5 12 17 7M13.5 12 17 12M13.5 12 17 17"/></g><g fill="#fff"><circle cx="6" cy="12" r="2"/><circle cx="18" cy="7" r="1.5"/><circle cx="18" cy="12" r="1.5"/><circle cx="18" cy="17" r="1.5"/></g></svg>
markmap
</span>
<span class="title" id="docTitle"></span>
<span class="spacer"></span>
<a class="chip" id="srcLink" target="_blank" rel="noopener" style="display:none">source</a>
<button class="chip" id="newBtn" title="Start a new map">New</button>
<button class="chip" id="editBtn" title="Edit the markdown (⌘E)">Edit</button>
<button class="chip primary" id="saveBtn" title="Save to your pod (⌘S)">Save</button>
<button class="chip" id="fitBtn" title="Fit map to window">Fit</button>
</header>
<div id="wrap">
<div id="editorPane"><textarea id="editor" spellcheck="false" placeholder="# Root ## Branch - leaf"></textarea></div>
<div id="map"><svg id="mm"></svg></div>
</div>
<!-- Put your own map here to fork this app: a JSON-LD island with markdown in schema:text.
<script type="application/ld+json" id="markmap-data">
{ "@context": { "schema": "https://schema.org/", "mm": "https://solid-apps.github.io/markmap/ns#" },
"@id": "#this", "@type": "mm:Markmap", "schema:name": "My map",
"schema:text": "# Root\n## Branch\n- leaf" }
</script>
-->
<script src="https://unpkg.com/xlogin"></script>
<script src="vendor/d3.min.js"></script>
<script src="vendor/markmap-view.js"></script>
<script src="vendor/markmap-lib.js"></script>
<script>
(async () => {
const $ = (s) => document.querySelector(s)
const S = (o, ...keys) => { for (const k of keys) { const v = o && o[k]; if (v != null) return v } }
const val = (v) => Array.isArray(v) ? val(v[0]) : (v && typeof v === 'object' && '@value' in v ? v['@value'] : v)
const authFetch = (u, o) => ((window.xlogin && window.xlogin.authFetch) || fetch)(u, o)
function toast(msg) {
let t = document.querySelector('.toast')
if (!t) { t = document.createElement('div'); t.className = 'toast'; document.body.appendChild(t) }
t.textContent = msg; t.classList.add('show')
clearTimeout(t._tid); t._tid = setTimeout(() => t.classList.remove('show'), 2600)
}
const { Transformer, Markmap, deriveOptions } = window.markmap
const MAPS = location.origin + '/public/markmap/' // absolute — xlogin's authFetch rejects relative URLs
const TEMPLATE = '# New map\n\n## First branch\n- a leaf\n- another\n\n## Second branch\n- [a link](https://example.com)\n'
let mm = null // Markmap instance
let MD = '' // current markdown (source of truth while editing)
let FROM = null // { url, kind: 'jsonld'|'md', cross: bool } | null (island/sample/new)
let DIRTY = false
const titleOf = (md) => ((String(md).replace(/^---\n[\s\S]*?\n---\n/, '').match(/^#\s+(.+)$/m) || [])[1] || '').trim()
const slugify = (s) => String(s || '').toLowerCase().replace(/[^\w-]+/g, '-').replace(/^-+|-+$/g, '') || 'map'
const envelope = (md) => ({
'@context': { 'schema': 'https://schema.org/', 'mm': 'https://solid-apps.github.io/markmap/ns#' },
'@id': '#this', '@type': 'mm:Markmap',
'schema:name': titleOf(md) || 'Untitled map',
'schema:text': md
})
function transform(md) {
const res = new Transformer().transform(String(md || ''))
const opts = res.frontmatter && res.frontmatter.markmap ? deriveOptions(res.frontmatter.markmap) : null
return { root: res.root, opts }
}
function renderMap(md) {
const { root, opts } = transform(md)
if (!mm) { mm = Markmap.create($('#mm'), opts, root); return Promise.resolve() }
return mm.setData(root, opts || {})
}
function setHeader() {
const t = titleOf(MD)
$('#docTitle').textContent = t
document.title = (t ? t + ' · ' : '') + 'markmap'
}
// --- load: data island → ?src= (JSON-LD or raw .md) → sample ---------------
async function loadDoc() {
const island = document.getElementById('markmap-data')
if (island && island.textContent.trim()) return { doc: JSON.parse(island.textContent), from: null }
const src = new URLSearchParams(location.search).get('src')
if (src) {
const u = new URL(src, location.href) // absolutize — xlogin's authFetch rejects relative URLs
const cross = u.origin !== location.origin
const r = await authFetch(u.href, { headers: { Accept: 'application/ld+json, application/json, text/markdown, text/plain' } })
if (!r.ok) throw new Error(`load ${src} → ${r.status}`)
const ct = r.headers.get('content-type') || ''
if (ct.includes('json')) return { doc: await r.json(), from: { url: u.href, kind: 'jsonld', cross } }
return { doc: { 'schema:text': await r.text() }, from: { url: u.href, kind: 'md', cross } }
}
const r = await fetch('sample.jsonld')
return { doc: await r.json(), from: null } // sample saves as a new map, never overwrites itself
}
function extract(doc) {
const nodes = doc['@graph'] ? [].concat(doc['@graph']) : [doc]
const hasMd = (x) => S(x, 'schema:text', 'mm:markdown', 'markdown', 'text', 'schema:articleBody', 'https://schema.org/text')
const n = nodes.find((x) => /markmap/i.test(JSON.stringify(x['@type'] || ''))) || nodes.find(hasMd) || nodes[0]
return { md: val(hasMd(n)), tree: S(n, 'mm:root', 'root') }
}
// --- save -------------------------------------------------------------------
function saveFailed(r) {
if (r.status === 401 || r.status === 403) toast('No write access — sign in (pill, bottom-right)')
else toast('Save failed (' + r.status + ')')
}
async function ensureMapsContainer() {
try {
const h = await authFetch(MAPS, { method: 'HEAD' })
if (h.ok) return
await authFetch(MAPS, { method: 'PUT', headers: { 'Content-Type': 'text/turtle', 'Link': '<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"' }, body: '' })
} catch { /* the PUT below will surface any real error */ }
}
async function save() {
if (!FROM || FROM.cross) return saveAs()
const r = FROM.kind === 'md'
? await authFetch(FROM.url, { method: 'PUT', headers: { 'Content-Type': 'text/markdown' }, body: MD })
: await authFetch(FROM.url, { method: 'PUT', headers: { 'Content-Type': 'application/ld+json' }, body: JSON.stringify(envelope(MD), null, 2) })
if (!r.ok) return saveFailed(r)
markSelfWrite(FROM.url)
DIRTY = false; setHeader(); toast('Saved')
}
async function saveAs() {
const name = prompt('Save map as…', slugify(titleOf(MD)))
if (!name) return
const url = MAPS + slugify(name) + '.jsonld'
await ensureMapsContainer()
const r = await authFetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/ld+json' }, body: JSON.stringify(envelope(MD), null, 2) })
if (!r.ok) return saveFailed(r)
markSelfWrite(url)
FROM = { url, kind: 'jsonld', cross: false }
syncSubs()
DIRTY = false; setHeader()
const path = new URL(url).pathname
history.replaceState(null, '', '?src=' + encodeURIComponent(path))
const a = $('#srcLink'); a.href = url; a.style.display = ''
toast('Saved → ' + path)
}
// --- live updates: Solid WS notifications (solid-0.1) -----------------------
// When another client (an agent, another device) changes the map doc we're
// viewing, the pod pushes `pub <uri>` and we re-render in place. Unsaved local
// edits are never clobbered — we warn instead. Map docs are public, so the
// browser WS (which can't send auth headers) subscribes fine.
const SELF_WRITES = {} // url -> ts; ignore our own write-echo
let LIVE = null, SUBBED = new Set()
const markSelfWrite = (url) => { SELF_WRITES[url] = Date.now() }
const wsEndpoint = () => (location.protocol === 'https:' ? 'wss' : 'ws') + '://' + location.host + '/.notifications'
function liveSub(url) { if (!LIVE || LIVE.readyState !== 1 || !url || SUBBED.has(url)) return; LIVE.send('sub ' + url); SUBBED.add(url) }
function syncSubs() { if (FROM && !FROM.cross && FROM.url) liveSub(FROM.url) }
function connectLive() {
let ws
try { ws = new WebSocket(wsEndpoint()) } catch { return }
LIVE = ws
ws.onopen = () => { SUBBED = new Set(); syncSubs() }
ws.onmessage = (e) => { const m = String(e.data || ''); if (m.startsWith('pub ')) onPub(m.slice(4).trim()) }
ws.onerror = () => { try { ws.close() } catch { /* noop */ } }
ws.onclose = () => { LIVE = null; SUBBED = new Set(); setTimeout(connectLive, 3000) }
}
async function onPub(uri) {
if (!FROM || uri !== FROM.url) return
if (SELF_WRITES[uri] && Date.now() - SELF_WRITES[uri] < 2500) return // our own write
if (DIRTY) { toast('Map changed on the pod — your unsaved edits are kept (Save overwrites)'); return }
try {
const r = await authFetch(FROM.url, { headers: { Accept: 'application/ld+json, application/json, text/markdown, text/plain' } })
if (!r.ok) return
const ct = r.headers.get('content-type') || ''
const fresh = ct.includes('json') ? extract(await r.json()).md : await r.text()
if (fresh == null || String(fresh) === MD) return
MD = String(fresh)
await renderMap(MD); setHeader()
if (mm) mm.fit() // keep a growing map in view
if (document.body.classList.contains('editing')) $('#editor').value = MD
toast('Updated from pod')
} catch { /* transient; next pub retries */ }
}
// --- edit -------------------------------------------------------------------
function setEditing(on) {
document.body.classList.toggle('editing', on)
$('#editBtn').textContent = on ? 'View' : 'Edit'
if (on) { $('#editor').value = MD; $('#editor').focus() }
requestAnimationFrame(() => mm && mm.fit())
}
let deb = 0
$('#editor').addEventListener('input', () => {
MD = $('#editor').value; DIRTY = true
clearTimeout(deb); deb = setTimeout(() => { renderMap(MD); setHeader() }, 250)
})
$('#editBtn').onclick = () => setEditing(!document.body.classList.contains('editing'))
$('#saveBtn').onclick = () => save()
$('#newBtn').onclick = () => {
if (DIRTY && !confirm('Discard unsaved changes?')) return
MD = TEMPLATE; FROM = null; DIRTY = true
renderMap(MD); setHeader(); setEditing(true)
history.replaceState(null, '', location.pathname)
$('#srcLink').style.display = 'none'
}
$('#fitBtn').onclick = () => mm && mm.fit()
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); if (document.body.classList.contains('editing')) save() }
if ((e.ctrlKey || e.metaKey) && e.key === 'e') { e.preventDefault(); $('#editBtn').click() }
})
addEventListener('beforeunload', (e) => { if (DIRTY) { e.preventDefault(); e.returnValue = '' } })
// --- boot -------------------------------------------------------------------
try {
if (window.xlogin && window.xlogin.ready) { try { await window.xlogin.ready } catch { /* render anyway */ } }
const { doc, from } = await loadDoc()
const { md, tree } = extract(doc)
FROM = from
if (from && from.url) { const a = $('#srcLink'); a.href = from.url; a.style.display = '' }
if (md) { MD = String(md); renderMap(MD); setHeader() }
else if (tree) { mm = Markmap.create($('#mm'), null, tree); $('#editBtn').style.display = 'none' } // tree docs are view-only
else throw new Error('No markdown (schema:text) or node tree (mm:root) in the document.')
connectLive()
} catch (e) {
document.getElementById('map').innerHTML = '<div class="err">' + String((e && e.message) || e).replace(/</g, '<') + '</div>'
}
})()
</script>
</body>
</html>