pinokiod 8.3.23 → 8.3.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,745 @@
1
+ // The app's Git page (server/views/git_page.ejs), opened as a tab on the app page.
2
+ //
3
+ // Repositories on the left, with their status. The selected repository's four
4
+ // sections on the right: Changes, History, Fork, Publish. Everything is drawn on
5
+ // the page: forms, confirmations and the terminal of a running git script all
6
+ // appear in the section itself. Nothing opens as a popup.
7
+ //
8
+ // The status is checked when the page opens, each time its tab is brought to the
9
+ // front, when Refresh is pressed, and around every action. Never on a timer, and
10
+ // never by watching files.
11
+ //
12
+ // One thing at a time. Reading is always possible. Every action (commit,
13
+ // discard, checkout, fork, create, publish) goes through act(): the page is
14
+ // blocked, the status is read again, and the action only goes ahead if the
15
+ // repository still looks the way it did when the button was pressed. The page
16
+ // stays blocked until the action is over and the status has been read once more.
17
+ (() => {
18
+ const root = document.getElementById('git-page')
19
+ if (!root) {
20
+ return
21
+ }
22
+ const appName = root.dataset.name || ''
23
+ const appCwd = root.dataset.cwd || ''
24
+ const SECTIONS = ['changes', 'history', 'fork', 'publish']
25
+
26
+ const state = {
27
+ repos: [], // from the last check
28
+ checkedAt: 0,
29
+ checking: null, // the check in flight; resolves to whether the status could be read
30
+ error: '', // the repositories could not be loaded
31
+ notice: '', // what became of the last action, when it did not simply succeed
32
+ repoKey: null, // selected repository
33
+ section: root.dataset.publish === '1' ? 'publish' : 'changes',
34
+ info: new Map(), // repoKey -> history data (commits, branches, remote, GitHub state)
35
+ views: new Map(), // repoKey -> its Changes section: { listed, ticked:Set|null, open:index, message, messageEdited, confirmReset: the look the discard was asked for }
36
+ commit: null, // the History section's open commit: { key, oid, title, changes, open }
37
+ forms: new Map(), // repoKey -> what was typed into its Fork and Publish forms
38
+ consent: null, // "Continue without committing", for one publish: { key, seen }
39
+ diffs: new Map(), // diff address -> its request, kept until the next check
40
+ work: null, // the action in progress: { title, note, url (a script's terminal), finished }
41
+ }
42
+
43
+ // ---------------------------------------------------------------- helpers
44
+ const h = (tag, props, ...children) => {
45
+ const node = document.createElement(tag)
46
+ Object.entries(props || {}).forEach(([key, value]) => {
47
+ if (value === false || value === null || value === undefined) return
48
+ if (key === 'class') node.className = value
49
+ else if (key === 'text') node.textContent = value
50
+ else if (key.startsWith('on')) node.addEventListener(key.slice(2), value)
51
+ else if (key in node) node[key] = value
52
+ else node.setAttribute(key, value)
53
+ })
54
+ children.flat().forEach((child) => {
55
+ if (child === false || child === null || child === undefined) return
56
+ node.append(child.nodeType ? child : document.createTextNode(String(child)))
57
+ })
58
+ return node
59
+ }
60
+ const icon = (name) => h('i', { class: name, 'aria-hidden': 'true' })
61
+ const button = (label, onclick, options = {}) => h('button', {
62
+ type: 'button',
63
+ class: `git-btn${options.primary ? ' git-btn--primary' : ''}${options.danger ? ' git-btn--danger' : ''}`,
64
+ disabled: Boolean(options.disabled),
65
+ title: options.title || null,
66
+ onclick,
67
+ }, options.icon ? icon(options.icon) : null, label)
68
+ const notice = (title, text, ...actions) => h('div', { class: 'git-notice' },
69
+ h('div', { class: 'git-notice-title', text: title }),
70
+ text ? h('div', { class: 'git-notice-text', text }) : null,
71
+ actions.length ? h('div', { class: 'git-notice-actions' }, actions) : null)
72
+
73
+ const encodeRepoPath = (value) => String(value || '').split('/').map(encodeURIComponent).join('/')
74
+ const isOid = (value) => typeof value === 'string' && /^[0-9a-f]{7,40}$/i.test(value)
75
+ const isUntracked = (status) => /new|add|untracked/i.test(status || '')
76
+ const shellQuote = (value) => `"${String(value).replace(/(["`$\\])/g, '\\$1')}"`
77
+ // a changed file's identity, a repository's list of them, and how the
78
+ // repository looks: the same list with each file's status
79
+ const keyOf = (change) => change.path || change.file
80
+ const listedOf = (entry) => (Array.isArray(entry.changes) ? entry.changes : []).map(keyOf).join('\n')
81
+ const lookOf = (entry) => (Array.isArray(entry.changes) ? entry.changes : []).map((change) => `${keyOf(change)}\t${change.status}`).join('\n')
82
+ const formOf = (entry) => {
83
+ if (!state.forms.has(entry.repoParam)) state.forms.set(entry.repoParam, {})
84
+ return state.forms.get(entry.repoParam)
85
+ }
86
+ const getJson = async (url) => {
87
+ const response = await fetch(url, { cache: 'no-store' })
88
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
89
+ return response.json()
90
+ }
91
+ const repo = () => state.repos.find((entry) => entry.repoParam === state.repoKey) || null
92
+ const hasRemote = (entry) => Boolean(entry && typeof entry.url === 'string' && entry.url.trim())
93
+ const cwdOf = (entry) => {
94
+ const info = entry ? state.info.get(entry.repoParam) : null
95
+ if (info && info.dir) return info.dir
96
+ const source = entry && (entry.git_push_url || entry.git_commit_url)
97
+ if (source) {
98
+ try {
99
+ const cwd = new URL(source, window.location.origin).searchParams.get('cwd')
100
+ if (cwd) return cwd
101
+ } catch (_) {}
102
+ }
103
+ return appCwd
104
+ }
105
+ const scriptUrl = (name, cwd, params = {}) => {
106
+ const query = new URLSearchParams({ cwd, ...params })
107
+ return `/run/scripts/git/${name}.json?${query.toString()}`
108
+ }
109
+ // a script that tells the page when it is done
110
+ const callbackUrl = (name, cwd, params = {}) => `${scriptUrl(name, cwd, params)}&callback_target=parent&callback=$location.href`
111
+
112
+ const remoteWebUrl = (remoteUrl) => {
113
+ const raw = typeof remoteUrl === 'string' ? remoteUrl.trim() : ''
114
+ if (!raw) return ''
115
+ if (/^https?:\/\//i.test(raw)) return raw.replace(/\.git$/i, '')
116
+ const ssh = raw.match(/^(?:ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+?)(?:\.git)?$/i)
117
+ if (ssh) return `https://${ssh[1]}/${ssh[2]}`
118
+ const scp = raw.match(/^(?:[^@]+@)?([^:/]+):(.+?)(?:\.git)?$/)
119
+ if (scp) return `https://${scp[1]}/${scp[2]}`
120
+ return ''
121
+ }
122
+ const openExternal = (url) => {
123
+ const agent = document.body.getAttribute('data-agent')
124
+ window.open(url, '_blank', agent === 'electron' ? 'browser' : undefined)
125
+ }
126
+ const forkDefaultName = (entry) => {
127
+ const web = remoteWebUrl(entry && entry.url)
128
+ const fromRemote = web.split('/').filter(Boolean).pop()
129
+ if (fromRemote) return fromRemote
130
+ const fromName = String((entry && (entry.name || entry.repoParam)) || '').split('/').filter(Boolean).pop()
131
+ return fromName || appName || 'fork'
132
+ }
133
+ const suggestMessage = (changes) => {
134
+ if (!changes.length) return 'Update files'
135
+ const groups = { Add: [], Update: [], Delete: [], Rename: [] }
136
+ changes.forEach((change) => {
137
+ const status = String(change.status || '').toLowerCase()
138
+ if (status.includes('new') || status.includes('add')) groups.Add.push(change.file)
139
+ else if (status.includes('delete') || status.includes('remove')) groups.Delete.push(change.file)
140
+ else if (status.includes('rename') || status.includes('moved')) groups.Rename.push(change.file)
141
+ else groups.Update.push(change.file)
142
+ })
143
+ return Object.entries(groups)
144
+ .filter(([, files]) => files.length)
145
+ .map(([verb, files]) => (files.length === 1 ? `${verb} ${files[0]}` : `${verb} ${files.length} files`))
146
+ .join(', ')
147
+ }
148
+
149
+ // ------------------------------------------------------------------ data
150
+ // A repository's commit draft is its ticks and its typed message. After every
151
+ // read of the status each draft is brought in line with the files, whichever
152
+ // section is showing. A draft carries over while there are files left to
153
+ // commit; once there are none it starts over. Ticks are null until a tick is
154
+ // changed or a message is typed, which means "every file". From then on they
155
+ // are the files that were ticked, so a file that turns up later is never
156
+ // ticked by itself.
157
+ const syncDrafts = () => state.repos.forEach((entry) => {
158
+ const changes = Array.isArray(entry.changes) ? entry.changes : []
159
+ const listed = listedOf(entry)
160
+ const before = state.views.get(entry.repoParam)
161
+ if (before && before.listed === listed) return
162
+ const draft = before && changes.length ? before : null
163
+ const present = new Set(changes.map(keyOf))
164
+ state.views.set(entry.repoParam, {
165
+ listed,
166
+ ticked: draft && draft.ticked ? new Set([...draft.ticked].filter((key) => present.has(key))) : null,
167
+ open: changes.length ? 0 : -1,
168
+ message: draft && draft.messageEdited ? draft.message : '',
169
+ messageEdited: Boolean(draft && draft.messageEdited),
170
+ confirmReset: '',
171
+ })
172
+ })
173
+ const check = () => {
174
+ if (state.checking) return state.checking
175
+ state.checking = (async () => {
176
+ let read = false
177
+ try {
178
+ const data = await getJson(`/info/gitstatus/${encodeURIComponent(appName)}?force=1`)
179
+ let repos = Array.isArray(data.repos) ? data.repos : []
180
+ if (repos.length === 0) {
181
+ // a folder with no repository in it
182
+ repos = [{ name: appName, main: true, repoParam: appName, changeCount: 0, changes: [], url: null, noRepo: true }]
183
+ }
184
+ repos.sort((a, b) => (a.main === b.main ? String(a.name).localeCompare(String(b.name)) : (a.main ? -1 : 1)))
185
+ state.repos = repos
186
+ state.error = ''
187
+ if (!repos.some((entry) => entry.repoParam === state.repoKey)) {
188
+ state.repoKey = repos[0] ? repos[0].repoParam : null
189
+ }
190
+ // a repository that is gone takes everything remembered about it with it,
191
+ // so one that later turns up under the same name starts clean
192
+ const present = new Set(repos.map((entry) => entry.repoParam))
193
+ ;[state.views, state.forms].forEach((map) => [...map.keys()].forEach((key) => present.has(key) || map.delete(key)))
194
+ if (state.consent && !present.has(state.consent.key)) state.consent = null
195
+ if (state.commit && !present.has(state.commit.key)) state.commit = null
196
+ read = true
197
+ } catch (error) {
198
+ try {
199
+ // the scan of every repository failed: the app's own repository on its own, to look at
200
+ const own = await getJson(`/gitcommit/HEAD/${encodeRepoPath(appName)}`)
201
+ const changes = Array.isArray(own.changes) ? own.changes : []
202
+ state.repos = [{ name: appName, main: true, repoParam: appName, changeCount: changes.length, changes, git_commit_url: own.git_commit_url || null, url: null }]
203
+ state.repoKey = appName
204
+ state.error = ''
205
+ } catch (_) {
206
+ // nothing could be read: what was on the page is no longer known to be true, so it goes
207
+ state.repos = []
208
+ state.error = 'Could not load the repositories.'
209
+ }
210
+ }
211
+ syncDrafts()
212
+ state.info.clear()
213
+ state.diffs.clear()
214
+ state.checkedAt = Date.now()
215
+ state.checking = null
216
+ render()
217
+ return read
218
+ })()
219
+ render()
220
+ return state.checking
221
+ }
222
+
223
+ // History data for a repository: commits, branches, remote and whether GitHub
224
+ // is connected. Loaded when a section first needs it, null until it arrives,
225
+ // kept until the next check.
226
+ const infoOf = (key) => {
227
+ const known = state.info.get(key)
228
+ if (known) return known.pending ? null : known
229
+ const marker = { pending: true }
230
+ state.info.set(key, marker)
231
+ getJson(`/info/git/HEAD/${encodeRepoPath(key)}`)
232
+ .catch(() => ({ failed: true }))
233
+ .then((data) => {
234
+ // a check since then has thrown this request away
235
+ if (state.info.get(key) === marker) {
236
+ state.info.set(key, data)
237
+ render()
238
+ }
239
+ })
240
+ return null
241
+ }
242
+
243
+ // ------------------------------------------------------------ taking action
244
+ // The status has been read again after an action; the page is released.
245
+ const finish = async (problem) => {
246
+ state.work = { title: state.work.title, note: 'Refreshing...' }
247
+ render()
248
+ await check()
249
+ state.work = null
250
+ state.consent = null
251
+ state.notice = problem || ''
252
+ render()
253
+ }
254
+ // The one way to do anything. `perform(entry)` gets the repository as it is
255
+ // now. It returns, or resolves to, the address of a git script, which then
256
+ // runs in Pinokio's terminal view in the section; or to nothing, when it made
257
+ // its request directly. If it throws, nothing more is done and its message is shown.
258
+ const act = async (title, entry, perform) => {
259
+ if (state.work) return
260
+ const key = entry.repoParam
261
+ const seen = lookOf(entry)
262
+ state.work = { title, note: 'Checking...' }
263
+ state.notice = ''
264
+ render()
265
+ // a check already under way began before the button was pressed: it does not count
266
+ await state.checking
267
+ const read = await check()
268
+ const now = state.repos.find((item) => item.repoParam === key)
269
+ if (!read || !now || now.error || now.noRepo) {
270
+ state.work = null
271
+ state.notice = 'The repository could not be checked, so nothing was done.'
272
+ } else if (lookOf(now) !== seen) {
273
+ state.work = null
274
+ state.consent = null
275
+ state.notice = 'The files changed since this was shown, so nothing was done. Look again, then retry.'
276
+ } else {
277
+ state.work = { title, note: 'Working...' }
278
+ render()
279
+ let started
280
+ try {
281
+ started = await perform(now)
282
+ } catch (error) {
283
+ return finish(error.message)
284
+ }
285
+ if (typeof started !== 'string') return finish()
286
+ state.work = { title, url: started, finished: false }
287
+ }
288
+ render()
289
+ }
290
+ // For publish and checkout: the history is read again, and the folder to run
291
+ // in is the one it names. A folder whose repository cannot be read is refused,
292
+ // because git would go on to use whatever repository contains it. Publish
293
+ // also needs the current branch to have a commit; checkout does not, since it
294
+ // is how a branch with none is left.
295
+ const folderOf = async (now, needsCommit) => {
296
+ const info = await getJson(`/info/git/HEAD/${encodeRepoPath(now.repoParam)}`).catch(() => null)
297
+ const hasHead = info && (typeof info.hasHead === 'boolean' ? info.hasHead : Array.isArray(info.log) && info.log.length > 0)
298
+ if (!info || info.gitDirExists === false || (needsCommit && !hasHead)) {
299
+ throw new Error('This repository could not be read, so nothing was done.')
300
+ }
301
+ return info.dir || cwdOf(now)
302
+ }
303
+ window.addEventListener('message', (event) => {
304
+ const data = event.data
305
+ if (!data) return
306
+ if (event.source === window.parent && window.parent !== window) {
307
+ // the app page tells the tab it brings to the front
308
+ if (data.action === 'foreground' && !state.work && Date.now() - state.checkedAt > 2000) {
309
+ check()
310
+ }
311
+ return
312
+ }
313
+ if (!state.work || !state.work.url) return
314
+ if (typeof data.callback === 'string' && data.callback.startsWith('$')) {
315
+ // a script that reports back (commit, checkout) is over
316
+ finish()
317
+ } else if (data.type === 'disconnect') {
318
+ // the others show their output until Close is pressed
319
+ state.work.finished = true
320
+ const footer = root.querySelector('.git-run-status')
321
+ if (footer) footer.textContent = 'Finished.'
322
+ }
323
+ })
324
+ const workPanel = () => (state.work.url
325
+ ? h('div', { class: 'git-run' },
326
+ h('div', { class: 'git-run-header' },
327
+ h('div', { class: 'git-run-title', text: state.work.title }),
328
+ h('div', { class: 'git-run-status', text: state.work.finished ? 'Finished.' : '' }),
329
+ button('Close', () => finish())),
330
+ h('iframe', { class: 'git-run-frame', src: state.work.url, allow: 'fullscreen *' }))
331
+ : h('div', { class: 'git-empty', text: `${state.work.title}: ${state.work.note}` }))
332
+
333
+ // ------------------------------------------------------------- file diffs
334
+ const diffLines = (data) => {
335
+ if (data.binary) return h('div', { class: 'git-empty', text: 'Binary file' })
336
+ if (!Array.isArray(data.diff) || data.diff.length === 0) {
337
+ return h('div', { class: 'git-empty', text: 'No changes to display' })
338
+ }
339
+ return h('div', { class: 'git-diff-lines' }, data.diff.map((line) => h('div', {
340
+ class: `git-diff-line${line.type === 'add' ? ' git-diff-line--add' : line.type === 'del' ? ' git-diff-line--del' : ''}`,
341
+ },
342
+ h('span', { class: 'git-diff-num', text: line.lineOld === null || line.lineOld === undefined ? '' : String(line.lineOld) }),
343
+ h('span', { class: 'git-diff-num', text: line.lineNew === null || line.lineNew === undefined ? '' : String(line.lineNew) }),
344
+ h('span', { class: 'git-diff-code', text: line.line }))))
345
+ }
346
+ // The diff of one changed file, with a button that opens the file itself.
347
+ const diffViewer = (change, repoKey) => {
348
+ const body = h('div', { class: 'git-diff-body' }, h('div', { class: 'git-empty', text: 'Loading...' }))
349
+ if (!state.diffs.has(change.diffpath)) {
350
+ state.diffs.set(change.diffpath, getJson(change.diffpath))
351
+ }
352
+ state.diffs.get(change.diffpath)
353
+ .then((data) => body.replaceChildren(diffLines(data)))
354
+ .catch(() => body.replaceChildren(h('div', { class: 'git-empty', text: 'Could not load the diff' })))
355
+ const relative = String(change.file || '').split('/').map(encodeURIComponent).join('/')
356
+ return h('div', { class: 'git-diff' },
357
+ h('div', { class: 'git-diff-header' },
358
+ h('div', { class: 'git-diff-title', text: change.file }),
359
+ button('Open in explorer', () => { fetch(`/api/${encodeRepoPath(repoKey)}/${relative}?fs=view`).catch(() => {}) }, { icon: 'fa-solid fa-folder-open' })),
360
+ body)
361
+ }
362
+
363
+ // ---------------------------------------------------------------- Changes
364
+ const changesSection = (entry) => {
365
+ if (entry.noRepo) {
366
+ return h('div', { class: 'git-empty', text: 'This folder is not a Git repository yet.' })
367
+ }
368
+ if (entry.error) {
369
+ return h('div', { class: 'git-error', text: `Could not read this repository's status: ${entry.error}` })
370
+ }
371
+ const changes = Array.isArray(entry.changes) ? entry.changes : []
372
+ const view = state.views.get(entry.repoParam)
373
+ if (changes.length === 0) {
374
+ return h('div', { class: 'git-empty', text: 'No changes. Everything is committed.' })
375
+ }
376
+ const isTicked = (change) => !view.ticked || view.ticked.has(keyOf(change))
377
+ const picked = changes.filter(isTicked)
378
+ if (!view.messageEdited) {
379
+ view.message = suggestMessage(picked)
380
+ }
381
+ const tracked = picked.filter((change) => !isUntracked(change.status)).map(keyOf)
382
+ const untracked = picked.filter((change) => isUntracked(change.status)).map(keyOf)
383
+
384
+ const selectAll = h('input', {
385
+ type: 'checkbox',
386
+ checked: picked.length === changes.length,
387
+ onchange: (event) => {
388
+ view.ticked = new Set(event.target.checked ? changes.map(keyOf) : [])
389
+ view.confirmReset = ''
390
+ render()
391
+ },
392
+ })
393
+ selectAll.indeterminate = picked.length > 0 && picked.length < changes.length
394
+
395
+ const files = h('div', { class: 'git-files' },
396
+ h('label', { class: 'git-file git-file--all' }, selectAll, h('span', { class: 'git-file-name', text: 'Select all' })),
397
+ changes.map((change, index) => h('div', {
398
+ class: `git-file${view.open === index ? ' git-file--open' : ''}`,
399
+ onclick: () => { view.open = index; render() },
400
+ },
401
+ h('input', {
402
+ type: 'checkbox',
403
+ checked: isTicked(change),
404
+ onclick: (event) => event.stopPropagation(),
405
+ onchange: (event) => {
406
+ view.ticked = new Set(picked.map(keyOf))
407
+ if (event.target.checked) view.ticked.add(keyOf(change))
408
+ else view.ticked.delete(keyOf(change))
409
+ view.confirmReset = ''
410
+ view.open = index
411
+ render()
412
+ },
413
+ }),
414
+ h('span', { class: 'git-file-name', text: change.file, title: change.file }),
415
+ h('span', { class: 'git-file-status', text: change.status }))),
416
+ h('div', { class: 'git-files-actions' },
417
+ view.confirmReset && view.confirmReset === lookOf(entry)
418
+ ? h('div', { class: 'git-confirm' },
419
+ h('div', { class: 'git-confirm-text', text: `Discard the changes in ${picked.length} file${picked.length === 1 ? '' : 's'}? This cannot be undone.` }),
420
+ button('Discard', () => {
421
+ view.confirmReset = ''
422
+ act(`Discarding ${picked.length} file${picked.length === 1 ? '' : 's'}`, entry, async (now) => {
423
+ const response = await fetch('/terminals/git/reset-files', {
424
+ method: 'POST',
425
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
426
+ body: JSON.stringify({ cwd: cwdOf(now), tracked_paths: tracked, untracked_paths: untracked }),
427
+ })
428
+ const payload = await response.json().catch(() => null)
429
+ if (!response.ok || !payload || payload.ok !== true) {
430
+ throw new Error(payload && payload.error ? payload.error : 'Failed to reset selected files.')
431
+ }
432
+ })
433
+ }, { danger: true }),
434
+ button('Cancel', () => { view.confirmReset = ''; render() }))
435
+ : button(`Reset selected (${picked.length})`, () => { view.confirmReset = lookOf(entry); render() }, {
436
+ icon: 'fa-solid fa-arrow-rotate-left',
437
+ disabled: picked.length === 0,
438
+ })))
439
+
440
+ const messageInput = h('input', {
441
+ type: 'text',
442
+ class: 'git-input',
443
+ id: 'git-commit-message',
444
+ value: view.message,
445
+ placeholder: 'Commit message',
446
+ 'aria-label': 'Commit message',
447
+ oninput: (event) => {
448
+ view.message = event.target.value
449
+ view.messageEdited = true
450
+ view.ticked = new Set(picked.map(keyOf))
451
+ },
452
+ })
453
+ const commit = () => act(`Committing ${picked.length} file${picked.length === 1 ? '' : 's'}`, entry, (now) => {
454
+ const params = { message: view.message.trim() || suggestMessage(picked) }
455
+ if (tracked.length) params.paths = tracked.map(shellQuote).join(' ')
456
+ if (untracked.length) params.untracked_paths = untracked.map(shellQuote).join(' ')
457
+ // the message is used up
458
+ view.message = ''
459
+ view.messageEdited = false
460
+ return callbackUrl('commit_files', cwdOf(now), params)
461
+ })
462
+ return h('div', { class: 'git-changes' },
463
+ h('div', { class: 'git-split' },
464
+ files,
465
+ view.open >= 0 && changes[view.open] ? diffViewer(changes[view.open], entry.repoParam) : h('div', { class: 'git-empty', text: 'Select a file to view its changes' })),
466
+ h('div', { class: 'git-commit-bar' },
467
+ messageInput,
468
+ button('Commit', commit, { primary: true, disabled: picked.length === 0, title: picked.length === 0 ? 'Select at least one file' : null })))
469
+ }
470
+
471
+ // ---------------------------------------------------------------- History
472
+ const commitView = (entry) => {
473
+ const view = state.commit
474
+ const checkout = () => act(`Checking out ${view.oid.slice(0, 7)}`, entry, async (now) => {
475
+ const cwd = await folderOf(now, false)
476
+ state.commit = null
477
+ return callbackUrl('checkout', cwd, { commit: view.oid })
478
+ })
479
+ return h('div', { class: 'git-commit' },
480
+ h('div', { class: 'git-commit-header' },
481
+ button('History', () => { state.commit = null; render() }, { icon: 'fa-solid fa-arrow-left' }),
482
+ h('div', { class: 'git-commit-title', text: view.title, title: view.title }),
483
+ h('code', { class: 'git-oid', text: view.oid.slice(0, 7) }),
484
+ button('Check out this commit', checkout, { icon: 'fa-solid fa-clock-rotate-left' })),
485
+ !view.changes
486
+ ? h('div', { class: 'git-empty', text: view.failed ? 'Could not load this commit' : 'Loading...' })
487
+ : view.changes.length === 0
488
+ ? h('div', { class: 'git-empty', text: 'No file changes in this commit' })
489
+ : h('div', { class: 'git-split' },
490
+ h('div', { class: 'git-files' }, view.changes.map((change, index) => h('div', {
491
+ class: `git-file${view.open === index ? ' git-file--open' : ''}`,
492
+ onclick: () => { view.open = index; render() },
493
+ },
494
+ h('span', { class: 'git-file-name', text: change.file, title: change.file }),
495
+ h('span', { class: 'git-file-status', text: change.status })))),
496
+ diffViewer(view.changes[view.open], entry.repoParam)))
497
+ }
498
+ const openCommit = (entry, item) => {
499
+ const view = { key: entry.repoParam, oid: item.oid, title: String(item.commit.message || '').split('\n')[0], changes: null, open: 0 }
500
+ state.commit = view
501
+ render()
502
+ getJson(item.info)
503
+ .then((data) => { view.changes = Array.isArray(data.changes) ? data.changes : [] })
504
+ .catch(() => { view.failed = true })
505
+ .then(() => { if (state.commit === view) render() })
506
+ }
507
+ const historySection = (entry) => {
508
+ if (state.commit && state.commit.key === entry.repoParam) return commitView(entry)
509
+ const info = infoOf(entry.repoParam)
510
+ if (!info) return h('div', { class: 'git-empty', text: 'Loading history...' })
511
+ if (info.failed) return h('div', { class: 'git-empty', text: 'Could not load the history' })
512
+ const commits = Array.isArray(info.log) ? info.log : []
513
+ const branches = (Array.isArray(info.branches) ? info.branches : [])
514
+ .map((item) => item && item.branch)
515
+ .filter((name) => typeof name === 'string' && name && !isOid(name))
516
+ const current = typeof info.branch === 'string' && !isOid(info.branch) && info.branch !== 'HEAD' ? info.branch : null
517
+ const checkout = (target) => act(`Checking out ${target}`, entry, async (now) => callbackUrl('checkout', await folderOf(now, false), { commit: target }))
518
+ const newest = current || ['main', 'master', 'develop', 'dev'].find((name) => branches.includes(name)) || branches[0] || null
519
+ const select = branches.length
520
+ ? h('select', { class: 'git-input git-input--select', 'aria-label': 'Switch branch', title: 'Switch branch', onchange: (event) => checkout(event.target.value) },
521
+ branches.includes(current) ? null : h('option', { value: '', selected: true, disabled: true, text: 'Switch branch...' }),
522
+ branches.map((name) => h('option', { value: name, selected: name === current, text: name })))
523
+ : null
524
+ const web = remoteWebUrl(info.remote)
525
+ const last = commits[0]
526
+ const summary = [`${commits.length} commit${commits.length === 1 ? '' : 's'}`]
527
+ if (last && window.timeago) summary.push(`Updated ${timeago.format(new Date(last.commit.author.timestamp * 1000))}`)
528
+ return h('div', { class: 'git-history' },
529
+ h('div', { class: 'git-history-bar' },
530
+ h('div', { class: 'git-history-summary' },
531
+ h('span', { text: summary.join(' · ') }),
532
+ web ? h('a', { class: 'git-link', href: web, text: web.replace(/^https?:\/\//, ''), onclick: (event) => { event.preventDefault(); openExternal(web) } }) : null),
533
+ h('div', { class: 'git-history-viewing', text: `Currently viewing ${current || info.ref || 'HEAD'}` }),
534
+ button('Return to newest commit', () => checkout(newest), { icon: 'fa-solid fa-arrow-rotate-left', disabled: !newest }),
535
+ select),
536
+ commits.length === 0
537
+ ? h('div', { class: 'git-empty', text: info.logError ? 'No commits yet' : 'No commits' })
538
+ : h('div', { class: 'git-commits' }, commits.map((item) => h('button', {
539
+ type: 'button',
540
+ class: 'git-commit-row',
541
+ title: String(item.commit.message || '').trim(),
542
+ onclick: () => openCommit(entry, item),
543
+ },
544
+ h('div', { class: 'git-commit-message', text: String(item.commit.message || '').split('\n')[0] }),
545
+ h('div', { class: 'git-commit-meta' },
546
+ h('span', { text: item.commit.author.name }),
547
+ window.timeago ? h('span', { text: timeago.format(new Date(item.commit.author.timestamp * 1000)) }) : null,
548
+ h('code', { class: 'git-oid', text: item.oid.slice(0, 7) }))))))
549
+ }
550
+
551
+ // ------------------------------------------------------- Fork and Publish
552
+ const loginNotice = (purpose) => notice(
553
+ 'Log in to GitHub',
554
+ `Connect your GitHub account to ${purpose}.`,
555
+ button('Log in', () => { window.parent.location.href = '/github' }, { primary: true, icon: 'fa-brands fa-github' }))
556
+
557
+ // whether GitHub is connected could not be found out
558
+ const unknownNotice = (entry) => notice('Unable to check repository state', 'The request for it failed.',
559
+ button('Try again', () => { state.info.delete(entry.repoParam); render() }, { primary: true }))
560
+
561
+ const forkSection = (entry) => {
562
+ const info = infoOf(entry.repoParam)
563
+ if (!info) return h('div', { class: 'git-empty', text: 'Loading...' })
564
+ if (info.failed) return unknownNotice(entry)
565
+ if (!info.connected) return loginNotice('fork this repository')
566
+ if (!hasRemote(entry)) {
567
+ return notice('Remote required', 'This repository does not have a remote configured, so it cannot be forked.')
568
+ }
569
+ const form = formOf(entry)
570
+ const name = h('input', { type: 'text', class: 'git-input', id: 'git-fork-name', value: typeof form.forkName === 'string' ? form.forkName : forkDefaultName(entry), oninput: (event) => { form.forkName = event.target.value } })
571
+ const org = h('input', { type: 'text', class: 'git-input', id: 'git-fork-org', value: form.org || '', placeholder: 'Organization name', 'aria-label': 'Organization name', oninput: (event) => { form.org = event.target.value } })
572
+ const orgRow = h('div', { class: 'git-field', hidden: !form.toOrg }, org)
573
+ const toOrg = h('input', { type: 'checkbox', checked: Boolean(form.toOrg), onchange: (event) => { form.toOrg = event.target.checked; orgRow.hidden = !form.toOrg; if (form.toOrg) org.focus() } })
574
+ const error = h('div', { class: 'git-error', hidden: true })
575
+ const submit = () => {
576
+ const forkName = name.value.trim()
577
+ const orgName = toOrg.checked ? org.value.trim() : ''
578
+ if (!forkName || (toOrg.checked && !orgName)) {
579
+ error.textContent = !forkName ? 'Enter a repository name for the fork' : 'Enter the organization name or uncheck the option'
580
+ error.hidden = false
581
+ return
582
+ }
583
+ const params = { name: forkName, ts: Date.now() }
584
+ if (orgName) params.org = orgName
585
+ act(`Forking ${entry.name} as ${forkName}`, entry, (now) => scriptUrl('fork', cwdOf(now), params))
586
+ }
587
+ return h('div', { class: 'git-form' },
588
+ h('div', { class: 'git-form-title', text: 'Fork repository' }),
589
+ h('div', { class: 'git-form-remote', text: entry.url }),
590
+ h('label', { class: 'git-label', for: 'git-fork-name', text: 'Fork name' }),
591
+ h('div', { class: 'git-field' }, name),
592
+ h('label', { class: 'git-check' }, toOrg, 'Fork into organization'),
593
+ orgRow,
594
+ error,
595
+ h('div', { class: 'git-form-actions' }, button('Fork on GitHub', submit, { primary: true, icon: 'fa-brands fa-github' })))
596
+ }
597
+
598
+ const publishSection = (entry) => {
599
+ const info = infoOf(entry.repoParam)
600
+ if (!info) return h('div', { class: 'git-empty', text: 'Loading...' })
601
+ if (info.failed) return unknownNotice(entry)
602
+ // nothing is offered for publishing until the files have been checked as they are now
603
+ if (state.checking) return h('div', { class: 'git-empty', text: 'Checking for changes...' })
604
+ if (!info.connected) return loginNotice('publish this workspace')
605
+ if (entry.noRepo || info.gitDirExists === false) {
606
+ return notice(`${entry.name} isn't a Git repository yet`, 'Initialize git in this folder and save a version before publishing.')
607
+ }
608
+ const review = button('Review files', () => { state.section = 'changes'; render() }, { primary: true })
609
+ const hasHead = typeof info.hasHead === 'boolean' ? info.hasHead : (Array.isArray(info.log) && info.log.length > 0)
610
+ if (!hasHead) {
611
+ return notice(`Create your first commit for ${entry.name}`, 'Save a version on the main branch before publishing to GitHub.', review)
612
+ }
613
+ const count = Number(entry.changeCount) || 0
614
+ // "Continue without committing" holds for one publish, of the files exactly as they were when it was pressed
615
+ const consented = state.consent && state.consent.key === entry.repoParam && state.consent.seen === lookOf(entry)
616
+ if (count > 0 && !consented) {
617
+ return notice(
618
+ `${count} uncommitted change${count === 1 ? '' : 's'}`,
619
+ 'Commit them first if you want them included in what you publish.',
620
+ button('Review and commit', () => { state.section = 'changes'; render() }, { primary: true }),
621
+ button('Continue without committing', () => { state.consent = { key: entry.repoParam, seen: lookOf(entry) }; render() }))
622
+ }
623
+ if (!hasRemote(entry)) {
624
+ const form = formOf(entry)
625
+ const name = h('input', { type: 'text', class: 'git-input', id: 'git-create-name', value: form.createName || '', placeholder: 'Enter repository name', oninput: (event) => { form.createName = event.target.value } })
626
+ const isPrivate = h('input', { type: 'checkbox', checked: Boolean(form.isPrivate), onchange: (event) => { form.isPrivate = event.target.checked } })
627
+ const error = h('div', { class: 'git-error', hidden: true, text: 'Repository name is required' })
628
+ const submit = () => {
629
+ const repoName = name.value.trim()
630
+ if (!repoName) {
631
+ error.hidden = false
632
+ return
633
+ }
634
+ const visibility = isPrivate.checked ? 'private' : 'public'
635
+ act(`Creating ${repoName} on GitHub`, entry, (now) => scriptUrl('create', cwdOf(now), { name: repoName, visibility }))
636
+ }
637
+ return h('div', { class: 'git-form' },
638
+ h('div', { class: 'git-form-title', text: 'Create a GitHub repository' }),
639
+ h('div', { class: 'git-form-remote', text: `${entry.name} has no remote yet. Create one on GitHub to publish it.` }),
640
+ h('label', { class: 'git-label', for: 'git-create-name', text: 'Repository name' }),
641
+ h('div', { class: 'git-field' }, name),
642
+ h('label', { class: 'git-check' }, isPrivate, 'Private repository'),
643
+ error,
644
+ h('div', { class: 'git-form-actions' }, button('Create on GitHub', submit, { primary: true, icon: 'fa-brands fa-github' })))
645
+ }
646
+ const web = remoteWebUrl(entry.url)
647
+ return h('div', { class: 'git-form' },
648
+ h('div', { class: 'git-form-title', text: 'Publish to GitHub' }),
649
+ h('div', { class: 'git-form-remote', text: entry.url }),
650
+ h('div', { class: 'git-notice-text', text: 'Pushes your committed changes to this remote.' }),
651
+ h('div', { class: 'git-form-actions' },
652
+ button('Publish', () => act(`Publishing ${entry.name}`, entry, async (now) => scriptUrl('push', await folderOf(now, true), { ts: Date.now() })), { primary: true, icon: 'fa-brands fa-github' }),
653
+ web ? button('View on GitHub', () => openExternal(web)) : null))
654
+ }
655
+
656
+ // ----------------------------------------------------------------- render
657
+ const sectionBody = (entry) => {
658
+ if (state.work) return workPanel()
659
+ if (state.section === 'history') return historySection(entry)
660
+ if (state.section === 'fork') return forkSection(entry)
661
+ if (state.section === 'publish') return publishSection(entry)
662
+ return changesSection(entry)
663
+ }
664
+ const render = () => {
665
+ // a running script's terminal is left alone: drawing it again would start the script again
666
+ if (state.work && state.work.url && root.querySelector('.git-run-frame')) return
667
+ // the field being typed in keeps the focus and the cursor across a redraw (its text is in the state)
668
+ const active = document.activeElement
669
+ const typing = active && root.contains(active) && active.id && active.type === 'text'
670
+ ? { id: active.id, start: active.selectionStart, end: active.selectionEnd }
671
+ : null
672
+ const entry = repo()
673
+ const checked = state.checking
674
+ ? 'Checking...'
675
+ : state.checkedAt
676
+ ? `Checked at ${new Date(state.checkedAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}`
677
+ : ''
678
+ const side = h('aside', { class: 'git-side' },
679
+ h('div', { class: 'git-side-top' },
680
+ h('div', { class: 'git-checked', text: checked }),
681
+ h('button', { type: 'button', class: 'git-btn git-btn--icon', title: 'Refresh', 'aria-label': 'Refresh', disabled: Boolean(state.checking || state.work), onclick: () => { state.notice = ''; check() } }, icon('fa-solid fa-rotate'))),
682
+ state.repos.map((item) => {
683
+ const count = Number(item.changeCount) || 0
684
+ return h('button', {
685
+ type: 'button',
686
+ class: `git-repo${item.repoParam === state.repoKey ? ' git-repo--selected' : ''}`,
687
+ onclick: () => {
688
+ if (state.work) return
689
+ state.repoKey = item.repoParam
690
+ state.commit = null
691
+ state.notice = ''
692
+ render()
693
+ },
694
+ },
695
+ h('div', { class: 'git-repo-name', text: item.name, title: item.name }),
696
+ h('div', {
697
+ class: `git-repo-status ${count > 0 || item.error || item.noRepo ? 'git-repo-status--dirty' : 'git-repo-status--clean'}`,
698
+ text: item.noRepo ? 'Not a repository' : item.error ? 'Could not check' : count > 0 ? `${count} change${count === 1 ? '' : 's'}` : 'Clean',
699
+ }))
700
+ }))
701
+ let main
702
+ if (!entry) {
703
+ main = h('div', { class: 'git-empty', text: state.error || (state.checking ? 'Checking repositories...' : 'No Git repositories detected') })
704
+ } else {
705
+ const web = remoteWebUrl(entry.url)
706
+ main = h('div', { class: 'git-main-inner' },
707
+ h('div', { class: 'git-main-header' },
708
+ h('div', { class: 'git-main-title', text: entry.name }),
709
+ web
710
+ ? h('a', { class: 'git-link', href: web, text: web.replace(/^https?:\/\//, ''), onclick: (event) => { event.preventDefault(); openExternal(web) } })
711
+ : h('span', { class: 'git-main-remote', text: entry.url || 'No remote' })),
712
+ h('div', { class: 'git-tabs', role: 'tablist' }, SECTIONS.map((name) => h('button', {
713
+ type: 'button',
714
+ role: 'tab',
715
+ class: `git-tab${state.section === name ? ' git-tab--selected' : ''}`,
716
+ 'aria-selected': state.section === name ? 'true' : 'false',
717
+ disabled: Boolean(state.work),
718
+ text: name.charAt(0).toUpperCase() + name.slice(1),
719
+ onclick: () => {
720
+ state.section = name
721
+ state.commit = null
722
+ state.notice = ''
723
+ state.consent = null
724
+ if (name === 'publish') {
725
+ // what gets published depends on the files as they are now
726
+ check()
727
+ } else {
728
+ render()
729
+ }
730
+ },
731
+ }))),
732
+ h('div', { class: 'git-section' },
733
+ state.notice || state.error ? h('div', { class: 'git-error', text: state.notice || state.error }) : null,
734
+ sectionBody(entry)))
735
+ }
736
+ root.replaceChildren(side, h('main', { class: 'git-main' }, main))
737
+ const again = typing && document.getElementById(typing.id)
738
+ if (again) {
739
+ again.focus()
740
+ try { again.setSelectionRange(typing.start, typing.end) } catch (_) {}
741
+ }
742
+ }
743
+
744
+ check()
745
+ })()