Repository navigation
Expand file tree
/
Copy pathstash-tcode.user.js
More file actions
2737 lines (2489 loc) · 126 KB
/
Copy pathstash-tcode.user.js
File metadata and controls
2737 lines (2489 loc) · 126 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
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Stash-TCode
// @namespace https://github.com/dtt-git/stash-tcode
// @version 0.7.0
// @description Drive TCode devices from Stash over USB Web Serial, with optional heart-rate modulation
// @author dtt (originally by Spunkle, modded by Steel)
// @include /^https?:\/\/[^\/?#]+:9999\//
// @grant GM_setValue
// @grant GM_getValue
// @grant unsafeWindow
// @license GPLv3
// @homepageURL https://github.com/dtt-git/stash-tcode
// @supportURL https://github.com/dtt-git/stash-tcode/issues
// @updateURL https://raw.githubusercontent.com/dtt-git/stash-tcode/main/stash-tcode.user.js
// @downloadURL https://raw.githubusercontent.com/dtt-git/stash-tcode/main/stash-tcode.user.js
// ==/UserScript==
// The last userscript release. Stash-TCode is now a Stash plugin (plugins/stash-tcode/), and this
// file stays at 0.7.0: Tampermonkey installs update to it, then get nothing further. It tells
// them so, and hands its settings to the plugin once that's installed.
// Wrapped so that, loaded as a Stash plugin, none of this lands in the page's globals.
(function(){
// --- HOST ---
// This one file runs two ways: as a Stash UI plugin (Stash loads it into the page) and as a
// Tampermonkey userscript. Only the userscript gets the GM_* functions.
const IS_USERSCRIPT = typeof GM_getValue === 'function';
const TCODE_VERSION = '0.7.0'; // keep in step with @version above and plugins/stash-tcode/stash-tcode.yml
const PLUGIN_ID = 'stash-tcode';
const README_URL = 'https://github.com/dtt-git/stash-tcode#install';
// The page's own window, where Stash's PluginApi lives. A userscript reaches it through unsafeWindow.
const pageWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
const STORE_PREFIX = 'stash-tcode:';
// Settings a userscript install hands over to the plugin on the same Stash (see handOffToPlugin).
const HANDOFF_KEY = STORE_PREFIX + 'userscript-settings';
// Saved values: Tampermonkey's storage for the userscript, localStorage for the plugin.
// Both are per browser, like the serial and Bluetooth permissions the settings refer to.
function storeGet(key, fallback){
if(IS_USERSCRIPT){ return GM_getValue(key, fallback); }
try {
var raw = localStorage.getItem(STORE_PREFIX + key);
return raw == null ? fallback : JSON.parse(raw);
} catch(e) { return fallback; }
}
function storeSet(key, value){
if(IS_USERSCRIPT){ GM_setValue(key, value); return; }
try { localStorage.setItem(STORE_PREFIX + key, JSON.stringify(value)); }
catch(e) { console.error("[TCode] Couldn't save settings:", e); }
}
// Whether the Stash-TCode plugin is installed and enabled on this Stash.
async function pluginEnabled(){
try {
var data = await stashGql("{ plugins { id enabled } }");
return (data.plugins || []).some(function(p){ return p.id === PLUGIN_ID && p.enabled; });
} catch(e) { return false; } // no answer: carry on as a userscript
}
// The userscript, finding the plugin installed, leaves its settings where the plugin will pick
// them up and steps aside: two copies in one page would both drive the device.
function handOffToPlugin(){
var copied = false;
try {
if(localStorage.getItem(HANDOFF_KEY) == null){
localStorage.setItem(HANDOFF_KEY, JSON.stringify(settings));
copied = true;
}
} catch(e) {}
console.log("[TCode] The Stash-TCode plugin is installed, so the userscript isn't running.");
showToast("Stash-TCode plugin installed",
(copied ? "Your settings were copied to the plugin and apply after a refresh. " : "") +
"Remove the Stash-TCode userscript from Tampermonkey: the plugin replaces it.", "warning", 15000);
}
// The plugin takes over settings a userscript handed over (see handOffToPlugin), once: they
// hold the ranges and devices the user actually set up. Later changes made in the plugin stand.
function importUserscriptSettings(own){
if(own && own.importedUserscript){ return own; }
try {
var raw = localStorage.getItem(HANDOFF_KEY);
if(raw == null){ return own; }
var handed = JSON.parse(raw);
handed.importedUserscript = true;
storeSet("settings", handed);
console.log("[TCode] Took over the userscript's settings");
return handed;
} catch(e) { return own; }
}
// ---------------------------------
var video="";
var lastPage = null;
var settings = loadSettings();
// --- SERIAL VARIABLES ---
var port = null;
var writer = null;
var keepReading = false;
var serialConnected = false;
var reader = null;
var readableStreamClosed = null;
var writableStreamClosed = null;
var textEncoder = new TextEncoder();
var serialBuffer = ""; // Buffer for accumulating fragmented serial responses
var bufferTimeout = null;
// ------------------------
var scriptList = null;
var scriptListRequest = null; // the in-flight Interactive Tools lookup, shared by all axes
var AXIS = new Object();
var pending = false;
var msPending = false;
var lastActionMs = null; // last playhead position we served, for seek detection
var SEEK_THRESHOLD_MS = 1000; // forward jump beyond this is treated as a seek
var boundPlayer = null; // the <video> our listeners are currently attached to
var lastSrc = null; // last media source seen, for transcode offset caching
var streamOffsetMs = 0; // scene-time offset of the current stream (transcode)
var videoPlayerLoaded = false;
var saveLimitsTimeout = null; // debounce handle for persisting axis ranges
var limitsReady = false; // true once saved ranges are restored; gates persistence so startup can't overwrite storage
const BOTH = 0;
const LOWER = 1;
const UPPER = 2;
function isNewerVersion (oldVer, newVer) {
const oldParts = oldVer.split('.')
const newParts = newVer.split('.')
for (var i = 0; i < newParts.length; i++) {
const a = ~~newParts[i]; const b = ~~oldParts[i];
if (a > b) return true; if (a < b) return false;
}
return false;
}
function handleUpgrade(thisVersion){
if(settings.currentVersion === undefined || isNewerVersion(settings.currentVersion, thisVersion)){
return true;
}
return false;
}
function getLimit(axis, which=BOTH){
var limits = [0, 9999];
if(AXIS && AXIS[axis] && AXIS[axis].limits){
limits = AXIS[axis].limits;
} else if(settings.axes && settings.axes[axis] && settings.axes[axis].limits){
limits = settings.axes[axis].limits; // fall back to saved range for the UI (e.g. menu opened before connect)
}
switch(which){
case BOTH: return limits;
case LOWER: return limits[0];
case UPPER: return limits[1];
}
}
function debug(text, value=""){
if(settings.debug){
if(value == ""){ console.log(text); } else { pageWindow[value] = text; }
}
}
// Persist current in-memory axis ranges to storage (debounced).
// Called from setLimits() so scroll-wheel AND slider changes survive refresh.
function persistLimitsSoon(){
if(!limitsReady){ return; } // don't save until saved ranges have been restored on load
if(saveLimitsTimeout){ clearTimeout(saveLimitsTimeout); }
saveLimitsTimeout = setTimeout(function(){
for(var ax in AXIS){
if(AXIS[ax] && AXIS[ax].limits != null && settings.axes[ax]){
settings.axes[ax].limits = [AXIS[ax].limits[0], AXIS[ax].limits[1]];
}
}
storeSet("settings", settings);
debug("[TCode] Persisted axis ranges to storage");
}, 300);
}
function saveSettings(){
storeSet("settings", settings);
publishDebugApi();
}
function loadSettings(){
var thisVersion = TCODE_VERSION;
var axisDefaults = function(enabled){ return {enabled: enabled, invert: false, center: null, autoCenter: true, auto: false, autoHz: 0.5,
speedLimit: false, maxSpeed: 5, link: "", linkOverride: false}; };
var defaultSettings = {"debug": false, "sync": 0, "autoConnect": true, "serialPort": null, "showHud": true, "knownAxes": [],
"showNotifications": true, "centerTime": 1000, "homeEnabled": true,
"axes": { L0: axisDefaults(true), L1: axisDefaults(false), L2: axisDefaults(false),
R0: axisDefaults(false), R1: axisDefaults(false), R2: axisDefaults(false) },
"hr": { deviceId: null, deviceName: null, enabled: false,
edgeHr: 140, band: 10, floor: 30, rejoinSec: 8, timeoutSec: 8,
decay: true, decayEvery: 2, decayBpm: 2, decayFloor: 105,
climaxRampSec: 45, climaxHoldSec: 20, climaxEaseSec: 15, climaxTag: "Climax" },
"currentVersion": thisVersion};
settings = storeGet("settings", null);
if(!IS_USERSCRIPT){ settings = importUserscriptSettings(settings); }
if(settings == null){ settings = defaultSettings; }
handleUpgrade(thisVersion);
// "Climax HR" was renamed "Edge HR": it's where an edge is called, not a climax.
// Carry the old value over before defaults are filled in.
if(settings.hr && settings.hr.climaxHr != null){
if(settings.hr.edgeHr == null){ settings.hr.edgeHr = settings.hr.climaxHr; }
delete settings.hr.climaxHr;
}
// The speed limit started as one global setting (in full travels/s as "maxSpeed",
// then TCode units/s as "maxUnitsPerSec"). It's now per axis, in full travels/s like
// MultiFunPlayer. Carry a global setting onto every axis.
var globalLimit = settings.maxUnitsPerSec != null ? settings.maxUnitsPerSec / 9999
: (settings.maxSpeed != null ? settings.maxSpeed : null);
if(settings.axes && (globalLimit != null || settings.speedLimit != null)){
for(const ax in settings.axes){
var a = settings.axes[ax];
if(a.maxSpeed == null && globalLimit != null){ a.maxSpeed = Math.round(globalLimit * 4) / 4; }
if(a.speedLimit == null){ a.speedLimit = !!settings.speedLimit; }
}
}
delete settings.speedLimit; delete settings.maxUnitsPerSec; delete settings.maxSpeed;
// Axes the device has reported before (see processLimits). Installs that have already
// connected a device have seen all of theirs, so their on/off choices stand.
if(settings.knownAxes === undefined){
settings.knownAxes = settings.serialPort ? ["L0", "L1", "L2", "R0", "R1", "R2"] : [];
}
backfillDefaults(settings, defaultSettings);
// Drop settings for features that no longer exist (hotkeys, random motion).
for(const gone of ["device", "initialKey", "minKey", "settingsKey", "syncKey"]){ delete settings[gone]; }
for(const ax in settings.axes){ delete settings.axes[ax].random; }
delete settings.hr.restingHr;
return settings;
}
// Fill in any key missing from `target`, recursing into nested objects, so settings
// groups added after a user's settings were first written get their defaults on upgrade.
// Arrays and null count as values, not groups.
function backfillDefaults(target, defaults){
for(const k in defaults){
var d = defaults[k];
if(target[k] === undefined){
target[k] = (d && typeof d === "object" && !Array.isArray(d)) ? JSON.parse(JSON.stringify(d)) : d;
}else if(d && typeof d === "object" && !Array.isArray(d) && target[k] && typeof target[k] === "object"){
backfillDefaults(target[k], d);
}
}
}
// --- UI TOOLKIT ---
// Everything is built from Stash's own markup (Bootstrap 4 + its .setting-section/.setting
// rows), so it picks up Stash's theme, including any custom CSS the user has installed.
// The stylesheet below only covers layout details and the range sliders, which Stash
// doesn't style.
var STASH = { bg: "#202b33", card: "#30404d", input: "#394b59", accent: "#137cbd", text: "#f5f8fa",
muted: "#bfccd6", success: "#0f9960", warning: "#d9822b", danger: "#db3737" };
function injectUiStyles(){
if(document.getElementById('tcode-ui-styles')){ return; }
var s = document.createElement('style');
s.id = 'tcode-ui-styles';
s.textContent = `
#tcode-modal .modal-header { align-items: center; }
#tcode-modal .modal-title { display: flex; align-items: center; gap: .5rem; }
#tcode-modal .modal-body { padding-top: .5rem; }
#tcode-modal .nav-tabs { margin: 0 0 1rem; }
#tcode-modal .nav-tabs .nav-link { cursor: pointer; }
#tcode-modal .setting-section h1 { font-size: 1.1rem; margin-bottom: .25rem; }
#tcode-modal .setting-section > .sub-heading { color: ${STASH.muted}; margin: 0 0 .5rem; }
#tcode-modal .setting-section:not(:first-child) { margin-top: 1.25rem; }
#tcode-modal .setting { gap: 1rem; padding: 12px 15px; }
#tcode-modal .setting > div:first-child { flex: 1 1 auto; min-width: 0; }
#tcode-modal .setting > div:last-child { flex: 0 0 auto; min-width: 0; }
#tcode-modal .setting h3 { font-size: 1rem; }
#tcode-modal .setting .sub-heading { color: ${STASH.muted}; margin-top: .25rem; }
#tcode-modal .setting.sub-setting { padding-left: 2rem; }
#tcode-modal .setting.disabled > div:last-child { opacity: .5; pointer-events: none; }
#tcode-modal .setting-group { padding-bottom: 0; }
#tcode-modal .setting-group:not(:last-child) { border-bottom: 1px solid #000; }
#tcode-modal .setting-group > .setting { border-bottom: none; }
#tcode-modal .setting-group .setting { flex-wrap: nowrap; } /* Stash wraps grouped rows; keep controls beside their label */
#tcode-modal .setting-group.collapsed > .setting:not(:first-child) { display: none; }
#tcode-modal .modal-footer { justify-content: space-between; }
#tcode-modal .tcode-version { color: ${STASH.muted}; font-size: .8rem; }
#tcode-modal .tcode-number { width: 90px; text-align: right; display: inline-block; }
#tcode-modal .tcode-suffix { margin-left: .4rem; color: ${STASH.muted}; }
#tcode-modal .tcode-status { display: inline-flex; align-items: center; gap: .4rem; }
#tcode-modal .tcode-dot { width: 8px; height: 8px; border-radius: 50%; background: ${STASH.danger}; display: inline-block; }
#tcode-modal .tcode-dot.on { background: ${STASH.success}; }
#tcode-modal .tcode-list { margin: .25rem 0 0; padding-left: 1.1rem; color: ${STASH.muted}; }
/* Range sliders: thin track in the input colour, accent fill, light thumb. */
.tcode-range { display: flex; align-items: center; gap: .6rem; width: 360px; max-width: 100%; }
.tcode-range .tcode-track { position: relative; flex: 1 1 auto; height: 20px; }
.tcode-range input[type=range] {
-webkit-appearance: none; appearance: none; position: absolute; inset: 0; width: 100%; height: 20px;
margin: 0; background: transparent; outline: none; --lo: 0%; --hi: 0%;
}
.tcode-range input[type=range]::-webkit-slider-runnable-track {
height: 4px; border-radius: 2px;
background: linear-gradient(to right, ${STASH.input} 0 var(--lo), ${STASH.accent} var(--lo) var(--hi), ${STASH.input} var(--hi) 100%);
}
.tcode-range input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none; appearance: none; width: 14px; height: 14px; margin-top: -5px; border-radius: 50%;
background: ${STASH.text}; box-shadow: 0 0 0 1px rgba(16,22,26,.4), 0 1px 2px rgba(16,22,26,.4); cursor: pointer;
}
.tcode-range input[type=range]:focus-visible::-webkit-slider-thumb { box-shadow: 0 0 0 3px rgba(19,124,189,.6); }
.tcode-range input[type=range]:disabled::-webkit-slider-thumb { background: ${STASH.muted}; cursor: default; }
.tcode-range.dual input[type=range] { pointer-events: none; }
.tcode-range.dual input[type=range]::-webkit-slider-thumb { pointer-events: auto; }
.tcode-range.dual input[type=range].upper::-webkit-slider-runnable-track { background: transparent; }
.tcode-range output { min-width: 10.5em; text-align: right; font-variant-numeric: tabular-nums; color: ${STASH.text}; font-size: .9rem; }
/* Toasts, in Stash's secondary colour with a coloured edge per type. */
#tcode-toasts { position: fixed; bottom: 1.5rem; left: 50%; transform: translateX(-50%); z-index: 1080;
display: flex; flex-direction: column-reverse; gap: .5rem; pointer-events: none; width: 360px; max-width: calc(100vw - 32px); }
.tcode-toast { background: ${STASH.input}; color: ${STASH.text}; border-radius: 3.5px; border-left: 4px solid ${STASH.accent};
box-shadow: 0 2px 8px rgba(16,22,26,.5); padding: .5rem .75rem; font-size: .875rem;
transition: opacity .25s ease, transform .25s ease; }
.tcode-toast.success { border-left-color: ${STASH.success}; }
.tcode-toast.warning { border-left-color: ${STASH.warning}; }
.tcode-toast.error { border-left-color: ${STASH.danger}; }
.tcode-toast .tcode-toast-title { font-weight: 600; }
.tcode-toast .tcode-toast-body { color: ${STASH.muted}; margin-top: .1rem; }
.tcode-toast.hiding { opacity: 0; transform: translateY(-6px); }
`;
document.head.appendChild(s);
}
// Tiny DOM builder. props: class, text, style (cssText), on<event> handlers; value,
// checked and disabled are set as properties; anything else becomes an attribute.
function el(tag, props, children){
var e = document.createElement(tag);
for(var k in (props || {})){
var v = props[k];
if(v == null || v === false && k !== 'value'){ continue; }
if(k === 'class'){ e.className = v; }
else if(k === 'text'){ e.textContent = v; }
else if(k === 'style'){ e.style.cssText = v; }
else if(k === 'value' || k === 'checked' || k === 'disabled'){ e[k] = v; }
else if(k.indexOf('on') === 0){ e.addEventListener(k.slice(2), v); }
else { e.setAttribute(k, v); }
}
for(var c of (children || [])){
if(c == null){ continue; }
e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
}
return e;
}
// A Stash settings section: heading, optional sub-heading, and the card rows go into.
function uiSection(parent, title, subheading){
var card = el('div', {class: 'card'});
parent.appendChild(el('div', {class: 'setting-section'}, [
el('h1', {text: title}),
subheading ? el('div', {class: 'sub-heading', text: subheading}) : null,
card
]));
return card;
}
// One Stash settings row: title and hint on the left, control on the right.
function uiSetting(parent, title, hint, control, opts){
opts = opts || {};
var row = el('div', {class: 'setting' + (opts.sub ? ' sub-setting' : '') + (opts.disabled ? ' disabled' : '')}, [
el('div', null, [el('h3', {text: title}), hint ? el('div', {class: 'sub-heading', text: hint}) : null]),
el('div', null, [control])
]);
parent.appendChild(row);
return row;
}
function uiSwitch(id, checked, onChange){
var input = el('input', {type: 'checkbox', id: 'tcode-' + id, class: 'custom-control-input', checked: !!checked,
onchange: function(){ onChange(input.checked); }});
return el('div', {class: 'custom-control custom-switch'}, [input, el('label', {class: 'custom-control-label', for: 'tcode-' + id})]);
}
function uiButton(label, variant, onClick, opts){
opts = opts || {};
return el('button', {type: 'button', class: 'btn btn-' + (variant || 'secondary') + (opts.small ? ' btn-sm' : ''),
text: label, disabled: !!opts.disabled, onclick: onClick});
}
// Number box. Out-of-range or empty input snaps back to the nearest valid value on change.
function uiNumber(id, value, o, onChange){
var input = el('input', {type: 'number', id: 'tcode-' + id, class: 'input-control form-control form-control-sm tcode-number',
min: o.min, max: o.max, step: o.step || 1, value: value});
input.addEventListener('change', function(){
var v = parseFloat(input.value);
if(!isFinite(v)){ v = value; }
v = Math.min(o.max, Math.max(o.min, v));
input.value = v; value = v;
onChange(v);
});
return el('span', null, [input, o.suffix ? el('span', {class: 'tcode-suffix', text: o.suffix}) : null]);
}
function setRangeFill(input, loPct, hiPct){
input.style.setProperty('--lo', loPct + '%');
input.style.setProperty('--hi', hiPct + '%');
}
// Single slider with a readout. o: {min, max, step, format(v), origin}. The fill runs from
// `origin` (default min) to the value. onInput fires while dragging, onChange on release.
// Returns {el, set(v), setDisabled(bool)}.
function uiRange(id, value, o, onInput, onChange){
var fmt = o.format || function(v){ return String(v); };
var input = el('input', {type: 'range', id: 'tcode-' + id, min: o.min, max: o.max, step: o.step || 1, value: value});
var out = el('output', {for: 'tcode-' + id});
var toPct = function(v){ return (v - o.min) / (o.max - o.min) * 100; };
function paint(){
var v = parseFloat(input.value), from = toPct(o.origin != null ? o.origin : o.min), to = toPct(v);
setRangeFill(input, Math.min(from, to), Math.max(from, to));
out.textContent = fmt(v);
}
input.addEventListener('input', function(){ paint(); if(onInput){ onInput(parseFloat(input.value)); } });
input.addEventListener('change', function(){ if(onChange){ onChange(parseFloat(input.value)); } });
paint();
return {
el: el('div', {class: 'tcode-range'}, [el('div', {class: 'tcode-track'}, [input]), out]),
set: function(v){ input.value = v; paint(); },
setDisabled: function(d){ input.disabled = d; }
};
}
// Two-handled range slider: two overlapping range inputs whose thumbs can't cross.
// onInput(lo, hi) fires while dragging, onChange(lo, hi) on release.
function uiDualRange(id, lo, hi, o, onInput, onChange){
var fmt = o.format || function(v){ return String(v); };
var lower = el('input', {type: 'range', class: 'lower', id: 'tcode-' + id + '-min', min: o.min, max: o.max, step: o.step || 1, value: lo,
'aria-label': 'Minimum'});
var upper = el('input', {type: 'range', class: 'upper', id: 'tcode-' + id + '-max', min: o.min, max: o.max, step: o.step || 1, value: hi,
'aria-label': 'Maximum'});
var out = el('output');
function values(){ return [parseFloat(lower.value), parseFloat(upper.value)]; }
function paint(){
var v = values(), span = o.max - o.min;
setRangeFill(lower, (v[0] - o.min) / span * 100, (v[1] - o.min) / span * 100);
out.textContent = fmt(v[0]) + ' – ' + fmt(v[1]);
// Upper sits above lower so its thumb isn't crossed by the lower's track; flip that
// when the lower thumb is near the top end, or it couldn't be grabbed there.
var lowerOnTop = v[0] > o.max - span * 0.05;
lower.style.zIndex = lowerOnTop ? 2 : 1;
upper.style.zIndex = lowerOnTop ? 1 : 2;
}
function onMove(e){
var v = values();
if(v[0] > v[1]){
if(e.target === lower){ lower.value = v[1]; } else { upper.value = v[0]; }
}
paint();
if(onInput){ onInput.apply(null, values()); }
}
lower.addEventListener('input', onMove); upper.addEventListener('input', onMove);
lower.addEventListener('change', function(){ if(onChange){ onChange.apply(null, values()); } });
upper.addEventListener('change', function(){ if(onChange){ onChange.apply(null, values()); } });
paint();
return { el: el('div', {class: 'tcode-range dual'}, [el('div', {class: 'tcode-track'}, [lower, upper]), out]) };
}
// --- TOASTS ---
function showToast(title, message, type = 'info', duration = 4000) {
if (!settings.showNotifications) return;
injectUiStyles();
var box = document.getElementById('tcode-toasts');
if(!box){ box = el('div', {id: 'tcode-toasts', role: 'status', 'aria-live': 'polite'}); document.body.appendChild(box); }
var toast = el('div', {class: 'tcode-toast ' + type}, [
el('div', {class: 'tcode-toast-title', text: title}),
message ? el('div', {class: 'tcode-toast-body', text: message}) : null
]);
box.appendChild(toast);
setTimeout(function(){
toast.classList.add('hiding');
setTimeout(function(){ toast.remove(); }, 250);
}, duration);
}
// ---------------------------------
// --- NAVBAR BUTTON (appended to the very end of the Donate/Stats/Settings/Help cluster) ---
// Persistent styles for the status dot. Added once; unlike the settings stylesheet
// this must NOT be torn down when the menu closes.
function injectNavStyles(){
if(document.getElementById('tcode-nav-styles')){ return; }
var s = document.createElement('style');
s.id = 'tcode-nav-styles';
s.textContent = `
#tcode-nav-btn { display: flex; align-items: center; }
#tcode-nav-btn .tcode-nav-dot {
display: inline-block; width: 8px; height: 8px; border-radius: 50%;
margin-right: 6px; flex-shrink: 0; background: #db3737;
transition: background 0.2s ease;
}
#tcode-nav-btn.connected .tcode-nav-dot { background: #0f9960; }
#tcode-nav-btn .tcode-nav-hr { margin-left: 8px; font-variant-numeric: tabular-nums; }
#tcode-nav-btn .tcode-nav-heart { color: #ff7373; margin-right: 3px; }
`;
document.head.appendChild(s);
}
// Reflect current serial status on the nav button (dot colour + label + tooltip).
function updateNavButton(){
refreshSettingsTab('device');
var btn = document.getElementById('tcode-nav-btn');
if(!btn){ return; }
var labelText = btn.querySelector('.tcode-nav-label-text');
if(serialConnected){
btn.classList.add('connected');
btn.title = "TCode: Connected — click for settings";
if(labelText){ labelText.textContent = "Connected"; }
}else{
btn.classList.remove('connected');
btn.title = "TCode: Not connected — click for settings";
if(labelText){ labelText.textContent = "Connect"; }
}
}
function createNavButton(){
injectNavStyles();
var btn = document.createElement('button');
btn.id = 'tcode-nav-btn';
btn.type = 'button';
// Match the Stats/Settings button classes (flex + vertically centered) plus Stash's
// own nav-utility styling, so it sits flush with its neighbors.
btn.className = 'nav-utility minimal d-flex align-items-center h-100 btn btn-primary';
btn.innerHTML = '<span class="tcode-nav-dot"></span>' +
'<span class="d-none d-sm-inline tcode-nav-label-text">Connect</span>' +
'<span class="tcode-nav-hr" style="display: none"><span class="tcode-nav-heart">♥</span><span class="tcode-nav-bpm"></span></span>';
btn.addEventListener('click', function(){ toggleMenu(); });
return btn;
}
// Append the button as the very last child of the Donate/Stats/Settings/Help cluster
// (.navbar-buttons — distinct from the primary Scenes/Images/.../Tags nav-link list,
// which is also, confusingly, classed .navbar-nav). No-op if already present, so the
// keep-alive interval can call it freely.
function injectNavButton(){
if(document.getElementById('tcode-nav-btn')){ return; }
var navButtons = document.querySelector('.navbar-buttons');
if(!navButtons){ return; } // navbar not rendered yet; the keep-alive will retry
navButtons.appendChild(createNavButton()); // very end of the cluster
updateNavButton();
updateHrUi();
}
// As a plugin, the button goes in through Stash's patchable navbar utility items, so React
// keeps it in place across re-renders. Stash renders those items twice, in the collapsed
// menu and in the .navbar-buttons cluster; the button goes in the cluster only.
function patchNavButton(api){
var React = api.React;
function TcodeNavSlot(){
var ref = React.useRef(null);
React.useEffect(function(){
var slot = ref.current;
if(!slot || !slot.closest('.navbar-buttons') || document.getElementById('tcode-nav-btn')){ return; }
slot.appendChild(createNavButton());
updateNavButton();
updateHrUi();
return function(){ slot.textContent = ''; };
}, []);
return React.createElement('div', {ref: ref, className: 'tcode-nav-slot d-flex align-items-center'});
}
// Stash appends the rendered result after the call's args, and another plugin's before
// patch can change how many args there are, so the result is the last one.
api.patch.after("MainNavBar.UtilityItems", function(){
return React.createElement(React.Fragment, null, arguments[arguments.length - 1], React.createElement(TcodeNavSlot));
});
}
function startNavButton(){
var api = pageWindow.PluginApi;
// Stash loads plugins before it first draws the navbar, so the patch is in place in time.
if(!IS_USERSCRIPT && api && api.patch && api.React){ patchNavButton(api); return; }
// A userscript starts after the navbar is drawn, and Stash re-renders it on navigation,
// which can drop our button. Re-inject on an interval (cheap; a no-op while it's there).
injectNavButton();
setInterval(injectNavButton, 1000);
}
// --- SETTINGS DIALOG ---
// A Stash-style modal with a tab per area. Controls write straight into `settings` and
// persist immediately, so closing the dialog never has anything left to save.
var AXIS_LIST = ["L0", "L1", "L2", "R0", "R1", "R2"];
var AXIS_NAMES = { L0: "Stroke", L1: "Surge", L2: "Sway", R0: "Twist", R1: "Roll", R2: "Pitch" };
// Tabs in display order; later sections of the script push their own.
var SETTINGS_TABS = [
{ id: 'device', label: 'Device', build: buildDeviceTab },
{ id: 'axes', label: 'Axes', build: buildAxesTab },
{ id: 'advanced', label: 'Advanced', build: buildAdvancedTab }
];
var activeTab = 'device';
function pct(v){ return Math.round(v / 99.99) + '%'; } // device units (0-9999) as a percentage
function ms(v){ return Math.round(v) + ' ms'; }
function settingsOpen(){ return !!document.getElementById('tcode-modal'); }
function toggleMenu(){
if(settingsOpen()){ closeSettings(); } else { openSettings(); }
}
function openSettings(){
if(settingsOpen()){ return; }
injectUiStyles();
var nav = el('nav', {class: 'nav nav-tabs', role: 'tablist'});
var body = el('div', {id: 'tcode-modal-body'});
var modal = el('div', {class: 'modal fade show', id: 'tcode-modal', role: 'dialog', 'aria-modal': 'true',
'aria-labelledby': 'tcode-modal-title', tabindex: '-1', style: 'display: block;'}, [
el('div', {class: 'modal-dialog modal-lg modal-dialog-scrollable'}, [
el('div', {class: 'modal-content'}, [
el('div', {class: 'modal-header'}, [
el('div', {class: 'modal-title h4', id: 'tcode-modal-title'}, ['TCode']),
el('button', {type: 'button', class: 'close', 'aria-label': 'Close', onclick: closeSettings}, [el('span', {'aria-hidden': 'true', text: '×'})])
]),
el('div', {class: 'modal-body'}, [nav, body]),
el('div', {class: 'modal-footer'}, [
el('span', {class: 'tcode-version', text: 'Stash-TCode ' + TCODE_VERSION}),
uiButton('Close', 'secondary', closeSettings)
])
])
])
]);
// Clicking the dimmed area outside the dialog closes it.
modal.addEventListener('mousedown', function(e){ if(e.target === modal){ closeSettings(); } });
document.body.appendChild(el('div', {class: 'modal-backdrop fade show', id: 'tcode-modal-backdrop'}));
document.body.appendChild(modal);
document.body.classList.add('modal-open');
document.addEventListener('keydown', onSettingsKey, true);
for(var tab of SETTINGS_TABS){
nav.appendChild(el('a', {class: 'nav-item nav-link', role: 'tab', 'data-tab': tab.id, text: tab.label,
onclick: (function(id){ return function(){ showTab(id); }; })(tab.id)}));
}
showTab(activeTab);
modal.focus();
}
// Removes the dialog unconditionally: a stray full-screen layer would swallow every
// click on the page.
function closeSettings(){
try { saveSettings(); } catch(e){ debug("[TCode] saveSettings error on close: " + e); }
for(var id of ['tcode-modal', 'tcode-modal-backdrop']){
var node = document.getElementById(id);
if(node){ node.remove(); }
}
document.body.classList.remove('modal-open');
document.removeEventListener('keydown', onSettingsKey, true);
}
function onSettingsKey(e){
if(e.key === 'Escape'){ e.stopPropagation(); closeSettings(); }
}
function showTab(id){
if(!SETTINGS_TABS.some(function(t){ return t.id === id; })){ id = SETTINGS_TABS[0].id; }
activeTab = id;
document.querySelectorAll('#tcode-modal .nav-tabs .nav-link').forEach(function(a){
var on = a.getAttribute('data-tab') === id;
a.classList.toggle('active', on);
a.setAttribute('aria-selected', on ? 'true' : 'false');
});
renderActiveTab();
}
// Rebuild the visible tab from current state (after a connection change, etc.).
function renderActiveTab(){
var body = document.getElementById('tcode-modal-body');
if(!body){ return; }
var tab = SETTINGS_TABS.find(function(t){ return t.id === activeTab; });
body.textContent = '';
tab.build(body);
}
// Re-render only if the given tab is the one showing, so live updates don't reset a
// tab the user is working in.
function refreshSettingsTab(id){
if(settingsOpen() && activeTab === id){ renderActiveTab(); }
}
// ---- Device tab ----
function buildDeviceTab(body){
var card = uiSection(body, "Device");
var status;
if(!serialConnected){ status = "Not connected"; }
else if(simulatedDevice){ status = "Simulated device (debug)"; }
else { status = "Connected over USB" + portLabel(); }
var statusEl = el('span', {class: 'tcode-status'}, [el('span', {class: 'tcode-dot' + (serialConnected ? ' on' : '')}), status]);
var row = uiSetting(card, "TCode device", null,
serialConnected ? uiButton("Disconnect", "secondary", disconnectSerial)
: uiButton("Connect", "primary", connectSerial));
row.firstChild.appendChild(el('div', {class: 'sub-heading'}, [statusEl]));
uiSetting(card, "Reconnect automatically", "Reopen the device on page load, and when it's plugged back in.",
uiSwitch('autoConnect', settings.autoConnect !== false, function(v){ settings.autoConnect = v; saveSettings(); }));
var hrCard = uiSection(body, "Heart rate monitor");
var hrButton;
if(hr.status === 'live' || hr.status === 'connecting' || hr.status === 'reconnecting'){
hrButton = uiButton("Disconnect", "secondary", disconnectHr);
}else if(settings.hr.deviceId && !hrCanAutoReconnect()){
hrButton = uiButton("Reconnect", "primary", connectHr);
}else{
hrButton = uiButton("Connect", "primary", connectHr);
}
var hrRow = uiSetting(hrCard, "Monitor", null, hrButton);
hrRow.firstChild.appendChild(el('div', {class: 'sub-heading'}, [
el('span', {class: 'tcode-status'}, [el('span', {class: 'tcode-dot' + (hrLive() ? ' on' : ''), id: 'tcode-hr-dot'}),
el('span', {id: 'tcode-hr-status', text: hrStatusText()})])
]));
hrRow.firstChild.appendChild(el('div', {class: 'sub-heading',
text: "Any Bluetooth monitor with the standard heart-rate service: chest straps, or watches broadcasting HR."}));
var play = uiSection(body, "Playback");
uiSetting(play, "Sync offset", "Shifts the script against the video. Positive plays strokes earlier.",
uiRange('sync', parseInt(settings.sync) || 0, {min: -250, max: 250, origin: 0, format: ms}, null,
function(v){ settings.sync = v; saveSettings(); }).el);
var home = uiSection(body, "Homing");
uiSetting(home, "Home on connect and scene change", "Off leaves the device wherever it stopped.",
uiSwitch('homeEnabled', settings.homeEnabled !== false, function(v){ settings.homeEnabled = v; saveSettings(); }));
uiSetting(home, "Home travel time", "How long the move to the home position takes. Longer is gentler.",
uiRange('centerTime', parseInt(settings.centerTime) || 1000, {min: 100, max: 5000, step: 50, format: ms}, null,
function(v){ settings.centerTime = v; saveSettings(); }).el);
uiSetting(home, "Home now", "Move every enabled axis to its home position.",
uiButton("Home now", "secondary", function(){ centerAll(); }, {disabled: !serialConnected}));
}
function portLabel(){
var p = settings.serialPort;
if(!p || p.usbVendorId == null){ return ""; }
var hex = function(n){ return Number(n).toString(16).toUpperCase().padStart(4, '0'); };
return " (" + hex(p.usbVendorId) + ":" + hex(p.usbProductId) + ")";
}
// ---- Axes tab ----
function buildAxesTab(body){
var card = uiSection(body, "Axes", "Range limits how far each axis travels. Home is where it rests when idle.");
AXIS_LIST.forEach(function(axis){ buildAxisGroup(card, axis); });
}
function buildAxisGroup(card, axis){
var cfg = settings.axes[axis];
var group = el('div', {class: 'setting-group' + (cfg.enabled ? '' : ' collapsed')});
card.appendChild(group);
uiSetting(group, axis + " · " + AXIS_NAMES[axis], null, uiSwitch('enable' + axis, cfg.enabled, function(v){
cfg.enabled = v;
group.classList.toggle('collapsed', !v);
saveSettings();
}));
var lim = getLimit(axis, BOTH);
var homeRange;
function applyRange(lo, hi, send){
cfg.limits = [lo, hi];
if(AXIS[axis]){ setLimits(lo, hi, axis, send); }
if(send){ saveSettings(); }
syncHome();
}
uiSetting(group, "Range", null,
uiDualRange('range' + axis, parseInt(lim[0]), parseInt(lim[1]), {min: 0, max: 9999, format: pct},
function(lo, hi){ applyRange(lo, hi, false); },
function(lo, hi){ applyRange(lo, hi, true); }).el, {sub: true});
uiSetting(group, "Invert", "Flip the direction of this axis.",
uiSwitch('invert' + axis, cfg.invert, function(v){ cfg.invert = v; saveSettings(); }), {sub: true});
var autoRow, freqRow, overrideRow;
var linkSelect = el('select', {id: 'tcode-link' + axis, class: 'input-control form-control form-control-sm', style: 'width: 160px'},
[el('option', {value: '', text: 'Off'})].concat(AXIS_LIST.filter(function(o){ return o !== axis; }).map(function(o){
return el('option', {value: o, text: o + ' · ' + AXIS_NAMES[o]});
})));
linkSelect.value = cfg.link || '';
linkSelect.addEventListener('change', function(){
cfg.link = linkSelect.value;
overrideRow.classList.toggle('disabled', !cfg.link);
autoRow.classList.toggle('disabled', !!cfg.link);
freqRow.classList.toggle('disabled', !!cfg.link || !cfg.auto);
saveSettings();
});
uiSetting(group, "Follow", "Copy another axis's motion: this axis moves to the same point in its own range. Applies when the scene has no script for this axis.",
linkSelect, {sub: true});
overrideRow = uiSetting(group, "Override script", "Follow even when the scene has a script for this axis, ignoring that script.",
uiSwitch('linkOverride' + axis, cfg.linkOverride, function(v){ cfg.linkOverride = v; saveSettings(); }),
{sub: true, disabled: !cfg.link});
autoRow = uiSetting(group, "Auto motion", "When the scene has no script for this axis, move in a smooth sine wave instead.",
uiSwitch('auto' + axis, cfg.auto, function(v){ cfg.auto = v; freqRow.classList.toggle('disabled', !v || !!cfg.link); saveSettings(); }),
{sub: true, disabled: !!cfg.link});
var hzFormat = function(v){ return v.toFixed(2) + " Hz · " + Math.round(v * 60) + "/min"; };
freqRow = uiSetting(group, "Frequency", "Full cycles per second.",
uiRange('autoHz' + axis, cfg.autoHz, {min: AUTO_HZ_MIN, max: AUTO_HZ_MAX, step: 0.05, format: hzFormat}, null,
function(v){ cfg.autoHz = v; saveSettings(); }).el, {sub: true, disabled: !cfg.auto || !!cfg.link});
var speedRow;
uiSetting(group, "Speed limit", "Cap how fast this axis moves. Faster moves are shortened so they stay in sync with the video.",
uiSwitch('speedLimit' + axis, cfg.speedLimit, function(v){ cfg.speedLimit = v; speedRow.classList.toggle('disabled', !v); saveSettings(); }), {sub: true});
// Stored as full travels per second (cfg.maxSpeed); shown as % of full travel per second.
speedRow = uiSetting(group, "Max speed", "How much of its full travel this axis may cover per second.",
uiRange('maxSpeed' + axis, Math.round(cfg.maxSpeed * 100), {min: MAX_SPEED_MIN * 100, max: MAX_SPEED_MAX * 100, step: 25,
format: function(v){ return v + "%/s"; }}, null,
function(v){ cfg.maxSpeed = v / 100; saveSettings(); }).el, {sub: true, disabled: !cfg.speedLimit});
uiSetting(group, "Auto home", "Rest at the middle of the range. Turn off to choose the home position.",
uiSwitch('autoCenter' + axis, cfg.autoCenter !== false, function(v){
cfg.autoCenter = v;
if(!v){ cfg.center = getCenter(axis); }
saveSettings();
syncHome();
if(serialConnected){ centerAxis(axis); }
}), {sub: true});
homeRange = uiRange('center' + axis, getCenter(axis), {min: 0, max: 9999, format: pct}, null, function(v){
cfg.center = v;
saveSettings();
if(serialConnected){ centerAxis(axis); } // preview on release, not on every input event
});
var homeRow = uiSetting(group, "Home position", null, homeRange.el, {sub: true});
function syncHome(){
var auto = cfg.autoCenter !== false;
homeRange.setDisabled(auto);
homeRow.classList.toggle('disabled', auto);
if(auto){ homeRange.set(getCenter(axis)); }
}
syncHome();
}
// ---- Advanced tab ----
function buildAdvancedTab(body){
var card = uiSection(body, "Advanced");
uiSetting(card, "Stats overlay", "Heart rate, ceiling, edges and the current phase over the video, while a monitor is connected or modulation is on.",
uiSwitch('showHud', settings.showHud !== false, function(v){ settings.showHud = v; saveSettings(); updateHud(); }));
uiSetting(card, "Notifications", "Show pop-ups for connections and script loading.",
uiSwitch('showNotifications', settings.showNotifications !== false, function(v){ settings.showNotifications = v; saveSettings(); }));
uiSetting(card, "Debug mode", "Log details to the console and show the debug tools below.",
uiSwitch('debug', settings.debug, function(v){ settings.debug = v; saveSettings(); renderActiveTab(); }));
if(settings.debug){
var dbg = uiSection(body, "Debug tools", "window.__tcode is available in the page console.");
uiSetting(dbg, "Simulated device", "Stands in for a TCode device: commands are recorded, nothing is sent.",
uiButton(simulatedDevice ? "Running" : "Start", "secondary", function(){ connectSimulatedDevice(); renderActiveTab(); },
{disabled: serialConnected}));
var simOn = hr.source === 'sim';
uiSetting(dbg, "Simulate heart rate", "Feeds a steady reading once a second in place of a monitor.",
uiSwitch('hrSim', simOn, function(v){ if(v){ startHrSim(); } else { stopHrSim(); } renderActiveTab(); }));
var simRange = uiRange('hrSimBpm', hrSimBpm, {min: 40, max: 200, format: function(v){ return v + " BPM"; }},
function(v){ hrSimBpm = v; if(hr.source === 'sim'){ feedHr(v, true); } }, null);
simRange.setDisabled(!simOn);
uiSetting(dbg, "Simulated BPM", null, simRange.el, {sub: true, disabled: !simOn});
}
}
// ---- Heart Rate tab ----
SETTINGS_TABS.splice(2, 0, { id: 'hr', label: 'Heart Rate', build: buildHrTab });
function buildHrTab(body){
var cfg = settings.hr;
var bpm = function(v){ return v + " BPM"; };
var sec = function(v){ return v + " s"; };
var changed = function(){ saveSettings(); refreshGovernor(); };
var main = uiSection(body, "Heart-rate modulation",
"Shortens strokes as your heart rate nears your edge, and holds the stroker back there until you recover.");
uiSetting(main, "Enable", hr.status === 'off' ? "Connect a monitor on the Device tab. Without one, scripts play normally." : null,
uiSwitch('hrEnabled', cfg.enabled, function(v){ cfg.enabled = v; changed(); }));
var live = uiSetting(main, "Session", null,
uiButton("Reset", "secondary", function(){ resetHrSession(); }, {small: true}));
live.firstChild.appendChild(el('div', {class: 'sub-heading', id: 'tcode-gov-status', text: govStatusText(lastGov)}));
var rates = uiSection(body, "Heart rate");
uiSetting(rates, "Edge", "The heart rate that counts as an edge. This is the ceiling: strokes stop here until you recover.",
uiNumber('edgeHr', cfg.edgeHr, {min: 50, max: 250, suffix: "BPM"}, function(v){ cfg.edgeHr = v; changed(); }));
var resp = uiSection(body, "Response");
uiSetting(resp, "Approach band", "Strokes start shortening this many BPM below the ceiling. 0 only reacts at the ceiling.",
uiRange('hrBand', cfg.band, {min: 0, max: 40, format: bpm}, null, function(v){ cfg.band = v; changed(); }).el);
uiSetting(resp, "Shortest stroke", "Stroke length just below the ceiling, as a share of the full range.",
uiRange('hrFloor', cfg.floor, {min: 0, max: 100, format: function(v){ return v + "%"; }}, null, function(v){ cfg.floor = v; changed(); }).el);
uiSetting(resp, "Rejoin time", "After an edge, strokes ramp back to full over this long.",
uiRange('hrRejoin', cfg.rejoinSec, {min: 0, max: 60, format: sec}, null, function(v){ cfg.rejoinSec = v; changed(); }).el);
uiSetting(resp, "Signal timeout", "If the monitor sends no real reading for this long (disconnected, or taken off), the device stops.",
uiRange('hrTimeout', cfg.timeoutSec, {min: 3, max: 20, format: sec}, null, function(v){ cfg.timeoutSec = v; changed(); }).el);
var decay = uiSection(body, "Adaptive ceiling decay", "Lowers the ceiling as edges add up, to counter fatigue over a long session.");
var decayRows = [];
uiSetting(decay, "Enable", null, uiSwitch('hrDecay', cfg.decay, function(v){
cfg.decay = v;
decayRows.forEach(function(r){ r.classList.toggle('disabled', !v); });
changed();
}));
decayRows.push(uiSetting(decay, "Every", "Number of edges per step.",
uiNumber('decayEvery', cfg.decayEvery, {min: 1, max: 10, suffix: "edges"}, function(v){ cfg.decayEvery = v; changed(); }), {sub: true}));
decayRows.push(uiSetting(decay, "Drop by", "How much the ceiling falls each step.",
uiNumber('decayBpm', cfg.decayBpm, {min: 1, max: 5, suffix: "BPM"}, function(v){ cfg.decayBpm = v; changed(); }), {sub: true}));
decayRows.push(uiSetting(decay, "Floor", "The ceiling never decays below this.",
uiNumber('decayFloor', cfg.decayFloor, {min: 80, max: 130, suffix: "BPM"}, function(v){ cfg.decayFloor = v; changed(); }), {sub: true}));
decayRows.forEach(function(r){ r.classList.toggle('disabled', !cfg.decay); });
}
// ---- Climax tab ----
SETTINGS_TABS.splice(3, 0, { id: 'climax', label: 'Climax', build: buildClimaxTab });
function buildClimaxTab(body){
var cfg = settings.hr;
var sec = function(v){ return v + " s"; };
var changed = function(){ saveSettings(); refreshGovernor(); };
var main = uiSection(body, "Climax markers",
"Scene markers with this tag release the limiter: strokes build to full before the marker and stay full, whatever your heart rate. Works with heart-rate modulation on.");
var tagInput = el('input', {type: 'text', id: 'tcode-climaxTag', class: 'input-control form-control form-control-sm', value: cfg.climaxTag,
style: 'width: 160px', spellcheck: 'false'});
tagInput.addEventListener('change', function(){
cfg.climaxTag = tagInput.value.trim() || "Climax";
tagInput.value = cfg.climaxTag;
saveSettings();
fetchClimaxMarkers();
});
uiSetting(main, "Marker tag", "Primary or secondary tag. Add markers in Stash's Markers tab, or with the button below.", tagInput);
var onScene = isFinite(getSceneId());
var hint, list = null;
if(!onScene){ hint = "Open a scene to see its climax markers."; }
else if(!climaxMarkers.length){ hint = "No climax markers in this scene yet."; }
else {
hint = climaxMarkers.length + (climaxMarkers.length === 1 ? " marker. Click a time to jump to it." : " markers. Click a time to jump to it.");
list = el('ul', {class: 'tcode-list'}, climaxMarkers.map(function(m){
return el('li', null, [
el('a', {href: '#', text: formatTime(m.seconds) + (m.end != null ? " – " + formatTime(m.end) : ""), onclick: function(e){
e.preventDefault();
seekScene(m.seconds);
}})
]);
}));
}
var row = uiSetting(main, "This scene", hint,
uiButton("Mark climax here", "primary", markClimaxHere, {disabled: !onScene || !boundPlayer}));
if(list){ row.firstChild.appendChild(list); }
var timing = uiSection(body, "Timing");
uiSetting(timing, "Build-up", "How long before the marker strokes start climbing back to full.",
uiRange('climaxRamp', cfg.climaxRampSec, {min: 0, max: 180, format: sec}, null, function(v){ cfg.climaxRampSec = v; changed(); }).el);
uiSetting(timing, "Hold", "How long strokes stay full after the marker. Markers with an end time hold for their whole range instead.",
uiRange('climaxHold', cfg.climaxHoldSec, {min: 5, max: 180, format: sec}, null, function(v){ cfg.climaxHoldSec = v; changed(); }).el);
uiSetting(timing, "Ease back", "How long it takes to hand control back to your heart rate afterwards.",
uiRange('climaxEase', cfg.climaxEaseSec, {min: 0, max: 180, format: sec}, null, function(v){ cfg.climaxEaseSec = v; changed(); }).el);
}
// --- WEB SERIAL IMPLEMENTATION ---
// Ask the user to pick a port (needs a click), then open it.
async function connectSerial() {
if (!navigator.serial) {
alert("Web Serial API is NOT available.\n\nUse a Chromium-based browser, and either serve Stash over HTTPS or add " + location.origin + " to 'Insecure origins treated as secure' in chrome://flags.");
return;
}
var picked;
try {
picked = await navigator.serial.requestPort();
} catch (e) {
if (e.name !== "NotFoundError") { showToast("Connection Failed", e.message, "error"); } // NotFoundError = picker cancelled
return;
}
await openPort(picked, false);
}
// Open a port and wire up the writer and read loop. `silent` is for automatic reconnects:
// failures are only logged, since the user didn't ask for anything.
async function openPort(p, silent) {
if (serialConnected) { return true; }
try {
await p.open({ baudRate: 115200 }); // Standard TCode Baud Rate
} catch (e) {
console.error("[TCode] Serial open failed:", e);
if (!silent) { showToast("Connection Failed", e.message, "error"); }
return false;
}
port = p;
const textEncoder = new TextEncoderStream();
writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
writer = textEncoder.writable.getWriter();
serialConnected = true;
simulatedDevice = false;
keepReading = true;
forgetAxisPositions();
// Remember which device this was so it can be reopened without the picker next time.
try {
var info = port.getInfo();
settings.serialPort = { usbVendorId: info.usbVendorId ?? null, usbProductId: info.usbProductId ?? null };
storeSet("settings", settings);
} catch (e) { debug("[TCode] getInfo failed: " + e); }
debug("USB Serial Connected");
showToast(silent ? "USB Reconnected" : "USB Connected", "Serial connection established at 115200 baud", "success");
updateNavButton(); // reflect connected state on the navbar
readSerialLoop();
return true;
}
// The previously used port among those this site already has permission for: an exact
// USB vendor/product match, or the only granted port if no USB device was saved yet.
// A saved device that isn't present never falls back to some other granted port, which
// could be anything (an Arduino, a different toy) and would be sent TCode.
function pickSavedPort(ports) {
var saved = settings.serialPort;