-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfocusBgViz.js
More file actions
427 lines (341 loc) · 13.7 KB
/
focusBgViz.js
File metadata and controls
427 lines (341 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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
/** @param {NS} ns **/
export async function main(ns) {
ns.disableLog("ALL");
const args = ns.flags([
["bars", 160],
["fade", 1.0],
["smooth", 0.85],
["maxH", 0.85],
["autoHide", false],
["stopOnClose", true],
// override target selection if needed (Focus screen root)
["selector", ""],
]);
const doc = eval("document");
const win = eval("window");
const CANVAS_ID = "bb-focus-viz-canvas";
const STYLE_ID = "bb-focus-viz-style";
const BTN_ID = "bb-focus-viz-btn";
const INJECT_ID = "bb-focus-viz-injected";
function hardCleanup() {
try { win.__bbFocusViz?.destroy?.(); } catch {}
try { delete win.__bbFocusViz; } catch {}
try { doc.getElementById(BTN_ID)?.remove(); } catch {}
try { doc.getElementById(CANVAS_ID)?.remove(); } catch {}
try { doc.getElementById(STYLE_ID)?.remove(); } catch {}
try { doc.getElementById(INJECT_ID)?.remove(); } catch {}
}
hardCleanup();
ns.atExit(hardCleanup);
const cfg = {
canvasId: CANVAS_ID,
styleId: STYLE_ID,
btnId: BTN_ID,
// you can override with --selector
selector: args.selector || "",
// fallback candidates for the Focus screen container
candidates: [
"div.MuiContainer-root.MuiContainer-maxWidthMd",
"div.MuiBox-root.css-1mojy8p-root",
],
bars: Math.max(16, Math.min(500, args.bars | 0)),
fade: Math.max(0, Math.min(1, args.fade)),
smooth: Math.max(0, Math.min(1, args.smooth)),
maxH: Math.max(0.1, Math.min(1, args.maxH)),
autoHide: !!args.autoHide,
stopOnClose: !!args.stopOnClose,
};
function inject() {
if (doc.getElementById(INJECT_ID)) return;
const s = doc.createElement("script");
s.id = INJECT_ID;
s.textContent = `
(() => {
const cfg = ${JSON.stringify(cfg)};
const log = (...a) => console.log("[bbFocusViz]", ...a);
const err = (...a) => console.error("[bbFocusViz]", ...a);
const CANVAS_ID = cfg.canvasId;
const STYLE_ID = cfg.styleId;
const BTN_ID = cfg.btnId;
let audioCtx = null, analyser = null, freq = null, raf = 0, stream = null;
let running = false;
let attachedTarget = null;
let lastStable = 0;
// ---------- helpers ----------
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = \`
.bb-focus-viz-target { position: relative !important; }
#\${CANVAS_ID} {
position: absolute !important;
top: 0 !important;
bottom: 0 !important;
left: 50% !important;
transform: translateX(-50%) !important;
width: 100vw !important;
height: 100% !important;
z-index: 0 !important;
pointer-events: none !important;
}
.bb-focus-viz-target > *:not(#\${CANVAS_ID}) {
position: relative !important;
z-index: 1 !important;
}
#\${BTN_ID} {
position: absolute !important;
top: 4px !important;
right: 0px !important;
z-index: 5 !important;
pointer-events: auto !important;
padding: 6px 10px !important;
font-size: 12px !important;
line-height: 1 !important;
letter-spacing: 0.02em !important;
border-radius: 6px !important;
border: 1px solid rgba(255,140,0,0.55) !important;
background: rgba(0,0,0,0.55) !important;
color: rgba(255,180,80,0.95) !important;
box-shadow: 0 0 0 1px rgba(0,0,0,0.65) inset !important;
cursor: pointer !important;
opacity: 0.92 !important;
user-select: none !important;
}
#\${BTN_ID}:hover { opacity: 1 !important; }
#\${BTN_ID}[data-state="on"] {
border-color: rgba(120,255,120,0.55) !important;
color: rgba(170,255,170,0.92) !important;
}
#\${BTN_ID}:disabled { opacity: 0.6 !important; cursor: default !important; }
\`;
document.head.appendChild(style);
}
function elCanvas() { return document.getElementById(CANVAS_ID); }
function elBtn() { return document.getElementById(BTN_ID); }
function setBtn(state, text, disabled) {
const b = elBtn();
if (!b) return;
b.setAttribute("data-state", state);
b.textContent = text;
b.disabled = !!disabled;
}
function findFocusTarget() {
if (cfg.selector) return document.querySelector(cfg.selector);
for (const sel of (cfg.candidates || [])) {
const el = document.querySelector(sel);
if (el) return el;
}
return null;
}
function isFocusExitButtonText(t) {
return t.includes("Stop Faction work") || t.includes("Do something else simultaneously");
}
function findFocusEntryButton() {
// your provided button: textContent === "Focus" (ignoring ripple span)
// keep it simple and robust: look for a button whose visible text starts with Focus
const btns = Array.from(document.querySelectorAll("button"));
for (const b of btns) {
const t = (b.textContent || "").trim();
if (t === "Focus" || t.startsWith("Focus")) return b;
}
return null;
}
// ---------- canvas attach ----------
function attachTo(target) {
if (!target) return false;
ensureStyle();
// ensure we don't leave stuff elsewhere
if (attachedTarget && attachedTarget !== target) {
try { attachedTarget.classList.remove("bb-focus-viz-target"); } catch {}
}
attachedTarget = target;
target.classList.add("bb-focus-viz-target");
// canvas
let canvas = document.getElementById(CANVAS_ID);
if (canvas && canvas.parentElement !== target) canvas.remove();
canvas = document.getElementById(CANVAS_ID);
if (!canvas) {
canvas = document.createElement("canvas");
canvas.id = CANVAS_ID;
target.insertBefore(canvas, target.firstChild);
}
// toggle button (only inside Focus screen, created only on entry)
let b = document.getElementById(BTN_ID);
if (b && b.parentElement !== target) b.remove();
b = document.getElementById(BTN_ID);
if (!b) {
b = document.createElement("button");
b.id = BTN_ID;
b.setAttribute("data-state", "off");
b.textContent = "Enable viz";
b.addEventListener("click", () => toggle(), false);
target.appendChild(b);
}
// bind exit buttons *now that we are in Focus*
bindExitButtons();
return true;
}
// ---------- audio viz ----------
function fitCanvas(canvas) {
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
const w = Math.max(1, Math.floor(rect.width * dpr));
const h = Math.max(1, Math.floor(rect.height * dpr));
if (canvas.width !== w || canvas.height !== h) {
canvas.width = w;
canvas.height = h;
}
return { dpr, rect };
}
function drawLoop() {
if (!running) return;
raf = requestAnimationFrame(drawLoop);
const canvas = elCanvas();
if (!canvas || !analyser) return;
const { dpr, rect } = fitCanvas(canvas);
const ctx = canvas.getContext("2d", { alpha: true });
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
analyser.getByteFrequencyData(freq);
if (!freq || !freq.length) return;
const w = rect.width;
const h = rect.height;
ctx.fillStyle = "rgba(0,0,0," + cfg.fade + ")";
ctx.fillRect(0, 0, w, h);
const bins = freq.length;
// hard cutoff on the right: only use low/mid frequencies
const rightCut = Math.min(bins - 1, 336); // try 256, 384, 512
const BARS = Math.max(64, Math.min(800, Math.floor(w / 6)));
const barW = w / BARS;
// normalize peak within the used range
let peak = 1;
for (let k = 0; k <= rightCut; k++) if (freq[k] > peak) peak = freq[k];
const gamma = 0.65; // optional boost, 1 = linear
for (let i = 0; i < BARS; i++) {
const t = i / Math.max(1, BARS - 1);
const idx = Math.floor(t * rightCut);
let v = freq[idx] / peak;
if (!Number.isFinite(v)) v = 0;
v = Math.pow(v, gamma);
const bh = v * h * cfg.maxH;
const hue = (i * 2) % 360;
const light = 20 + v * 55;
ctx.fillStyle = "hsl(" + hue + ", 90%, " + light + "%)";
const x = i * barW;
ctx.fillRect(x, h - bh, Math.max(1, barW - 2), bh);
}
}
async function start() {
if (running) return;
setBtn("off", "Requesting…", true);
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
analyser.smoothingTimeConstant = cfg.smooth;
if (audioCtx.state === "suspended") await audioCtx.resume();
stream = await navigator.mediaDevices.getUserMedia({
audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false }
});
const src = audioCtx.createMediaStreamSource(stream);
src.connect(analyser);
freq = new Uint8Array(analyser.frequencyBinCount);
running = true;
setBtn("on", "Disable viz", false);
if (cfg.autoHide) {
setTimeout(() => { const b = elBtn(); if (b) b.style.display = "none"; }, 900);
}
log("started");
drawLoop();
} catch (e) {
err("start failed:", e);
running = false;
setBtn("off", "Enable viz (failed)", false);
}
}
function stop() {
running = false;
try { cancelAnimationFrame(raf); } catch {}
raf = 0;
if (cfg.stopOnClose) {
try { stream && stream.getTracks().forEach(t => t.stop()); } catch {}
stream = null;
try { audioCtx && audioCtx.close(); } catch {}
audioCtx = null;
analyser = null;
freq = null;
}
const b = elBtn();
if (b) b.style.display = "";
setBtn("off", "Enable viz", false);
log("stopped");
}
function toggle() { running ? stop() : start(); }
function destroy() {
stop();
try { document.getElementById(BTN_ID)?.remove(); } catch {}
try { document.getElementById(CANVAS_ID)?.remove(); } catch {}
try { attachedTarget?.classList?.remove?.("bb-focus-viz-target"); } catch {}
attachedTarget = null;
log("destroyed");
}
// ---------- exit buttons: destroy on click ----------
function bindExitButtons() {
const btns = Array.from(document.querySelectorAll("button"));
for (const b of btns) {
const t = (b.textContent || "").trim();
if (!t) continue;
if (!isFocusExitButtonText(t)) continue;
if (b.dataset.bbFocusVizExitBound === "1") continue;
b.dataset.bbFocusVizExitBound = "1";
b.addEventListener("click", () => {
try { window.__bbFocusViz?.destroy?.(); } catch {}
}, true);
}
}
// ---------- Focus entry: create only when entering ----------
function bindFocusEntry() {
const entry = findFocusEntryButton();
if (!entry) return;
if (entry.dataset.bbFocusVizEntryBound === "1") return;
entry.dataset.bbFocusVizEntryBound = "1";
entry.addEventListener("click", () => {
// after clicking Focus, wait until Focus UI is rendered then attach
const startTs = performance.now();
const timeoutMs = 2500;
const tick = () => {
const target = findFocusTarget();
if (target) {
attachTo(target);
log("attached on Focus entry");
return;
}
if (performance.now() - startTs > timeoutMs) {
err("timed out waiting for Focus target");
return;
}
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
}, true);
}
// ---------- observer: keep entry binding alive even if nav re-renders ----------
const mo = new MutationObserver(() => {
try { bindFocusEntry(); } catch {}
// if we're currently attached, keep exit buttons bound (react likes to rebuild)
try { if (attachedTarget) bindExitButtons(); } catch {}
});
mo.observe(document.documentElement, { childList: true, subtree: true });
// initial bind
bindFocusEntry();
window.__bbFocusViz = { start, stop, toggle, destroy };
log("controller injected");
})();
`;
doc.documentElement.appendChild(s);
}
inject();
ns.toast("Focus viz: injected. It will only appear after clicking Focus.", "info", 4000);
// keep script alive
while (true) await ns.sleep(60000);
}