-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
763 lines (673 loc) · 25.1 KB
/
Copy pathcontentScript.js
File metadata and controls
763 lines (673 loc) · 25.1 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
// Injects the ticker strip into every page and keeps it updated from storage.
let STORAGE_KEYS;
let formatQuotePrice;
let formatSigned;
let formatSignedCurrency;
let isHostTapeExcluded;
const TICKER_CONTAINER_ID = "pts-ticker-container";
const ORIGINAL_MARGIN_ATTR = "data-pts-original-margin-top";
const TAPE_RESERVATION_PROPERTY = "--myticker-tape-reservation";
// Keep primary selector simple so hosts and tests can resolve it reliably.
const CHATGPT_DIALOG_SELECTOR = "dialog[open]";
/** Closed shadow root kept in-module so host pages cannot scrape holdings DOM. */
let tickerHost = null;
let tickerShadow = null;
let tickerBar = null;
let latestState;
let latestStateResolved = false;
let tickerSettings = null;
let reducedMotionMq = { matches: false, addEventListener() {} };
let tapeReservation = null;
let tapeResizeObserver = null;
let tapeDocumentObserver = null;
let chatgptDialog = null;
let tapeReconcileFrame = null;
let cancelTickerExit = null;
let extensionContextAlive = true;
function isContextInvalidated(error) {
return /extension context invalidated/i.test(String(error?.message || error || ""));
}
function teardownForInvalidatedContext() {
if (!extensionContextAlive) return;
extensionContextAlive = false;
cancelTapeReconciliation();
cancelTickerExit?.();
tapeResizeObserver?.disconnect();
tapeDocumentObserver?.disconnect();
tapeResizeObserver = null;
tapeDocumentObserver = null;
reducedMotionMq?.removeEventListener?.("change", onReducedMotionChange);
clearTapeReservation();
tickerHost?.remove?.();
tickerHost = null;
tickerShadow = null;
tickerBar = null;
}
function reportLifecycle(stage, error) {
if (!extensionContextAlive) return;
try {
const pending = chrome.runtime.sendMessage({
type: "content-script-lifecycle",
payload: {
stage,
origin: globalThis.location?.origin || "",
error: error ? { name: String(error.name || "Error"), message: String(error.message || "") } : undefined
}
});
if (pending?.catch) pending.catch((sendError) => {
if (isContextInvalidated(sendError)) teardownForInvalidatedContext();
});
} catch (sendError) {
if (isContextInvalidated(sendError)) teardownForInvalidatedContext();
// Diagnostics must never make the page integration fail.
}
}
function reportFatal(error) {
reportLifecycle("fatal-error", error);
console.warn("[MyTicker] content script initialization failed", error);
}
function runSafely(work) {
if (!extensionContextAlive) return;
try {
work();
} catch (error) {
if (isContextInvalidated(error)) {
teardownForInvalidatedContext();
return;
}
reportFatal(error);
}
}
function prefersReducedMotion() {
return reducedMotionMq.matches;
}
/** Global off or this host is on the Appearance exclusion list. */
function shouldShowTape(settings = tickerSettings) {
if (!settings || settings.enabled === false) return false;
try {
const host = globalThis.location?.hostname || "";
if (typeof isHostTapeExcluded === "function" && isHostTapeExcluded(host, settings.excludedSites)) {
return false;
}
} catch {
// location can throw in edge contexts; fail open only when globally enabled
}
return true;
}
function onReducedMotionChange() {
runSafely(() => {
if (tickerBar) {
tickerBar.classList.toggle("pts-reduced-motion", prefersReducedMotion());
chrome.storage.local.get([STORAGE_KEYS.positionsState], (data) => {
runSafely(() => {
const state = data[STORAGE_KEYS.positionsState];
latestState = state;
latestStateResolved = true;
renderTicker(state);
});
});
}
});
}
function bootstrap() {
try {
const bridge = globalThis.__MYTICKER_CONTENT_SHARED__;
if (!bridge) throw new Error("Content shared bridge was not loaded");
({ STORAGE_KEYS, formatQuotePrice, formatSigned, formatSignedCurrency, isHostTapeExcluded } = bridge);
if (typeof isHostTapeExcluded !== "function") {
isHostTapeExcluded = () => false;
}
reportLifecycle("loaded");
if (!extensionContextAlive) return;
reducedMotionMq = window.matchMedia("(prefers-reduced-motion: reduce)");
reducedMotionMq.addEventListener("change", onReducedMotionChange);
init();
} catch (error) {
reportFatal(error);
}
}
bootstrap();
function init() {
if (!extensionContextAlive) return;
chrome.storage.sync.get([STORAGE_KEYS.settings], (data) => {
if (!extensionContextAlive) return;
try {
const settings = data[STORAGE_KEYS.settings];
tickerSettings = settings;
reportLifecycle("storage-settings-read");
if (shouldShowTape(settings)) {
ensureTickerContainer(false);
applyTickerSpeed(settings);
applyTapeSize(settings);
applyTickerTheme(settings);
}
} catch (error) {
reportFatal(error);
}
});
chrome.storage.onChanged.addListener((changes, areaName) => {
runSafely(() => {
if (areaName === "sync" && changes[STORAGE_KEYS.settings]) {
const newSettings = changes[STORAGE_KEYS.settings].newValue;
tickerSettings = newSettings;
if (shouldShowTape(newSettings)) {
ensureTickerContainer(true);
applyTickerSpeed(newSettings);
applyTapeSize(newSettings);
applyTickerTheme(newSettings);
} else {
removeTickerContainer();
}
}
if (areaName === "local" && changes[STORAGE_KEYS.positionsState]) {
const state = changes[STORAGE_KEYS.positionsState].newValue;
latestState = state;
latestStateResolved = true;
renderTicker(state);
}
});
});
chrome.storage.local.get([STORAGE_KEYS.positionsState], (data) => {
if (!extensionContextAlive) return;
runSafely(() => {
const state = data[STORAGE_KEYS.positionsState];
latestState = state;
latestStateResolved = true;
renderTicker(state);
});
});
}
function snapshotInlineValue(style, property) {
return {
value: style.getPropertyValue ? style.getPropertyValue(property) : style[property] || "",
priority: style.getPropertyPriority?.(property) || ""
};
}
function restoreInlineValue(style, property, snapshot) {
const { value, priority } = snapshot;
if (style.setProperty) {
if (value) style.setProperty(property, value, priority);
else style.removeProperty?.(property);
return;
}
style[property] = value;
}
function isChatGptPage() {
const hostname = globalThis.location?.hostname;
return hostname === "chatgpt.com" || hostname === "chat.openai.com";
}
function getOriginalBodyMarginPx(body) {
const inlineMargin = Number.parseFloat(snapshotInlineValue(body.style, "margin-top").value);
if (Number.isFinite(inlineMargin)) return inlineMargin;
const computedMargin = Number.parseFloat(globalThis.getComputedStyle?.(body).marginTop);
return Number.isFinite(computedMargin) ? computedMargin : 0;
}
function isFullScreenDialog(dialog) {
if (!dialog?.hasAttribute("open")) return false;
const position = dialog.style.getPropertyValue("position") || globalThis.getComputedStyle?.(dialog).position;
if (position !== "fixed") return false;
const rect = dialog.getBoundingClientRect?.();
const viewportWidth = globalThis.innerWidth || document.documentElement?.clientWidth || 0;
const viewportHeight = globalThis.innerHeight || document.documentElement?.clientHeight || 0;
const tolerance = 2;
return Boolean(
rect && viewportWidth && viewportHeight &&
rect.top <= tolerance && rect.left <= tolerance &&
rect.width >= viewportWidth - tolerance && rect.height >= viewportHeight - tolerance
);
}
function applyChatGptReservation(height) {
if (!isChatGptPage()) {
clearChatGptReservation();
return;
}
const dialog = document.querySelector?.(CHATGPT_DIALOG_SELECTOR) || null;
const trackedDialog = chatgptDialog?.element === dialog && dialog?.hasAttribute("open");
if (!trackedDialog && chatgptDialog) clearChatGptReservation();
if (!trackedDialog && !isFullScreenDialog(dialog)) return;
if (!chatgptDialog) {
chatgptDialog = {
element: dialog,
top: snapshotInlineValue(dialog.style, "top"),
inset: snapshotInlineValue(dialog.style, "inset"),
height: snapshotInlineValue(dialog.style, "height")
};
}
dialog.classList.add("myticker-chatgpt-tape-reserved");
dialog.style.setProperty("top", `${height}px`, "important");
dialog.style.setProperty("inset", `${height}px 0 0`, "important");
dialog.style.setProperty("height", `calc(100% - ${height}px)`, "important");
}
function clearChatGptReservation() {
if (!chatgptDialog) return;
chatgptDialog.element.classList.remove("myticker-chatgpt-tape-reserved");
restoreInlineValue(chatgptDialog.element.style, "top", chatgptDialog.top);
restoreInlineValue(chatgptDialog.element.style, "inset", chatgptDialog.inset);
restoreInlineValue(chatgptDialog.element.style, "height", chatgptDialog.height);
chatgptDialog = null;
}
function applyTapeReservation() {
if (!tickerBar || !document.body) return;
if (tapeReservation?.body && tapeReservation.body !== document.body) clearTapeReservation();
if (!tapeReservation) {
tapeReservation = {
body: document.body,
bodyMarginTop: snapshotInlineValue(document.body.style, "margin-top"),
rootScrollPaddingTop: snapshotInlineValue(document.documentElement.style, "scroll-padding-top"),
rootReservation: snapshotInlineValue(document.documentElement.style, TAPE_RESERVATION_PROPERTY),
originalPx: getOriginalBodyMarginPx(document.body)
};
document.body.setAttribute(ORIGINAL_MARGIN_ATTR, String(tapeReservation.originalPx));
}
const height = Math.max(0, Number(tickerBar.getBoundingClientRect?.().height) || 0);
document.body.style.setProperty("margin-top", `${tapeReservation.originalPx + height}px`, "important");
document.documentElement.style.setProperty("scroll-padding-top", `${height}px`, "important");
document.documentElement.style.setProperty(TAPE_RESERVATION_PROPERTY, `${height}px`, "important");
applyChatGptReservation(height);
}
function observeTapeReservation() {
tapeResizeObserver?.disconnect();
tapeResizeObserver = null;
if (typeof ResizeObserver !== "function" || !tickerBar) return;
tapeResizeObserver = new ResizeObserver(() => runSafely(applyTapeReservation));
tapeResizeObserver.observe(tickerBar);
}
function observeTapeDocument() {
tapeDocumentObserver?.disconnect();
tapeDocumentObserver = null;
if (typeof MutationObserver !== "function" || !document.documentElement) return;
tapeDocumentObserver = new MutationObserver((records) => runSafely(() => {
const hasRelevantChange = records.some((record) =>
record.type === "childList" || (record.type === "attributes" && record.attributeName === "open")
);
if (!hasRelevantChange) return;
if (!tickerBar) return;
queueTapeReconciliation();
}));
tapeDocumentObserver.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["open"]
});
}
function queueTapeReconciliation() {
if (!extensionContextAlive || tapeReconcileFrame !== null) return;
tapeReconcileFrame = requestAnimationFrame(() => {
tapeReconcileFrame = null;
runSafely(() => {
if (!tickerBar) return;
if (tapeReservation?.body !== document.body) {
clearTapeReservation();
applyTapeReservation();
observeTapeReservation();
observeTapeDocument();
return;
}
applyTapeReservation();
});
});
}
function cancelTapeReconciliation() {
if (tapeReconcileFrame === null) return;
cancelAnimationFrame?.(tapeReconcileFrame);
tapeReconcileFrame = null;
}
function clearTapeReservation() {
cancelTapeReconciliation();
tapeResizeObserver?.disconnect();
tapeResizeObserver = null;
tapeDocumentObserver?.disconnect();
tapeDocumentObserver = null;
clearChatGptReservation();
if (!tapeReservation) return;
const { body, bodyMarginTop, rootScrollPaddingTop, rootReservation } = tapeReservation;
if (body) {
restoreInlineValue(body.style, "margin-top", bodyMarginTop);
body.removeAttribute(ORIGINAL_MARGIN_ATTR);
}
restoreInlineValue(document.documentElement.style, "scroll-padding-top", rootScrollPaddingTop);
restoreInlineValue(document.documentElement.style, TAPE_RESERVATION_PROPERTY, rootReservation);
tapeReservation = null;
}
function ensureTickerContainer(animate = false) {
const hostMounted = document.documentElement.contains?.(tickerHost) ?? tickerHost?.parentNode === document.documentElement;
if (tickerHost && hostMounted && tickerBar) {
cancelTickerExit?.();
if (tapeReservation?.body !== document.body) {
applyTapeReservation();
observeTapeReservation();
}
return;
}
if (!document.body) {
document.addEventListener(
"DOMContentLoaded",
() => {
runSafely(() => ensureTickerContainer(animate));
},
{ once: true }
);
return;
}
// Host is a zero-size mount; UI lives in closed shadow (pages cannot scrape P&L DOM).
tickerHost = document.createElement("div");
tickerHost.id = TICKER_CONTAINER_ID;
tickerHost.setAttribute("data-myticker", "1");
tickerHost.style.cssText = "all:initial;position:fixed;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483000;pointer-events:none;";
tickerShadow = tickerHost.attachShadow({ mode: "closed" });
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = chrome.runtime.getURL("ticker.css");
tickerShadow.appendChild(link);
tickerBar = document.createElement("div");
tickerBar.className = "pts-ticker-bar";
tickerBar.style.pointerEvents = "auto";
if (prefersReducedMotion() || !animate) {
tickerBar.classList.add("pts-reduced-motion", "pts-ticker-visible");
}
tickerShadow.appendChild(tickerBar);
// The body can be replaced by SPA navigation between the guard above and an
// insertBefore call. Appending to the stable document root prevents that
// race from aborting the content script on sites such as LinkedIn.
document.documentElement.appendChild(tickerHost);
reportLifecycle("mount-success");
applyTapeSize(tickerSettings);
applyTickerTheme(tickerSettings);
applyTapeReservation();
observeTapeReservation();
observeTapeDocument();
if (!prefersReducedMotion() && animate) {
requestAnimationFrame(() => {
tickerBar.classList.add("pts-ticker-visible");
});
}
// Storage can resolve before a late page body lets us mount. Re-render the
// cached state once this bar exists rather than dropping that first paint.
renderTicker(latestState);
}
function restoreBodyMargin() {
clearTapeReservation();
}
function removeTickerContainer() {
if (!tickerHost || !tickerBar) {
restoreBodyMargin();
tickerHost = null;
tickerShadow = null;
tickerBar = null;
return;
}
const host = tickerHost;
const bar = tickerBar;
let finished = false;
let cancelled = false;
let exitTimer = null;
const finish = () => {
if (finished || cancelled) return;
finished = true;
if (host.parentNode) host.parentNode.removeChild(host);
delete bar._ptsParts;
tickerHost = null;
tickerShadow = null;
tickerBar = null;
cancelTickerExit = null;
};
if (prefersReducedMotion()) {
restoreBodyMargin();
finish();
return;
}
bar.classList.remove("pts-ticker-visible");
bar.classList.add("pts-ticker-exiting");
// Page reservation changes are deliberately immediate: the tape can be
// toggled by keyboard and must never animate host-page layout or force sync
// reflow. Only the tape itself uses transform/opacity on exit.
restoreBodyMargin();
const onEnd = (e) => {
if (e.propertyName !== "opacity") return;
finish();
};
bar.addEventListener("transitionend", onEnd, { once: true });
exitTimer = setTimeout(finish, 200);
cancelTickerExit = () => {
if (finished || cancelled) return;
cancelled = true;
clearTimeout(exitTimer);
bar.classList.remove("pts-ticker-exiting");
bar.classList.add("pts-ticker-visible");
cancelTickerExit = null;
};
}
function getTickerParts(container) {
if (!container._ptsParts) {
const aggregate = document.createElement("div");
aggregate.className = "pts-aggregate";
aggregate.setAttribute("role", "status");
aggregate.setAttribute("aria-label", "Portfolio day profit and loss");
const scrollWrapper = document.createElement("div");
scrollWrapper.className = "pts-scroll-wrapper";
scrollWrapper.setAttribute("tabindex", "0");
scrollWrapper.setAttribute("role", "group");
scrollWrapper.setAttribute("aria-label", "Market tape. Focus pauses scrolling.");
const scrollInner = document.createElement("div");
scrollInner.className = "pts-scroll-inner";
scrollWrapper.appendChild(scrollInner);
container.appendChild(aggregate);
container.appendChild(scrollWrapper);
container._ptsParts = {
stale: null,
aggregate,
scrollWrapper,
scrollInner
};
}
return container._ptsParts;
}
function positionKey(pos) {
const sym = String(pos.symbol || pos.displayName || "").toUpperCase();
const broker = String(pos.brokerId || "").toUpperCase();
const exchange = String(pos.exchange || "").toUpperCase();
return `${sym}|${broker}|${exchange}`;
}
function updateStaleIndicator(container, parts, state) {
if (state?.staleWarning) {
if (!parts.stale) {
parts.stale = document.createElement("div");
parts.stale.className = "pts-stale-indicator";
parts.stale.setAttribute("role", "status");
parts.stale.title =
"Price data may be outdated – check your API key or network";
container.insertBefore(parts.stale, container.firstChild);
}
parts.stale.textContent = "⚠ Stale";
} else if (parts.stale) {
parts.stale.remove();
parts.stale = null;
}
}
function updateAggregate(parts, state) {
const aggregate = parts.aggregate;
const aggPnl = Number(state?.aggregate?.dayPnl) || 0;
const aggPct = Number(state?.aggregate?.dayPnlPct) || 0;
const currency = state?.displayCurrency;
const dirClass = aggPnl > 0 ? "pts-up" : aggPnl < 0 ? "pts-down" : "pts-flat";
const newSign = aggPnl > 0 ? "up" : aggPnl < 0 ? "down" : "flat";
aggregate.classList.remove("pts-up", "pts-down", "pts-flat");
aggregate.classList.add(dirClass);
aggregate.dataset.ptsSign = newSign;
aggregate.textContent = currency
? `MyTicker · Today ${formatSignedCurrency(aggPnl, currency)} (${formatSigned(aggPct)}%)`
: "MyTicker · Today mixed currencies";
}
function buildItemElement(pos) {
const item = document.createElement("div");
item.className = "pts-item";
item.dataset.ptsKey = positionKey(pos);
const groupSpan = document.createElement("span");
groupSpan.className = "pts-group-marker";
const nameSpan = document.createElement("span");
nameSpan.className = "pts-symbol";
const priceSpan = document.createElement("span");
priceSpan.className = "pts-price";
const changeSpan = document.createElement("span");
changeSpan.className = "pts-change";
const pnlSpan = document.createElement("span");
pnlSpan.className = "pts-personal-pnl";
const staleSpan = document.createElement("span");
staleSpan.className = "pts-item-stale";
staleSpan.setAttribute("role", "status");
item.appendChild(groupSpan);
item.appendChild(nameSpan);
item.appendChild(priceSpan);
item.appendChild(changeSpan);
item.appendChild(pnlSpan);
item.appendChild(staleSpan);
return item;
}
function updateItemElement(item, pos, isGroupBoundary) {
const changePct = Number.isFinite(Number(pos.changePct))
? Number(pos.changePct)
: Number(pos.dayPnlPct) || 0;
const isHolding = (pos.kind || "holding") === "holding";
const dayPnl = Number(pos.dayPnl) || 0;
const dirClass = changePct > 0 ? "pts-up" : changePct < 0 ? "pts-down" : "pts-flat";
item.classList.remove("pts-up", "pts-down", "pts-flat", "pts-crypto");
item.classList.add(dirClass);
if (pos.assetClass === "crypto") {
item.classList.add("pts-crypto");
}
item.dataset.ptsKey = positionKey(pos);
// Privacy: never expose quantity in title attributes (page-scrape surface)
item.title = `${pos.displayName || pos.symbol || ""} · ${formatSigned(changePct)}%`;
const [groupSpan, nameSpan, priceSpan, changeSpan, pnlSpan, staleSpan] = item.children;
groupSpan.textContent = isGroupBoundary ? getGroupLabel(pos.kind) : "";
groupSpan.hidden = !isGroupBoundary;
nameSpan.textContent = pos.displayName || pos.symbol || "—";
priceSpan.textContent = formatQuotePrice(pos.lastPrice, pos.currency || "USD");
changeSpan.textContent = `${formatSigned(changePct)}%`;
pnlSpan.textContent = isHolding ? `p&l ${formatSignedCurrency(dayPnl, pos.currency || "USD")}` : "";
pnlSpan.hidden = !isHolding;
staleSpan.textContent = pos.stale ? "stale" : "";
staleSpan.hidden = !pos.stale;
staleSpan.setAttribute("aria-label", pos.stale ? "Stale quote" : "");
}
function updateScrollItems(parts, state) {
const positions = state?.tickerItems || state?.positions || [];
const reduced = prefersReducedMotion();
const scrollInner = parts.scrollInner;
const renderSlots = (slotCount) => {
while (scrollInner.children.length > slotCount) {
scrollInner.removeChild(scrollInner.lastChild);
}
for (let i = 0; i < slotCount; i++) {
const pos = positions[i % positions.length];
if (!pos) continue;
let item = scrollInner.children[i];
if (!item) {
item = buildItemElement(pos);
scrollInner.appendChild(item);
}
const previous = positions[(i - 1 + positions.length) % positions.length];
const isGroupBoundary = i % positions.length === 0 || previous?.kind !== pos.kind;
updateItemElement(item, pos, isGroupBoundary);
}
};
// Measure one copy first. Duplicate only when it actually overflows, so the
// marquee remains the tape's sole continuous animation.
renderSlots(positions.length);
const shouldMarquee = !reduced && scrollInner.scrollWidth > parts.scrollWrapper.clientWidth;
renderSlots(shouldMarquee ? positions.length * 2 : positions.length);
parts.scrollInner.classList.toggle("pts-scroll-static", !shouldMarquee);
}
function clearTickerContent(container) {
const parts = container._ptsParts;
if (parts?.stale) {
parts.stale.remove();
parts.stale = null;
}
if (parts?.aggregate) {
parts.aggregate.textContent = "No items — add holdings or a watchlist";
parts.aggregate.classList.remove("pts-up", "pts-down", "pts-flat");
parts.aggregate.classList.add("pts-flat");
delete parts.aggregate.dataset.ptsSign;
}
if (parts?.scrollInner) {
while (parts.scrollInner.firstChild) {
parts.scrollInner.removeChild(parts.scrollInner.firstChild);
}
}
}
function renderTicker(state) {
if (!tickerBar) return;
tickerBar.classList.toggle("pts-reduced-motion", prefersReducedMotion());
if (!latestStateResolved && !state) {
const parts = getTickerParts(tickerBar);
parts.aggregate.textContent = "Updating markets";
parts.aggregate.classList.remove("pts-up", "pts-down");
parts.aggregate.classList.add("pts-flat");
while (parts.scrollInner.firstChild) parts.scrollInner.removeChild(parts.scrollInner.firstChild);
return;
}
const items = state?.tickerItems || state?.positions || [];
if (!items.length) {
getTickerParts(tickerBar);
clearTickerContent(tickerBar);
reportLifecycle("render-success");
return;
}
const parts = getTickerParts(tickerBar);
updateStaleIndicator(tickerBar, parts, state);
updateAggregate(parts, state);
updateScrollItems(parts, state);
reportLifecycle("render-success");
}
function getGroupLabel(kind) {
if (kind === "watchlist") return "watchlist";
if (kind === "crypto") return "crypto";
return "holdings";
}
function getInitials(name) {
if (!name) return "";
const parts = String(name)
.split(/\s+/)
.filter(Boolean);
if (!parts.length) return "";
if (parts.length === 1) {
return parts[0].slice(0, 2).toUpperCase();
}
return (parts[0][0] + parts[1][0]).toUpperCase();
}
function applyTickerSpeed(settings) {
const duration =
settings?.tickerStyleConfig?.tickerSpeed ||
40;
const value = `${Number(duration)}s`;
// Set on host document (inherited) and bar if present
document.documentElement.style.setProperty("--pts-ticker-duration", value);
if (tickerBar) {
tickerBar.style.setProperty("--pts-ticker-duration", value);
}
}
function getTapeScale(settings) {
const size = normalizeTapeScale(settings?.tickerStyleConfig?.tapeScale);
return { compact: 0.92, comfortable: 1.08, large: 1.20 }[size];
}
function applyTapeSize(settings) {
const size = normalizeTapeScale(settings?.tickerStyleConfig?.tapeScale);
const scale = getTapeScale(settings);
document.documentElement.style.setProperty("--pts-tape-scale", String(scale));
if (tickerBar) {
tickerBar.setAttribute("data-tape-size", size);
tickerBar.style.setProperty("--pts-tape-scale", String(scale));
}
if (tapeReservation) applyTapeReservation();
}
function applyTickerTheme(settings) {
const theme = ["light", "dark"].includes(settings?.tickerStyleConfig?.theme)
? settings.tickerStyleConfig.theme
: "system";
if (tickerBar) tickerBar.setAttribute("data-theme", theme);
}
function normalizeTapeScale(value) {
return ["compact", "comfortable", "large"].includes(value) ? value : "comfortable";
}