Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/viewer/app/tv-chart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ test('the widget follows the interval, theme and language, and never lets the sy
expect(c.hide_volume).toBe(true);
// no range: TradingView's own view of the interval, the last candle near the price scale (a range left ~10 empty candles)
expect('range' in c).toBe(false);
// no zoom kept by TradingView across charts: every draw and ↻ is the standard view
expect(c.disabled_features).toEqual(['use_localstorage_for_settings']);
expect(tvConfig('AAPL', 'D', false, 'en', 'tv-2', '#368727').theme).toBe('light');
});

Expand Down
13 changes: 8 additions & 5 deletions src/viewer/app/tv-chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,13 @@ export function candleOverrides(c: CandleColors): Record<string, string | boolea
};
}

// No `range`: each chart opens on TradingView's own view of its interval, about 2.5 months of Daily, 9 months of Weekly
// and 3.5 years of Monthly, with the last candle 4 to 5 candles from the price scale. A `range` (2m, 8m, 33m from the
// owner's "press + 3 times", 2026-12-03) fit those spans but left about 10 empty candles at the right; the owner asked for
// the default look instead (2026-12-03: "we must checge this ... when click here [↻] to this"). The right room itself is
// not ours to set: tv.js passes overrides for it, the chart ignores them (checked in Chrome 2026-12-03)
// No `range` and no memory: each chart opens, and ↻ draws it again, on TradingView's own standard view of its interval,
// the last candle 2 or 3 candles from the price scale (owner 2026-12-03: "we must checge this ... when click here [↻] to
// this"). A `range` (2m, 8m, 33m from the owner's "press + 3 times") fit its span but left about 10 empty candles at the
// right. Without `use_localstorage_for_settings` the widget would keep the last zoom of any chart in its own storage and
// draw every new chart with it, so ↻ could not go back to the standard view; the zoom and position of an open window stay
// for its next open because the closed window is kept drawn (ui/Zoom.tsx keep). The right room and the bar width are not
// ours to set: tv.js passes overrides for them, the chart ignores them (all checked in Chrome 2026-12-03)

/**
* the widget's settings: our interval, theme, language and card colour; no symbol change, no toolbar (our pills pick the
Expand All @@ -92,6 +94,7 @@ export function tvConfig(ticker: string, interval: TvInterval, dark: boolean, la
hide_side_toolbar: true,
hide_volume: true,
allow_symbol_change: false,
disabled_features: ['use_localstorage_for_settings'],
save_image: false,
overrides: {
...candleOverrides(candleColors(dark, brand)),
Expand Down
17 changes: 13 additions & 4 deletions src/viewer/ui/Fundamentals.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/// <reference lib="esnext" />
import { useEffect, useRef, useState } from 'react';
import { useEffect, useId, useRef, useState } from 'react';
import type { Position } from '../../shared/model';
import { fundamentalsFrame, fundamentalsLater, fundamentalsTicker, fundamentalsUrl, reopens } from '../app/fundamentals';
import { lang, t } from '../app/i18n';
import { prefs, setPrefs } from '../app/prefs';
import { createStore } from '../../shared/store';
import { shownPicked } from '../app/multi';
import { asSplit, paneDir } from '../app/split';
import { CHART_HEAD_STEPS, chartHeadLook, fitStep } from '../app/head-fit';
Expand Down Expand Up @@ -37,6 +38,10 @@ export const hasFundamentals = (p: Position): boolean => !!fundamentalsFrame(p,
// the words of the intervals, said in the app's language when drawn
const WORDS: Record<TvInterval, () => string> = { D: () => t('Daily'), W: () => t('Weekly'), M: () => t('Monthly') };

// the one window kept drawn while closed (ui/Zoom.tsx keep), the last one opened: its charts keep their zoom and position
// for the next open until ↻; opening another symbol's window lets the old one go, so only one set of frames stays alive
const keptWindow = createStore<string>('');

// set once a link reopened the window kept from before the reload, so the other links of that symbol do not open theirs
let reopened = false;

Expand All @@ -48,10 +53,13 @@ let reopened = false;
export function FundamentalsLink({ p, className, children }: { p: Position; className: string; children: React.ReactNode }) {
const [open, setOpenState] = useState(false);
// the open window is kept in the prefs, so a reload opens it again (owner 2026-12-03)
const setOpen = (on: boolean): void => { setOpenState(on); setPrefs({ fundamentalsOpen: on ? p.symbol : '' }); };
const me = useId();
const kept = useStore(keptWindow) === me;
const setOpen = (on: boolean): void => { setOpenState(on); if (on) keptWindow.set(me); setPrefs({ fundamentalsOpen: on ? p.symbol : '' }); };
useEffect(() => {
if (!reopens(prefs.get().fundamentalsOpen, p.symbol, reopened)) return;
reopened = true;
keptWindow.set(me);
setOpenState(true);
}, [p.symbol]);
const [drawn, setDrawn] = useState(0);
Expand All @@ -64,7 +72,8 @@ export function FundamentalsLink({ p, className, children }: { p: Position; clas
// controls is measured in an invisible copy, the ticker as drawn, the head is as wide as the charts or the page under it
const [looksBox, looks] = useWidths<HTMLSpanElement>();
const [headingBox, headingWidth] = useWidth<HTMLSpanElement>();
const dark = open && typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
// the theme of the page, read on every draw also while closed: a kept window must not redraw its charts on close
const dark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
const frame = fundamentalsFrame(p, dark, language);
const page = fundamentalsUrl(p);
const ticker = fundamentalsTicker(p);
Expand Down Expand Up @@ -121,7 +130,7 @@ export function FundamentalsLink({ p, className, children }: { p: Position; clas
return (
<>
<button ref={from} type="button" className={className} title={title} aria-label={title} onClick={() => setOpen(true)} data-fundamentals>{children}</button>
<Zoom open={open} title={title} heading={heading} oneLine origin={from} onClose={() => setOpen(false)} tools={tools}>
<Zoom open={open} keep={kept} title={title} heading={heading} oneLine origin={from} onClose={() => setOpen(false)} tools={tools}>
{chart
// one chart per interval: side by side, or one under another when the window is too narrow for that
? <div ref={charts} className="h-[78vh] w-full" data-tv-charts={shown.join(' ')}>
Expand Down
51 changes: 51 additions & 0 deletions src/viewer/ui/Zoom.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/// <reference types="bun" />
/// <reference types="node" />
/// <reference lib="esnext" />
// A kept window stays drawn but hidden when closed, so its frames keep their state (the TradingView charts' zoom); a
// plain one goes away; neither is drawn before its first open
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { GlobalRegistrator } from '@happy-dom/global-registrator';

// no animations here: the window opens and closes at once (Zoom's path for a browser without Element.animate); put back
// afterwards, the other test files share the same classes
let animate: unknown;
beforeAll(() => {
GlobalRegistrator.register({ url: 'http://localhost:1237/' });
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const proto = Element.prototype as unknown as { animate?: unknown };
animate = proto.animate;
proto.animate = undefined;
});
afterAll(() => {
(Element.prototype as unknown as { animate?: unknown }).animate = animate;
GlobalRegistrator.unregister();
});

test('closed, a kept window stays hidden with its content, a plain one is gone', async () => {
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { Zoom } = await import('./Zoom');
document.body.innerHTML = '<div id="root"></div>';
const root = createRoot(document.getElementById('root')!);
const draw = (open: boolean, keep: boolean) => act(async () => root.render(<Zoom open={open} keep={keep} title="PG" onClose={() => undefined}><iframe data-frame title="chart" /></Zoom>));
const win = () => document.querySelector<HTMLElement>('[data-chart-zoom]');

await draw(false, true);
expect(win()).toBeNull(); // never opened: nothing drawn, nothing loaded
await draw(true, true);
expect(win()?.style.visibility).toBe('');
const frame = document.querySelector('[data-frame]');
await draw(false, true);
expect(win()?.dataset.parked).toBe('on');
expect(win()?.style.visibility).toBe('hidden');
expect(win()?.hasAttribute('inert')).toBe(true);
expect(document.querySelector('[data-frame]')).toBe(frame); // the same frame, not a new one
await draw(true, true);
expect(win()?.dataset.parked).toBeUndefined();
expect(win()?.style.visibility).toBe('');
expect(document.querySelector('[data-frame]')).toBe(frame);
// no longer the kept one (another window opened): closed, it goes away
await draw(false, false);
expect(win()).toBeNull();
await act(async () => root.unmount());
});
24 changes: 19 additions & 5 deletions src/viewer/ui/Zoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,18 @@ const focusables = (root: HTMLElement): HTMLElement[] =>
// `heading`: what the title line shows when it is more than the words of `title` (a link); `oneLine`: the tools stay on the
// title's line on a phone too, wrapping only when they do not fit (the chart window, owner 2026-12-03: "I dont want to see
// intervals below line with ticker")
export function Zoom({ open, title, onClose, children, tools, origin, narrow, heading, oneLine }: { open: boolean; title: string; onClose: () => void; children: React.ReactNode; tools?: React.ReactNode; origin?: React.RefObject<HTMLElement | null>; narrow?: boolean; heading?: React.ReactNode; oneLine?: boolean }) {
// `keep`: closed, the window stays drawn but hidden (visibility, the same size, no events), so what lives in its frames
// keeps its state for the next open (the TradingView charts' zoom and position, owner 2026-12-03: "next time I open (if not
// pressed on ↻) the config for these charts should stay the same as it was before I closed"); a frame cannot be moved or
// read, only kept
export function Zoom({ open, title, onClose, children, tools, origin, narrow, heading, oneLine, keep }: { open: boolean; title: string; onClose: () => void; children: React.ReactNode; tools?: React.ReactNode; origin?: React.RefObject<HTMLElement | null>; narrow?: boolean; heading?: React.ReactNode; oneLine?: boolean; keep?: boolean }) {
const [mounted, setMounted] = useState(open);
// opened at least once: before that nothing is drawn, a kept window loads its frames only when first opened
const [opened, setOpened] = useState(open);
const root = useRef<HTMLDivElement>(null);
const panel = useRef<HTMLDivElement>(null);
const back = useRef<HTMLDivElement>(null);
useEffect(() => { if (open) setMounted(true); }, [open]);
useEffect(() => { if (open) { setMounted(true); setOpened(true); } }, [open]);
useLayoutEffect(() => {
const p = panel.current;
const b = back.current;
Expand All @@ -49,7 +56,12 @@ export function Zoom({ open, title, onClose, children, tools, origin, narrow, he
let done = false;
grow.onfinish = () => {
done = true;
if (open) { grow.cancel(); dim.cancel(); } else setMounted(false);
if (open) { grow.cancel(); dim.cancel(); return; }
// a kept window hides before its animation lets go of the shrunk look, so it never flashes back full size
if (root.current) root.current.style.visibility = 'hidden';
grow.cancel();
dim.cancel();
setMounted(false);
};
// a reopen while it shrinks stops the old animation; the new one starts from the card again
return () => { if (!done) { grow.cancel(); dim.cancel(); } };
Expand Down Expand Up @@ -86,11 +98,13 @@ export function Zoom({ open, title, onClose, children, tools, origin, narrow, he
const fromFrames = panel.current ? frameKeys(panel.current, (e) => { if (e.key === 'Escape') onClose(); }) : () => undefined;
return () => { window.removeEventListener('keydown', onKey); fromFrames(); };
}, [open, onClose, mounted]); // mounted: the window is drawn a moment after `open`, its frames with it
if (!mounted) return null;
const parked = !mounted && !!keep && opened;
if (!mounted && !parked) return null;
// drawn into <body>, not inside the card: a card in the packed columns with its own view-transition layer would let
// the next card paint over the window (owner 2026-11-24 found it)
return createPortal((
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-label={title} data-chart-zoom>
<div ref={root} className="fixed inset-0 z-50 flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-label={title} data-chart-zoom
style={parked ? { visibility: 'hidden' } : undefined} inert={parked} aria-hidden={parked || undefined} data-parked={parked ? 'on' : undefined}>
<div ref={back} className="absolute inset-0 bg-slate-950/60" onClick={onClose} />
<div ref={panel} className={`card relative flex max-h-full w-full ${narrow ? 'max-w-4xl' : 'max-w-[min(96vw,100rem)]'} flex-col gap-3 overflow-auto`} style={{ transformOrigin: 'top left' }}>
{/* the tools sit on the right next to ✕, as on the card next to ⤢ (owner 2026-11-24: "move all buttons to the right") */}
Expand Down