Branchwell

Skillfarm / website · skillfarm.ai / public / js / site.js

Raw 13.5 KB on a4acba8fed02ff053e24fa2ab137b32f1b601fa1
1(function () {
2 'use strict';
3 document.documentElement.classList.add('js');
4 var signedIn = document.body.getAttribute('data-signed-in') === '1';
5 function on(sel, ev, fn) {
6 document.addEventListener(ev, function (e) {
7 var t = e.target && e.target.closest ? e.target.closest(sel) : null;
8 if (t) fn(t, e);
9 });
10 }
11 function compact(n) {
12 if (n < 1000) return String(n);
13 if (n < 10000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
14 if (n < 1000000) return Math.round(n / 1000) + 'k';
15 return (n / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
16 }
17
18 // Mobile navigation
19 on('[data-nav-toggle]', 'click', function (btn) {
20 var nav = document.getElementById('main-nav');
21 var open = nav.classList.toggle('is-open');
22 btn.setAttribute('aria-expanded', open ? 'true' : 'false');
23 });
24
25 // Close the account menu when clicking elsewhere or pressing Escape
26 document.addEventListener('click', function (e) {
27 document.querySelectorAll('details.menu[open]').forEach(function (d) {
28 if (!d.contains(e.target)) d.removeAttribute('open');
29 });
30 });
31 document.addEventListener('keydown', function (e) {
32 if (e.key === 'Escape') document.querySelectorAll('details.menu[open]').forEach(function (d) { d.removeAttribute('open'); });
33 });
34
35 // Likes
36 on('[data-like]', 'click', function (btn) {
37 if (!signedIn) {
38 location.href = '/signin?next=' + encodeURIComponent(location.pathname + location.search);
39 return;
40 }
41 if (btn.classList.contains('is-busy')) return;
42 var liked = btn.classList.contains('is-liked');
43 btn.classList.add('is-busy');
44 fetch('/api/skills/' + encodeURIComponent(btn.getAttribute('data-like')) + '/like', { method: liked ? 'DELETE' : 'POST', headers: { accept: 'application/json' }, credentials: 'same-origin' })
45 .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, body: j }; }); })
46 .then(function (res) {
47 if (!res.ok) {
48 btn.setAttribute('title', res.body.message || 'That did not work.');
49 return;
50 }
51 document.querySelectorAll('[data-like="' + btn.getAttribute('data-like') + '"]').forEach(function (b) {
52 b.classList.toggle('is-liked', !!res.body.liked);
53 b.setAttribute('aria-pressed', res.body.liked ? 'true' : 'false');
54 b.setAttribute('title', res.body.liked ? 'Remove your like' : 'Like this skill');
55 var count = b.querySelector('[data-like-count]');
56 if (count) count.textContent = compact(res.body.likes);
57 });
58 })
59 .catch(function () { btn.setAttribute('title', 'Could not reach Skillfarm. Try again.'); })
60 .then(function () { btn.classList.remove('is-busy'); });
61 });
62
63 // Copy buttons
64 function copyText(text, done) {
65 if (navigator.clipboard && navigator.clipboard.writeText) {
66 navigator.clipboard.writeText(text).then(function () { done(true); }, function () { done(false); });
67 } else {
68 var ta = document.createElement('textarea');
69 ta.value = text;
70 ta.style.position = 'fixed';
71 ta.style.opacity = '0';
72 document.body.appendChild(ta);
73 ta.select();
74 var ok = false;
75 try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
76 document.body.removeChild(ta);
77 done(ok);
78 }
79 }
80 on('[data-copy]', 'click', function (btn) {
81 var label = btn.querySelector('span');
82 var before = label ? label.textContent : '';
83 copyText(btn.getAttribute('data-copy'), function (ok) {
84 if (!label) return;
85 label.textContent = ok ? 'Copied' : 'Press Ctrl+C';
86 setTimeout(function () { label.textContent = before; }, 1600);
87 });
88 });
89
90 // Share a skill: the device's share sheet where there is one, otherwise copy the link
91 on('[data-share]', 'click', function (btn) {
92 var url = btn.getAttribute('data-share-url');
93 var label = btn.querySelector('span');
94 var before = label ? label.textContent : '';
95 function copied(ok) {
96 if (!label) return;
97 label.textContent = ok ? 'Link copied' : 'Press Ctrl+C';
98 setTimeout(function () { label.textContent = before; }, 1800);
99 }
100 if (navigator.share) {
101 navigator.share({ title: btn.getAttribute('data-share-title'), text: btn.getAttribute('data-share-text'), url: url })
102 .catch(function (e) { if (!e || e.name !== 'AbortError') copyText(url, copied); });
103 } else {
104 copyText(url, copied);
105 }
106 });
107
108 // A shared repo is read one skill per request. Keep asking for the next one until none are left, then show the result.
109 document.querySelectorAll('[data-repo-share]').forEach(function (box) {
110 var url = box.getAttribute('data-repo-share');
111 var status = box.querySelector('[data-repo-share-status]');
112 var fails = 0;
113 function say(t) { if (status) status.textContent = t; }
114 function step() {
115 fetch(url, { method: 'POST', headers: { accept: 'application/json' }, credentials: 'same-origin' })
116 .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, body: j }; }); })
117 .then(function (res) {
118 if (!res.ok) throw new Error('step');
119 fails = 0;
120 if (res.body.left > 0) {
121 say('Skillfarm found ' + res.body.found + (res.body.found === 1 ? ' skill' : ' skills') + ' and is reading them. ' + res.body.left + ' to go.');
122 step();
123 } else {
124 location.reload();
125 }
126 })
127 .catch(function () {
128 fails += 1;
129 if (fails < 4) setTimeout(step, 1500 * fails);
130 else say('Reading paused. The rest are read within a few minutes, and you can close this page. Reload it to check.');
131 });
132 }
133 step();
134 });
135
136 // Send to agent. The visitor's agent is remembered in this browser only.
137 var AGENT_KEY = 'sf-agent';
138 function savedAgent() { try { return localStorage.getItem(AGENT_KEY) || ''; } catch (e) { return ''; } }
139 function saveAgent(a) { try { localStorage.setItem(AGENT_KEY, a); } catch (e) { /* private window */ } }
140 function pickedOption(box) {
141 var pick = box.querySelector('[data-send-pick]');
142 return pick.options[pick.selectedIndex];
143 }
144 function showSend(box, agent) {
145 var pick = box.querySelector('[data-send-pick]');
146 for (var i = 0; i < pick.options.length; i++) if (pick.options[i].value === agent) pick.selectedIndex = i;
147 var opt = pickedOption(box);
148 var href = opt.getAttribute('data-href');
149 box.querySelector('[data-send-go]').setAttribute('href', href || '#');
150 box.querySelector('[data-send-label]').textContent = (href ? 'Send to ' : 'Copy for ') + opt.textContent;
151 box.querySelector('[data-send-note]').textContent = opt.getAttribute('data-note');
152 }
153 function showAgent(agent) {
154 if (!agent) return;
155 document.querySelectorAll('[data-send]').forEach(function (box) { showSend(box, agent); });
156 document.querySelectorAll('[data-agent-tabs] [data-tab="' + agent + '"]').forEach(function (tab) { openTab(tab); });
157 }
158 document.addEventListener('change', function (e) {
159 var pick = e.target;
160 if (!pick.matches || !pick.matches('[data-send-pick]')) return;
161 saveAgent(pick.value);
162 showAgent(pick.value);
163 });
164 on('[data-send-go]', 'click', function (go, e) {
165 var box = go.closest('[data-send]');
166 var opt = pickedOption(box);
167 var note = box.querySelector('[data-send-note]');
168 saveAgent(opt.value);
169 if (!opt.getAttribute('data-href')) e.preventDefault();
170 copyText(opt.getAttribute('data-prompt'), function (ok) {
171 note.textContent = ok ? opt.getAttribute('data-after') : 'Could not copy the prompt here. Use the Copy button next to it instead.';
172 });
173 });
174
175 // Tab sets
176 function openTab(tab) {
177 var set = tab.closest('[data-tabset]');
178 var key = tab.getAttribute('data-tab');
179 set.querySelectorAll('[data-tab]').forEach(function (t) {
180 var active = t === tab;
181 t.classList.toggle('is-active', active);
182 t.setAttribute('aria-selected', active ? 'true' : 'false');
183 });
184 set.querySelectorAll('[data-panel]').forEach(function (p) { p.hidden = p.getAttribute('data-panel') !== key; });
185 }
186
187 on('[data-tabset] [data-tab]', 'click', function (tab) {
188 openTab(tab);
189 // Choosing an agent's tab is choosing your agent.
190 if (tab.closest('[data-agent-tabs]')) {
191 saveAgent(tab.getAttribute('data-tab'));
192 showAgent(tab.getAttribute('data-tab'));
193 }
194 });
195 showAgent(savedAgent());
196
197 // Share form: switch between a GitHub link and pasted text
198 document.querySelectorAll('[data-share-form]').forEach(function (form) {
199 function sync() {
200 var picked = form.querySelector('input[name="mode"]:checked');
201 var mode = picked ? picked.value : 'paste';
202 form.querySelectorAll('[data-mode]').forEach(function (el) {
203 var show = el.getAttribute('data-mode') === mode;
204 el.hidden = !show;
205 el.querySelectorAll('input, textarea').forEach(function (i) { i.disabled = !show; });
206 });
207 }
208 form.querySelectorAll('input[name="mode"]').forEach(function (r) { r.addEventListener('change', sync); });
209 sync();
210 form.addEventListener('submit', function () {
211 var b = form.querySelector('button[type="submit"]');
212 if (b) { b.classList.add('is-disabled'); b.textContent = b.getAttribute('data-busy-label') || 'Submitting…'; }
213 });
214 });
215
216 // Load a local SKILL.md into the paste box
217 document.addEventListener('change', function (e) {
218 var input = e.target;
219 if (!input.matches || !input.matches('[data-skill-file]')) return;
220 var file = input.files && input.files[0];
221 if (!file) return;
222 if (file.size > 200000) { alertInline(input, 'That file is larger than 200 KB.'); return; }
223 var reader = new FileReader();
224 reader.onload = function () {
225 var form = input.closest('form');
226 var area = form && form.querySelector('textarea[name="skill_md"]');
227 if (area) area.value = String(reader.result);
228 };
229 reader.readAsText(file);
230 });
231 function alertInline(el, text) {
232 var note = el.parentNode.querySelector('.file-note');
233 if (!note) {
234 note = document.createElement('small');
235 note.className = 'file-note';
236 el.parentNode.appendChild(note);
237 }
238 note.textContent = ' ' + text;
239 }
240
241 // Avatar: crop to a square and resize in the browser, then upload both sizes
242 document.querySelectorAll('[data-avatar]').forEach(function (box) {
243 var input = box.querySelector('[data-avatar-input]');
244 var status = box.querySelector('[data-avatar-status]');
245 if (!input) return;
246 function say(t) { if (status) status.textContent = t; }
247 function draw(img, size) {
248 var canvas = document.createElement('canvas');
249 canvas.width = size;
250 canvas.height = size;
251 var w = img.naturalWidth || img.width, h = img.naturalHeight || img.height;
252 var side = Math.min(w, h);
253 var ctx = canvas.getContext('2d');
254 ctx.imageSmoothingQuality = 'high';
255 ctx.drawImage(img, (w - side) / 2, (h - side) / 2, side, side, 0, 0, size, size);
256 return canvas;
257 }
258 function toBlob(canvas, type) {
259 return new Promise(function (resolve) { canvas.toBlob(function (b) { resolve(b); }, type, 0.86); });
260 }
261 function encode(canvas) {
262 return toBlob(canvas, 'image/webp').then(function (b) {
263 if (b && b.type === 'image/webp') return b;
264 return toBlob(canvas, 'image/jpeg');
265 });
266 }
267 input.addEventListener('change', function () {
268 var file = input.files && input.files[0];
269 if (!file) return;
270 if (!/^image\/(png|jpeg|webp)$/.test(file.type)) { say('Choose a PNG, JPEG or WebP image.'); return; }
271 if (file.size > 12 * 1024 * 1024) { say('That image is larger than 12 MB.'); return; }
272 say('Preparing…');
273 var url = URL.createObjectURL(file);
274 var img = new Image();
275 img.onload = function () {
276 Promise.all([encode(draw(img, 512)), encode(draw(img, 128))])
277 .then(function (blobs) {
278 URL.revokeObjectURL(url);
279 if (!blobs[0] || !blobs[1]) throw new Error('encode');
280 var ext = blobs[0].type === 'image/webp' ? 'webp' : 'jpg';
281 var fd = new FormData();
282 fd.append('avatar', blobs[0], 'avatar.' + ext);
283 fd.append('avatar_small', blobs[1], 'avatar-128.' + ext);
284 say('Uploading…');
285 return fetch('/api/me/avatar', { method: 'POST', body: fd, headers: { accept: 'application/json' }, credentials: 'same-origin' });
286 })
287 .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, body: j }; }); })
288 .then(function (res) {
289 if (!res.ok) { say(res.body.message || 'The upload did not work.'); return; }
290 say('Saved.');
291 var preview = box.querySelector('[data-avatar-preview]');
292 if (preview && res.body.url) {
293 var fresh = document.createElement('img');
294 fresh.className = 'avatar';
295 fresh.width = 128; fresh.height = 128; fresh.alt = '';
296 fresh.src = res.body.url;
297 preview.innerHTML = '';
298 preview.appendChild(fresh);
299 } else {
300 location.reload();
301 }
302 })
303 .catch(function () { say('The upload did not work. Try a different image.'); });
304 };
305 img.onerror = function () { URL.revokeObjectURL(url); say('That file could not be read as an image.'); };
306 img.src = url;
307 });
308 });
309
310 // Confirm before destructive forms
311 document.addEventListener('submit', function (e) {
312 var form = e.target;
313 if (form.matches && form.matches('form[data-confirm]') && !window.confirm(form.getAttribute('data-confirm'))) e.preventDefault();
314 });
315})();