Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 8.4 KiBRawPermalink
1/* SPDX-License-Identifier: Apache-2.0
2 Copyright (c) 2026 UtopiaIA
3 Elffuss Braid · braid.elffuss.com
4 The language toggle, the copy buttons, the faded edge of code blocks that
5 scroll (only those take keyboard focus), and the markers of the ratio
6 table. No dependencies, no requests. Without this file the page is
7 English and complete, every code block takes focus, and the toggle and
8 the copy buttons stay hidden. */
9(function () {
10 'use strict';
11
12 var KEY = 'braid-lang';
13 var root = document.documentElement;
14 var TITLE = {
15 en: 'Elffuss Braid · version control for many agents at once',
16 es: 'Elffuss Braid · control de versiones para muchos agentes a la vez'
17 };
18 var SAID = {
19 en: { copied: 'Copied', failed: 'Could not copy: the text is selected instead' },
20 es: { copied: 'Copiado', failed: 'No se pudo copiar: el texto queda seleccionado' }
21 };
22
23 function valid(value) {
24 return value === 'en' || value === 'es' ? value : null;
25 }
26 function fromQuery() {
27 try { return valid(new URLSearchParams(window.location.search).get('lang')); } catch (e) { return null; }
28 }
29 function fromStore() {
30 try { return valid(window.localStorage.getItem(KEY)); } catch (e) { return null; }
31 }
32 function remember(value) {
33 try { window.localStorage.setItem(KEY, value); } catch (e) { /* private mode: fine */ }
34 }
35 function fromBrowser() {
36 var tag = (navigator.language || '').toLowerCase();
37 return tag.indexOf('es') === 0 ? 'es' : null;
38 }
39
40 // ?lang=, then the stored choice, then a Spanish browser, then English.
41 // Set before the body is parsed, so the other language never flashes.
42 var lang = fromQuery() || fromStore() || fromBrowser() || 'en';
43 root.setAttribute('lang', lang);
44
45 function each(selector, fn) {
46 var list = document.querySelectorAll(selector);
47 for (var i = 0; i < list.length; i++) fn(list[i]);
48 }
49
50 // Boxes whose text keeps its lines and may scroll sideways. In the HTML
51 // each is a labelled region that takes keyboard focus; edges() keeps that
52 // only for the ones that do scroll at the current width.
53 var SCROLLERS = '.code pre, .term-cols pre, .table-wrap';
54 var scrollers = [];
55
56 function apply(value) {
57 lang = value;
58 root.setAttribute('lang', value);
59 document.title = TITLE[value];
60 each('[data-set-lang]', function (button) {
61 button.setAttribute('aria-pressed', String(button.getAttribute('data-set-lang') === value));
62 });
63 each('[data-aria-' + value + ']', function (el) {
64 if (el.matches(SCROLLERS) && el.getAttribute('role') !== 'region') return;
65 el.setAttribute('aria-label', el.getAttribute('data-aria-' + value));
66 });
67 allEdges(); // the other language has other widths
68 }
69
70 function keepQuery(value) {
71 try {
72 var url = new URL(window.location.href);
73 if (url.searchParams.has('lang')) {
74 url.searchParams.set('lang', value);
75 window.history.replaceState(null, '', url.toString());
76 }
77 } catch (e) { /* old browser: the toggle still works */ }
78 }
79
80 function say(text) {
81 var live = document.getElementById('live');
82 if (!live) return;
83 live.textContent = '';
84 window.setTimeout(function () { live.textContent = text; }, 40);
85 }
86
87 function write(text) {
88 if (navigator.clipboard && window.isSecureContext) {
89 return navigator.clipboard.writeText(text);
90 }
91 return new Promise(function (resolve, reject) {
92 var area = document.createElement('textarea');
93 area.value = text;
94 area.setAttribute('readonly', '');
95 area.style.position = 'fixed';
96 area.style.top = '0';
97 area.style.left = '0';
98 area.style.opacity = '0';
99 document.body.appendChild(area);
100 area.select();
101 var done = false;
102 try { done = document.execCommand('copy'); } catch (e) { done = false; }
103 document.body.removeChild(area);
104 if (done) resolve(); else reject(new Error('copy'));
105 });
106 }
107
108 function copy(button) {
109 var block = button.closest('.code');
110 var code = block && block.querySelector('pre code');
111 if (!code) return;
112 write(code.textContent).then(function () {
113 button.classList.add('copied');
114 window.clearTimeout(button._braidTimer);
115 button._braidTimer = window.setTimeout(function () { button.classList.remove('copied'); }, 1800);
116 say(SAID[lang].copied);
117 }, function () {
118 var range = document.createRange();
119 range.selectNodeContents(code);
120 var selection = window.getSelection();
121 selection.removeAllRanges();
122 selection.addRange(range);
123 say(SAID[lang].failed);
124 });
125 }
126
127 // A marker per row of the ratio table, drawn from the table's own cells
128 // on a log scale, with a line at 1.
129 function markers() {
130 var table = document.querySelector('#measured table.ratios');
131 if (!table || !table.tBodies.length) return;
132 var found = [];
133 var rows = table.tBodies[0].rows;
134 for (var i = 0; i < rows.length; i++) {
135 var cell = rows[i].cells[1];
136 var value = cell ? parseFloat(cell.textContent.replace(',', '.')) : NaN;
137 if (isFinite(value) && value > 0) found.push({ cell: cell, value: value });
138 }
139 if (!found.length) return;
140 var values = found.map(function (f) { return f.value; });
141 var lo = Math.log(Math.min(0.1, Math.min.apply(null, values) / 1.5));
142 var hi = Math.log(Math.max(10, Math.max.apply(null, values) * 1.5));
143 function at(v) { return (Math.log(v) - lo) / (hi - lo) * 100; }
144 var one = at(1);
145 found.forEach(function (f) {
146 var x = at(f.value);
147 var mark = document.createElement('span');
148 mark.className = 'mk';
149 mark.setAttribute('aria-hidden', 'true');
150 var line = document.createElement('span');
151 line.className = 'mk-one';
152 line.style.left = one.toFixed(2) + '%';
153 var bar = document.createElement('span');
154 bar.className = 'mk-bar';
155 bar.style.left = Math.min(x, one).toFixed(2) + '%';
156 bar.style.width = Math.abs(x - one).toFixed(2) + '%';
157 var dot = document.createElement('span');
158 dot.className = 'mk-dot';
159 dot.style.left = x.toFixed(2) + '%';
160 mark.appendChild(bar);
161 mark.appendChild(line);
162 mark.appendChild(dot);
163 f.cell.appendChild(mark);
164 });
165 var legend = document.getElementById('mk-legend');
166 if (legend) legend.hidden = false;
167 }
168
169 // A box that is wider than its text scrolls in it. Only then is it a
170 // region to tab to, named in the page's language; otherwise it is plain
171 // text, and keyboards and screen readers pass over it. The side that has
172 // more is marked, and site.css fades the text there.
173 function edges(el) {
174 var max = el.scrollWidth - el.clientWidth;
175 var scrolls = max > 1;
176 if (scrolls) {
177 el.setAttribute('tabindex', '0');
178 el.setAttribute('role', 'region');
179 var label = el.getAttribute('data-aria-' + lang);
180 if (label) el.setAttribute('aria-label', label);
181 } else if (el !== document.activeElement) {
182 el.removeAttribute('tabindex');
183 el.removeAttribute('role');
184 el.removeAttribute('aria-label');
185 }
186 el.classList.toggle('more-right', scrolls && el.scrollLeft < max - 1);
187 el.classList.toggle('more-left', scrolls && el.scrollLeft > 1);
188 }
189 function allEdges() {
190 for (var i = 0; i < scrollers.length; i++) edges(scrollers[i]);
191 }
192 function watchEdges() {
193 scrollers = document.querySelectorAll(SCROLLERS);
194 for (var i = 0; i < scrollers.length; i++) {
195 scrollers[i].addEventListener('scroll', function () { edges(this); }, { passive: true });
196 }
197 window.addEventListener('resize', allEdges);
198 document.addEventListener('toggle', allEdges, true); // a <details> opened
199 allEdges();
200 }
201
202 function start() {
203 apply(lang);
204 // Without this file these do nothing, so they only show up with it.
205 each('button.copy, .lang', function (el) { el.hidden = false; });
206 document.addEventListener('click', function (event) {
207 var target = event.target;
208 if (!target || !target.closest) return;
209 var toggle = target.closest('[data-set-lang]');
210 if (toggle) {
211 var value = valid(toggle.getAttribute('data-set-lang'));
212 if (value) {
213 apply(value);
214 remember(value);
215 keepQuery(value);
216 }
217 return;
218 }
219 var button = target.closest('button.copy');
220 if (button) copy(button);
221 });
222 markers();
223 watchEdges();
224 }
225
226 if (document.readyState === 'loading') {
227 document.addEventListener('DOMContentLoaded', start);
228 } else {
229 start();
230 }
231})();