internal/site/template.go32.6 KB · Go
Raw
  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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
package site

const pageTemplate = `<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="color-scheme" content="light dark">
  <title>{{.Title}}</title>
  <link rel="icon" type="image/png" sizes="256x256" href="{{.BaseURL}}/.dumbforge/assets/gabriel-mark.png">
  <link rel="icon" type="image/svg+xml" href="{{.BaseURL}}/.dumbforge/assets/gabriel-mark.svg">
  <link rel="stylesheet" href="{{.BaseURL}}/.dumbforge/assets/site.css?v={{.AssetVersion}}">
</head>
<body data-base-url="{{.BaseURL}}" data-route-kind="{{.Kind}}" data-route-path="{{.Path}}" data-current-branch="{{.Branch}}" data-default-branch="{{.DefaultBranch}}" data-branches-url="{{.BranchesURL}}" data-files-url="{{.FilesURL}}">
  <header class="topbar">
    <a class="brand" href="{{.BaseURL}}" aria-label="Dumbforge repository home"><img class="brand-mark" src="{{.BaseURL}}/.dumbforge/assets/gabriel-mark.svg" alt=""></a>
    <nav class="header-crumbs" aria-label="Repository breadcrumb">
      <span class="header-owner">{{.Owner}}</span><span>/</span><a class="header-repo" href="{{.BaseURL}}">{{.RepoName}}</a>
    </nav>
  </header>
  <section class="repo-nav">
    <nav class="tabs" aria-label="Repository">
      <a class="tab {{if and (ne .Kind "commits") (ne .Kind "commit")}}active{{end}}" href="{{.BaseURL}}">{{icon "code"}} Code</a>
      <a class="tab {{if or (eq .Kind "commits") (eq .Kind "commit")}}active{{end}}" href="{{.CommitsURL}}">{{icon "history"}} Commits <span class="counter">{{.CommitCount}}</span></a>
    </nav>
  </section>

  <main>
    <div class="content-shell {{if or (eq .Kind "blob") (eq .Kind "commit")}}blob-content-shell{{end}}">
      {{if eq .Kind "repo"}}
      <div class="repo-overview-head">
        <div class="repo-title">{{if .RepoAvatarURL}}<img class="avatar repo-title-avatar" src="{{.RepoAvatarURL}}" alt="" referrerpolicy="no-referrer">{{else}}<span class="repo-icon">{{icon "repo"}}</span>{{end}}<a href="{{.BaseURL}}">{{.RepoName}}</a><span class="visibility">Public</span></div>
        <a class="secondary-button fork-button" href="{{.GitHubImportURL}}" target="_blank" rel="noopener" data-copy="{{.CloneURL}}" data-copied-label="URL copied — paste on GitHub" aria-label="Copy clone URL and open GitHub Importer" title="Copies the clone URL, then opens GitHub Importer">{{icon "fork"}} <span data-copy-label>Import to GitHub</span></a>
      </div>
      <div class="repo-grid">
        <section class="primary">
          <div class="toolbar repo-toolbar">
            {{template "branch-menu" .}}
            <span class="toolbar-spacer"></span>
            {{template "go-file-button" .}}
            {{template "clone-menu" .}}
          </div>
          {{template "tree" .}}
          {{if .Readme}}
          <article class="readme-card">
            <div class="card-heading">{{icon "book"}}{{.ReadmeName}}</div>
            <div class="markdown-body">{{.Readme}}</div>
          </article>
          {{end}}
        </section>
        <aside class="sidebar">
          <section class="sidebar-section about-section">
            <h2>About</h2>
            {{if .Description}}<p class="about-description">{{.Description}}</p>{{else}}<p class="about-description muted">No description provided.</p>{{end}}
            {{if .Homepage}}<a class="about-link" href="{{.Homepage}}">{{icon "link"}}<span>{{.HomepageLabel}}</span></a>{{end}}
            {{if and .SourceURL (ne .SourceURL .Homepage)}}<a class="about-link" href="{{.SourceURL}}">{{icon "external"}}<span>Upstream repository</span></a>{{end}}
          </section>
          {{if .Contributors}}
          <section class="sidebar-section">
            <h2 class="section-title"><span>{{icon "people"}} Contributors</span><span class="counter">{{.ContributorCount}}</span></h2>
            <div class="contributors-list">
              {{range .Contributors}}<div class="contributor">
                <img class="avatar contributor-avatar" src="{{.AvatarURL}}" alt="" loading="lazy" referrerpolicy="no-referrer">
                <span class="contributor-name">{{.Name}}</span>
                <span class="contributor-count">{{.Commits}}</span>
              </div>{{end}}
            </div>
          </section>
          {{end}}
          {{if .Languages}}
          <section class="sidebar-section">
            <h2>Languages</h2>
            <div class="language-bar" aria-label="Repository languages">
              {{range .Languages}}<span class="language-segment" style="{{.Style}}" title="{{.Name}} {{.Percent}}%"></span>{{end}}
            </div>
            <ul class="language-list">
              {{range .Languages}}<li style="{{.Style}}"><span class="language-dot"></span><strong>{{.Name}}</strong><span>{{.Percent}}%</span></li>{{end}}
            </ul>
          </section>
          {{end}}
        </aside>
      </div>
      {{else if eq .Kind "tree"}}
      <section class="primary full-width">
        <div class="toolbar toolbar-path">
          {{template "branch-menu" .}}
          <div class="breadcrumbs">{{range $i, $crumb := .Breadcrumbs}}{{if $i}}<span>/</span>{{end}}<a href="{{$crumb.URL}}">{{$crumb.Name}}</a>{{end}}</div>
          <span class="toolbar-spacer"></span>
          {{template "go-file-button" .}}
          {{template "clone-menu" .}}
        </div>
        {{template "tree" .}}
      </section>
      {{else if eq .Kind "commits"}}
      <section class="primary full-width commit-history">
        <div class="toolbar history-toolbar">
          {{template "branch-menu" .}}
          <span class="toolbar-spacer"></span>
          {{template "go-file-button" .}}
          <span class="history-total">{{icon "history"}} {{.CommitCount}} commits</span>
        </div>
        <div class="history-heading"><h1>Commit history</h1><p>Browse every commit reachable from <strong>{{.Branch}}</strong>.</p></div>
        {{range .CommitGroups}}<section class="commit-group">
          <h2>Commits on {{.Date}}</h2>
          <div class="commit-list">
            {{range .Commits}}<article class="commit-list-row" id="{{.OID}}">
              <img class="avatar commit-avatar" src="{{.AvatarURL}}" alt="" loading="lazy" referrerpolicy="no-referrer">
              <div class="commit-list-body">
                <a class="commit-list-message" href="{{.URL}}">{{.Message}}</a>
                <span><strong>{{.Author}}</strong> committed on <time datetime="{{.DateTime}}" data-smart-time>{{.Date}}</time></span>
              </div>
              <div class="commit-list-actions">
                <a class="commit-sha" href="{{.URL}}">{{.ShortOID}}</a>
                <button class="secondary-button commit-list-copy" type="button" data-copy="{{.OID}}" aria-label="Copy commit ID" title="Copy full commit ID"><span data-copy-icon>{{icon "copy"}}</span><span data-copied-icon hidden>{{icon "check"}}</span><span class="sr-only" data-copy-label>Copy commit ID</span></button>
              </div>
            </article>{{end}}
          </div>
        </section>{{end}}
      </section>
      {{else if eq .Kind "commit"}}
      <section class="primary full-width commit-view">
        <div class="commit-page-heading"><h1>Commit <code>{{.ViewedCommit.Commit.ShortOID}}</code></h1></div>
        <div class="commit-author-row">
          <img class="avatar commit-avatar" src="{{.ViewedCommit.Commit.AvatarURL}}" alt="" referrerpolicy="no-referrer">
          <span><strong>{{.ViewedCommit.Commit.Author}}</strong> committed on <time datetime="{{.ViewedCommit.Commit.DateTime}}" data-smart-time>{{.ViewedCommit.Commit.Date}}</time></span>
        </div>
        <article class="commit-summary-card">
          <div class="commit-summary-title">
            <strong>{{.ViewedCommit.Commit.Message}}</strong>
          </div>
          {{if .ViewedCommit.Commit.Body}}<pre class="commit-body">{{.ViewedCommit.Commit.Body}}</pre>{{end}}
          <div class="commit-identifiers">
            <span>commit <code>{{.ViewedCommit.Commit.OID}}</code></span>
            {{range .ViewedCommit.Parents}}<span>parent <a href="{{.URL}}"><code>{{.ShortOID}}</code></a></span>{{end}}
            <button class="secondary-button commit-copy" type="button" data-copy="{{.ViewedCommit.Commit.OID}}" aria-label="Copy commit ID"><span data-copy-icon>{{icon "copy"}}</span><span data-copied-icon hidden>{{icon "check"}}</span><span data-copy-label>Copy SHA</span></button>
          </div>
          <div class="diff-overview">
            {{if .ViewedCommit.Truncated}}<strong>Large commit</strong>{{else}}<strong>{{.ViewedCommit.FileCount}} changed files</strong>{{end}}
            {{if gt (len .ViewedCommit.Parents) 1}}<span class="muted">Diffed against the first of {{len .ViewedCommit.Parents}} parents.</span>{{end}}
            <span class="diff-totals"><b class="addition">+{{.ViewedCommit.Additions}}</b><b class="deletion">−{{.ViewedCommit.Deletions}}</b></span>
          </div>
        </article>

        {{if .ViewedCommit.Truncated}}
        <div class="diff-limit-notice"><strong>Diff too large to render</strong><p>This commit's patch exceeds the 8 MB static-page limit. Clone the repository to inspect the complete change.</p></div>
        {{else if .ViewedCommit.Files}}
        <div class="diff-layout">
          <aside class="file-browser diff-sidebar" aria-label="Changed files">
            <div class="file-browser-heading">{{icon "folder"}}<strong>Files changed</strong></div>
            <label class="file-tree-search">{{icon "search"}}<input type="search" placeholder="Search changed files" autocomplete="off" data-diff-file-tree-query></label>
            <nav class="file-tree" data-diff-file-tree>
              {{range .ViewedCommit.Files}}<a class="file-tree-file" href="#{{.Anchor}}" data-diff-file data-path="{{.TreePath}}">{{icon "file"}}<span>{{.DisplayPath}}</span></a>{{end}}
            </nav>
          </aside>
          <div class="diff-files">
          {{range .ViewedCommit.Files}}<article class="diff-file" id="{{.Anchor}}">
            <header class="diff-file-header">
              <span class="diff-status">{{.Status}}</span><strong title="{{.DisplayPath}}">{{.DisplayPath}}</strong>
              <span class="diff-file-stats"><b class="addition">+{{.Additions}}</b><b class="deletion">−{{.Deletions}}</b></span>
            </header>
            {{if .Binary}}<div class="diff-file-notice">Binary file changed.</div>
            {{else if not .Rows}}<div class="diff-file-notice">{{if .Truncated}}Diff omitted because this commit exceeds the static-page render limit.{{else}}File metadata changed without textual changes.{{end}}</div>
            {{else}}<div class="split-diff diff-chroma"><table aria-label="Side-by-side diff for {{.DisplayPath}}"><colgroup><col class="diff-number-col"><col class="diff-code-col"><col class="diff-number-col"><col class="diff-code-col"></colgroup><tbody>
              {{range .Rows}}{{if .Hunk}}<tr class="diff-hunk"><td colspan="4"><code>{{.Header}}</code></td></tr>{{else}}<tr>
                <td class="diff-line-number {{.OldClass}}">{{if .OldPresent}}{{.OldNumber}}{{end}}</td>
                <td class="diff-code old {{.OldClass}} {{if not .OldPresent}}empty{{end}}"><code>{{if .OldPresent}}{{.OldCode}}{{end}}</code></td>
                <td class="diff-line-number {{.NewClass}}">{{if .NewPresent}}{{.NewNumber}}{{end}}</td>
                <td class="diff-code new {{.NewClass}} {{if not .NewPresent}}empty{{end}}"><code>{{if .NewPresent}}{{.NewCode}}{{end}}</code></td>
              </tr>{{end}}{{end}}
            </tbody></table></div>{{if .Truncated}}<div class="diff-truncated-notice">Diff truncated after the static-page render limit. Clone the repository to inspect the complete change.</div>{{end}}{{end}}
          </article>{{end}}
          </div>
        </div>
        {{else}}<div class="diff-limit-notice">{{if .ViewedCommit.Binaries}}<strong>Binary changes omitted</strong><p>Binary files are not rendered in static diffs.</p>{{else}}<strong>No file changes</strong><p>This commit has no changes relative to its first parent.</p>{{end}}</div>{{end}}
      </section>
      {{else}}
      <div class="blob-layout">
        <aside class="file-browser" aria-label="Repository files">
          <div class="file-browser-heading">{{icon "folder"}}<strong>Files</strong></div>
          <div class="file-browser-branch">{{template "branch-menu" .}}</div>
          <label class="file-tree-search">{{icon "search"}}<input type="search" placeholder="Search files" autocomplete="off" data-file-tree-query></label>
          <nav class="file-tree" data-file-tree><p class="menu-status">Loading files…</p></nav>
        </aside>
        <section class="primary blob-main">
          <div class="toolbar toolbar-path blob-toolbar">
            <div class="breadcrumbs">{{range $i, $crumb := .Breadcrumbs}}{{if $i}}<span>/</span>{{end}}<a href="{{$crumb.URL}}">{{$crumb.Name}}</a>{{end}}</div>
            <span class="toolbar-spacer"></span>
            {{template "go-file-button" .}}
            {{template "clone-menu" .}}
          </div>
          <div class="blob-card">
            <div class="blob-heading">
              <div><strong>{{.Path}}</strong><span>{{humanSize .FileSize}} · {{.Language}}</span></div>
              <div class="blob-actions"><a href="{{.RawURL}}">Raw</a><button type="button" data-copy="{{.RawURL}}"><span data-copy-icon>{{icon "copy"}}</span><span data-copied-icon hidden>{{icon "check"}}</span><span data-copy-label>Copy link</span></button></div>
            </div>
			{{if .IsSubmodule}}<div class="binary-notice"><span>{{icon "repo"}}</span><strong>Submodule</strong><p>Points to commit <code>{{.SubmoduleOID}}</code>.</p>{{if .SubmoduleURL}}<a href="{{.SubmoduleURL}}">Open submodule</a>{{end}}</div>
			{{else if .IsImage}}<div class="image-preview"><img src="{{.RawURL}}" alt="{{.Path}}"></div>
            {{else if .IsMarkdown}}<article class="markdown-file"><div class="markdown-body">{{.Markdown}}</div></article>
            {{else if .Code}}<div class="code-view">{{.Code}}</div>
            {{else}}<div class="binary-notice"><span>{{icon "file"}}</span><strong>Preview unavailable</strong><p>This file is binary or too large to render safely.</p><a href="{{.RawURL}}">Download raw file</a></div>{{end}}
          </div>
        </section>
      </div>
      {{end}}
    </div>
  </main>

  <div class="dialog-backdrop" data-file-dialog hidden>
    <section class="file-dialog" role="dialog" aria-modal="true" aria-labelledby="go-file-title">
      <header><h2 id="go-file-title">Go to file</h2><button class="icon-button" type="button" data-file-close aria-label="Close">{{icon "close"}}</button></header>
      <label class="file-search">{{icon "search"}}<input type="search" placeholder="Search files" autocomplete="off" data-file-query></label>
      <div class="file-results" data-file-results><p class="menu-status">Loading files…</p></div>
    </section>
  </div>
  <template data-tree-folder-icon>{{icon "folder"}}</template>
  <template data-tree-file-icon>{{icon "file"}}</template>

  <script>
  (function () {
    var body = document.body;
    var all = function (selector, root) { return Array.prototype.slice.call((root || document).querySelectorAll(selector)); };
    var one = function (selector, root) { return (root || document).querySelector(selector); };

    function legacyCopy(value) {
      var input = document.createElement('textarea');
      input.value = value;
      input.style.position = 'fixed';
      input.style.opacity = '0';
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      input.remove();
    }
    function showCopied(button) {
      var label = one('[data-copy-label]', button);
      var copyIcon = one('[data-copy-icon]', button);
      var copiedIcon = one('[data-copied-icon]', button);
      if (label && !label.dataset.original) label.dataset.original = label.textContent;
      if (!button.dataset.originalAria) button.dataset.originalAria = button.getAttribute('aria-label') || '';
      if (label) label.textContent = button.getAttribute('data-copied-label') || 'Copied!';
      if (copyIcon) copyIcon.hidden = true;
      if (copiedIcon) copiedIcon.hidden = false;
      button.classList.add('is-copied');
      button.setAttribute('aria-label', 'Copied to clipboard');
      clearTimeout(button._copyTimer);
      button._copyTimer = setTimeout(function () {
        if (label) label.textContent = label.dataset.original || 'Copy';
        if (copyIcon) copyIcon.hidden = false;
        if (copiedIcon) copiedIcon.hidden = true;
        button.classList.remove('is-copied');
        if (button.dataset.originalAria) button.setAttribute('aria-label', button.dataset.originalAria);
        else button.removeAttribute('aria-label');
      }, 1600);
    }
    function copyText(value, button) {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(value).then(function () { showCopied(button); }).catch(function () { legacyCopy(value); showCopied(button); });
      } else {
        legacyCopy(value);
        showCopied(button);
      }
    }
    all('[data-copy]').forEach(function (button) {
      button.addEventListener('click', function () { copyText(button.getAttribute('data-copy'), button); });
    });

    var relativeFormatter = window.Intl && Intl.RelativeTimeFormat ? new Intl.RelativeTimeFormat(undefined, {numeric: 'always'}) : null;
    function updateRelativeTimes() {
      if (!relativeFormatter) return;
      var now = Date.now();
      all('[data-relative-time], [data-smart-time]').forEach(function (node) {
        var date = new Date(node.getAttribute('datetime'));
        if (isNaN(date.getTime())) return;
        if (!node.dataset.absoluteLabel) node.dataset.absoluteLabel = node.textContent;
        var seconds = (date.getTime() - now) / 1000;
        var absolute = Math.abs(seconds);
        if (node.hasAttribute('data-smart-time') && absolute >= 604800) {
          node.textContent = node.dataset.absoluteLabel;
          return;
        }
        var divisor = 1;
        var unit = 'second';
        if (absolute >= 31536000) { divisor = 31536000; unit = 'year'; }
        else if (absolute >= 2592000) { divisor = 2592000; unit = 'month'; }
        else if (absolute >= 86400) { divisor = 86400; unit = 'day'; }
        else if (absolute >= 3600) { divisor = 3600; unit = 'hour'; }
        else if (absolute >= 60) { divisor = 60; unit = 'minute'; }
        node.textContent = relativeFormatter.format(Math.round(seconds / divisor), unit);
        if (!node.title) node.title = date.toLocaleString();
      });
    }
    updateRelativeTimes();
    if (relativeFormatter) window.setInterval(updateRelativeTimes, 60000);

    function closeMenu(menu) {
      if (!menu) return;
      var panel = one('[data-popover]', menu);
      var toggle = one('[aria-expanded]', menu);
      if (panel) panel.hidden = true;
      if (toggle) toggle.setAttribute('aria-expanded', 'false');
    }
    function wireMenu(menu, onOpen) {
      if (!menu) return;
      var toggle = one('[aria-expanded]', menu);
      var panel = one('[data-popover]', menu);
      toggle.addEventListener('click', function () {
        var shouldOpen = panel.hidden;
        all('[data-menu]').forEach(function (other) { if (other !== menu) closeMenu(other); });
        panel.hidden = !shouldOpen;
        toggle.setAttribute('aria-expanded', shouldOpen ? 'true' : 'false');
        if (shouldOpen && onOpen) onOpen(panel);
      });
    }
    var cloneMenu = one('[data-clone-menu]');
    wireMenu(cloneMenu, function (panel) { one('input', panel).select(); });

    function encodedRoute(parts) {
      var segments = [];
      parts.forEach(function (part) {
        String(part || '').split('/').forEach(function (segment) { if (segment) segments.push(encodeURIComponent(segment)); });
      });
      return body.dataset.baseUrl.replace(/\/$/, '') + (segments.length ? '/' + segments.join('/') : '');
    }
    function branchRouteSegment(branch) {
      return String(branch || '').replace(/\//g, '~');
    }
    function branchTarget(branch, defaultBranch) {
      var kind = body.dataset.routeKind;
      var filePath = body.dataset.routePath;
      var branchRoute = branchRouteSegment(branch);
      if (kind === 'repo') return branch === defaultBranch ? body.dataset.baseUrl : encodedRoute(['tree', branchRoute]);
      if (kind === 'tree') {
        if (!filePath && branch === defaultBranch) return body.dataset.baseUrl;
        return encodedRoute(['tree', branchRoute, filePath]);
      }
      if (kind === 'blob') return encodedRoute(['blob', branchRoute, filePath]);
      if (kind === 'commits') return encodedRoute(['commits', branchRoute]);
      return body.dataset.baseUrl;
    }
    var branchMenu = one('[data-branch-menu]');
    var branchesLoaded = false;
    wireMenu(branchMenu, function (panel) {
      if (branchesLoaded) return;
      fetch(body.dataset.branchesUrl, {cache: 'no-cache'}).then(function (response) {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        return response.json();
      }).then(function (manifest) {
        var list = one('[data-branch-list]', panel);
        list.textContent = '';
        manifest.branches.forEach(function (branch) {
          var link = document.createElement('a');
          link.className = 'branch-option';
          link.href = branchTarget(branch, manifest.defaultBranch);
          link.textContent = branch;
          if (branch === body.dataset.currentBranch) link.classList.add('selected');
          list.appendChild(link);
        });
        if (!manifest.branches.length) list.textContent = 'No branches published.';
        branchesLoaded = true;
      }).catch(function () { one('[data-branch-list]', panel).textContent = 'Could not load branches.'; });
    });

    document.addEventListener('click', function (event) {
      all('[data-menu]').forEach(function (menu) { if (!menu.contains(event.target)) closeMenu(menu); });
    });

    var fileDialog = one('[data-file-dialog]');
    var fileQuery = one('[data-file-query]');
    var fileResults = one('[data-file-results]');
    var files = null;
    var filesPromise = null;
    function loadFiles() {
      if (files) return Promise.resolve(files);
      if (!filesPromise) {
        filesPromise = fetch(body.dataset.filesUrl, {cache: 'no-cache'}).then(function (response) {
          if (!response.ok) throw new Error('HTTP ' + response.status);
          return response.json();
        }).then(function (manifest) {
          files = manifest.files || [];
          return files;
        }).catch(function (error) {
          filesPromise = null;
          throw error;
        });
      }
      return filesPromise;
    }
    function renderFiles() {
      if (!files) return;
      var query = fileQuery.value.trim().toLowerCase();
      var matches = files.filter(function (file) { return !query || file.path.toLowerCase().indexOf(query) !== -1; });
      matches.sort(function (a, b) {
        var ai = query ? a.path.toLowerCase().indexOf(query) : 0;
        var bi = query ? b.path.toLowerCase().indexOf(query) : 0;
        return ai - bi || a.path.length - b.path.length || a.path.localeCompare(b.path);
      });
      fileResults.textContent = '';
      matches.slice(0, 100).forEach(function (file) {
        var link = document.createElement('a');
        link.href = file.url;
        link.className = 'file-result';
        link.textContent = file.path;
        fileResults.appendChild(link);
      });
      if (!matches.length) fileResults.innerHTML = '<p class="menu-status">No matching files.</p>';
      else if (matches.length > 100) {
        var more = document.createElement('p');
        more.className = 'menu-status';
        more.textContent = 'Keep typing to narrow ' + matches.length + ' results.';
        fileResults.appendChild(more);
      }
    }
    function openFiles() {
      fileDialog.hidden = false;
      document.body.classList.add('dialog-open');
      fileQuery.value = '';
      fileQuery.focus();
      if (files) { renderFiles(); return; }
      loadFiles().then(renderFiles)
        .catch(function () { fileResults.innerHTML = '<p class="menu-status">Could not load the file list.</p>'; });
    }
    function closeFiles() {
      fileDialog.hidden = true;
      document.body.classList.remove('dialog-open');
    }
    all('[data-file-toggle]').forEach(function (button) { button.addEventListener('click', openFiles); });
    one('[data-file-close]').addEventListener('click', closeFiles);
    fileDialog.addEventListener('click', function (event) { if (event.target === fileDialog) closeFiles(); });
    fileQuery.addEventListener('input', renderFiles);
    fileQuery.addEventListener('keydown', function (event) {
      if (event.key === 'Enter') { var first = one('.file-result', fileResults); if (first) window.location.href = first.href; }
    });

    function addTreeIcon(target, selector) {
      var source = one(selector);
      if (source) target.appendChild(source.content.cloneNode(true));
    }
    function fileTreeLink(file, label, compact) {
      var link = document.createElement('a');
      link.className = 'file-tree-file';
      link.href = file.url;
      addTreeIcon(link, '[data-tree-file-icon]');
      var text = document.createElement('span');
      text.textContent = label;
      if (compact) text.title = file.path;
      link.appendChild(text);
      if (file.path === body.dataset.routePath || (file.url.charAt(0) === '#' && file.url === window.location.hash)) {
        link.classList.add('selected');
        link.setAttribute('aria-current', 'page');
      }
      return link;
    }
    function renderTreeNode(node, container, prefix, expandAll) {
      Object.keys(node.folders).sort().forEach(function (name) {
        var child = node.folders[name];
        var childPath = prefix ? prefix + '/' + name : name;
        var wrapper = document.createElement('div');
        wrapper.className = 'file-tree-node';
        var toggle = document.createElement('button');
        toggle.className = 'file-tree-folder';
        toggle.type = 'button';
        var caret = document.createElement('span');
        caret.className = 'file-tree-caret';
        caret.textContent = '›';
        toggle.appendChild(caret);
        addTreeIcon(toggle, '[data-tree-folder-icon]');
        var label = document.createElement('span');
        label.textContent = name;
        toggle.appendChild(label);
        var children = document.createElement('div');
        children.className = 'file-tree-children';
        var open = expandAll || body.dataset.routePath === childPath || body.dataset.routePath.indexOf(childPath + '/') === 0;
        children.hidden = !open;
        caret.classList.toggle('open', open);
        toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
        toggle.addEventListener('click', function () {
          var opening = children.hidden;
          children.hidden = !opening;
          caret.classList.toggle('open', opening);
          toggle.setAttribute('aria-expanded', opening ? 'true' : 'false');
        });
        wrapper.appendChild(toggle);
        wrapper.appendChild(children);
        container.appendChild(wrapper);
        renderTreeNode(child, children, childPath, expandAll);
      });
      node.files.sort(function (a, b) { return a.name.localeCompare(b.name); }).forEach(function (entry) {
        container.appendChild(fileTreeLink(entry.file, entry.name, false));
      });
    }
    function renderFileTree(target, queryInput, treeFiles, expandAll) {
      if (!target || !treeFiles) return;
      var query = queryInput ? queryInput.value.trim().toLowerCase() : '';
      target.textContent = '';
      if (query) {
        var matches = treeFiles.filter(function (file) { return file.path.toLowerCase().indexOf(query) !== -1; });
        matches.slice(0, 200).forEach(function (file) { target.appendChild(fileTreeLink(file, file.path, true)); });
        if (!matches.length) target.innerHTML = '<p class="menu-status">No matching files.</p>';
        return;
      }
      var root = {folders: {}, files: []};
      treeFiles.forEach(function (file) {
        var parts = file.path.split('/');
        var node = root;
        parts.slice(0, -1).forEach(function (part) {
          if (!node.folders[part]) node.folders[part] = {folders: {}, files: []};
          node = node.folders[part];
        });
        node.files.push({name: parts[parts.length - 1], file: file});
      });
      renderTreeNode(root, target, '', expandAll);
      var selected = one('.file-tree-file.selected', target);
      if (selected) target.scrollTop = Math.max(0, selected.offsetTop - (target.clientHeight - selected.offsetHeight) / 2);
    }

    var fileTree = one('[data-file-tree]');
    var fileTreeQuery = one('[data-file-tree-query]');
    if (fileTree) {
      loadFiles().then(function (loadedFiles) { renderFileTree(fileTree, fileTreeQuery, loadedFiles, false); })
        .catch(function () { fileTree.innerHTML = '<p class="menu-status">Could not load files.</p>'; });
      fileTreeQuery.addEventListener('input', function () { renderFileTree(fileTree, fileTreeQuery, files, false); });
    }

    var diffFileTree = one('[data-diff-file-tree]');
    var diffFileTreeQuery = one('[data-diff-file-tree-query]');
    if (diffFileTree) {
      var diffFiles = all('[data-diff-file]', diffFileTree).map(function (link) {
        return {path: link.getAttribute('data-path'), url: link.getAttribute('href')};
      });
      renderFileTree(diffFileTree, diffFileTreeQuery, diffFiles, true);
      diffFileTreeQuery.addEventListener('input', function () { renderFileTree(diffFileTree, diffFileTreeQuery, diffFiles, true); });
      window.addEventListener('hashchange', function () {
        all('.file-tree-file', diffFileTree).forEach(function (link) {
          var selected = link.getAttribute('href') === window.location.hash;
          link.classList.toggle('selected', selected);
          if (selected) link.setAttribute('aria-current', 'page');
          else link.removeAttribute('aria-current');
        });
      });
    }

    document.addEventListener('keydown', function (event) {
      if (event.key !== 'Escape') return;
      if (!fileDialog.hidden) { closeFiles(); return; }
      all('[data-menu]').forEach(closeMenu);
    });
  }());
  </script>
</body>
</html>

{{define "branch-menu"}}
<div class="branch-menu" data-branch-menu data-menu>
  <button class="branch-button" type="button" aria-expanded="false">{{icon "branch"}}<span>{{.Branch}}</span>{{icon "chevron"}}</button>
  <div class="branch-popover" data-popover hidden>
    <h3>Switch branches</h3>
    <div class="branch-list" data-branch-list><p class="menu-status">Loading branches…</p></div>
  </div>
</div>
{{end}}

{{define "go-file-button"}}<button class="secondary-button go-file-button" type="button" data-file-toggle>{{icon "search"}} Go to file</button>{{end}}

{{define "clone-menu"}}
<div class="clone-menu" data-clone-menu data-menu>
  <button class="clone-button" type="button" aria-expanded="false">{{icon "code"}} Code {{icon "chevron"}}</button>
  <div class="clone-popover" data-popover hidden>
    <h3>Clone with HTTPS</h3>
    <p>Use Git without installing Dumbforge.</p>
    <div class="clone-input-group">
      <input type="text" value="{{.CloneURL}}" readonly aria-label="Clone URL">
      <button type="button" data-copy="{{.CloneURL}}" aria-label="Copy to clipboard"><span data-copy-icon>{{icon "copy"}}</span><span data-copied-icon hidden>{{icon "check"}}</span><span class="sr-only" data-copy-label>Copy</span></button>
    </div>
    <code>git clone {{.CloneURL}}</code>
  </div>
</div>
{{end}}

{{define "tree"}}
<div class="tree-card">
  <div class="commit-row">
    <img class="avatar commit-avatar" src="{{.Commit.AvatarURL}}" alt="" referrerpolicy="no-referrer">
    <div class="latest-commit"><strong>{{.Commit.Author}}</strong><a class="commit-message" href="{{.Commit.URL}}">{{.Commit.Message}}</a></div>
    <a class="commit-hash" href="{{.Commit.URL}}">{{.Commit.ShortOID}}</a>
    <time datetime="{{.Commit.DateTime}}" data-smart-time>{{.Commit.Date}}</time>
    <a class="commit-count-link" href="{{.CommitsURL}}">{{icon "history"}}<strong>{{.CommitCount}}</strong> commits</a>
  </div>
  <div class="tree-rows">
    {{if .ParentURL}}<div class="tree-row parent-row"><a class="file-icon parent-icon" href="{{.ParentURL}}" aria-label="Parent directory">{{icon "back"}}</a><a class="file-name" href="{{.ParentURL}}">..</a><span></span><span></span></div>{{end}}
    {{range .Entries}}<div class="tree-row">
	      {{if eq .Type "tree"}}<span class="file-icon folder">{{icon "folder"}}</span>{{else if eq .Type "commit"}}<span class="file-icon">{{icon "repo"}}</span>{{else}}<span class="file-icon">{{icon "file"}}</span>{{end}}
      <a class="file-name" href="{{.URL}}">{{.Name}}</a>
      <a class="row-message" href="{{.CommitURL}}" title="{{.CommitMessage}}">{{.CommitMessage}}</a>
      <time class="file-date" datetime="{{.CommitDateTime}}" data-relative-time>{{.CommitDate}}</time>
    </div>{{end}}
  </div>
</div>
{{end}}`