diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 6bbc53115f0..2c26ca29c9e 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -302,6 +302,312 @@ "count": 1 } }, + "packages/advanced-chart-core/src/__tests__/index.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 2 + }, + "typescript/no-unsafe-assignment": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/core/__tests__/bootstrap.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 4 + }, + "typescript/no-unsafe-assignment": { + "count": 1 + }, + "typescript/unbound-method": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/core/__tests__/bridge.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 1 + }, + "typescript/no-unsafe-assignment": { + "count": 1 + }, + "typescript/unbound-method": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/core/__tests__/loadLibrary.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 2 + } + }, + "packages/advanced-chart-core/src/core/__tests__/resolution.test.ts": { + "typescript/no-unsafe-argument": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/core/__tests__/timezone.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/core/dataLifecycle.ts": { + "no-shadow": { + "count": 2 + } + }, + "packages/advanced-chart-core/src/core/state.ts": { + "no-shadow": { + "count": 2 + } + }, + "packages/advanced-chart-core/src/features/indicators/__tests__/indicators.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/features/indicators/__tests__/legend.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 56 + }, + "typescript/unbound-method": { + "count": 3 + } + }, + "packages/advanced-chart-core/src/features/indicators/__tests__/subPane.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 2 + }, + "typescript/no-unsafe-member-access": { + "count": 3 + } + }, + "packages/advanced-chart-core/src/features/indicators/index.ts": { + "no-shadow": { + "count": 6 + }, + "unicorn/no-useless-undefined": { + "count": 3 + } + }, + "packages/advanced-chart-core/src/features/indicators/legend.ts": { + "no-shadow": { + "count": 10 + }, + "unicorn/no-useless-undefined": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/features/indicators/studies.ts": { + "no-shadow": { + "count": 3 + } + }, + "packages/advanced-chart-core/src/features/volume/__tests__/volume.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 1 + }, + "typescript/no-unsafe-member-access": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/features/volume/index.ts": { + "unicorn/no-useless-undefined": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/interaction/__tests__/crosshair.test.ts": { + "id-length": { + "count": 2 + }, + "no-shadow": { + "count": 2 + }, + "typescript/no-unsafe-assignment": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/interaction/__tests__/visibleRange.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/messages/__tests__/handler.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/messages/handler.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/overlays/positionLines/__tests__/positionLines.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 1 + }, + "typescript/no-unsafe-member-access": { + "count": 4 + } + }, + "packages/advanced-chart-core/src/overlays/positionLines/__tests__/state.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 5 + } + }, + "packages/advanced-chart-core/src/overlays/positionLines/index.ts": { + "unicorn/no-useless-undefined": { + "count": 3 + } + }, + "packages/advanced-chart-core/src/overlays/socialLeaderboard/__tests__/socialLeaderboard.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 2 + } + }, + "packages/advanced-chart-core/src/overlays/tradeMarkers/__tests__/animation.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/overlays/tradeMarkers/__tests__/markerHitTest.test.ts": { + "no-shadow": { + "count": 2 + }, + "typescript/no-unnecessary-type-assertion": { + "count": 1 + }, + "typescript/no-unsafe-assignment": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/overlays/tradeMarkers/index.ts": { + "no-shadow": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/pagination/__tests__/priceApi.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 3 + }, + "typescript/no-unsafe-assignment": { + "count": 1 + }, + "typescript/no-unsafe-member-access": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/pagination/__tests__/rnBacked.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 13 + }, + "typescript/no-unsafe-assignment": { + "count": 18 + }, + "typescript/no-unsafe-member-access": { + "count": 22 + } + }, + "packages/advanced-chart-core/src/platform/__tests__/reactNativeHost.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 1 + }, + "typescript/unbound-method": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/platform/iframeHost.ts": { + "no-shadow": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/platform/reactNativeHost.ts": { + "no-shadow": { + "count": 2 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/chartType.test.ts": { + "typescript/no-unsafe-member-access": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/datafeed.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 11 + }, + "typescript/no-unsafe-assignment": { + "count": 4 + }, + "typescript/no-unsafe-member-access": { + "count": 13 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/externalLinkBridge.test.ts": { + "no-shadow": { + "count": 1 + }, + "typescript/no-unnecessary-type-assertion": { + "count": 1 + }, + "typescript/no-unsafe-assignment": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/initChart.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 2 + }, + "typescript/no-unsafe-assignment": { + "count": 3 + }, + "typescript/no-unsafe-call": { + "count": 9 + }, + "typescript/no-unsafe-member-access": { + "count": 18 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/ohlcvIngestion.test.ts": { + "no-shadow": { + "count": 4 + }, + "no-unsafe-optional-chaining": { + "count": 5 + }, + "typescript/no-unsafe-assignment": { + "count": 9 + }, + "typescript/no-unsafe-call": { + "count": 4 + }, + "typescript/no-unsafe-member-access": { + "count": 13 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/scaleLayout.test.ts": { + "typescript/no-unsafe-member-access": { + "count": 10 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/theme.test.ts": { + "typescript/no-unsafe-assignment": { + "count": 4 + }, + "typescript/no-unsafe-member-access": { + "count": 11 + } + }, + "packages/advanced-chart-core/src/widget/__tests__/tvDomHelpers.test.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/widget/datafeed.ts": { + "unicorn/no-useless-undefined": { + "count": 1 + } + }, + "packages/advanced-chart-core/src/widget/externalLinkBridge.ts": { + "typescript/no-unnecessary-type-assertion": { + "count": 5 + } + }, "packages/ai-controllers/jest.config.cjs": { "import/unambiguous": { "count": 1 diff --git a/oxlint.config.ts b/oxlint.config.ts index ec85f4d616e..0b45fa4065e 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -83,6 +83,11 @@ export default createConfig({ }, }, + { + files: ['packages/advanced-chart-core/**'], + env: { browser: true }, + }, + { files: [ 'packages/bitcoin-regtest-up/src/bin/bitcoin-regtest-up.ts', diff --git a/packages/advanced-chart-core/jest.config.cjs b/packages/advanced-chart-core/jest.config.cjs index 88d80a03d24..241ca8f4066 100644 --- a/packages/advanced-chart-core/jest.config.cjs +++ b/packages/advanced-chart-core/jest.config.cjs @@ -13,4 +13,14 @@ const displayName = path.basename(__dirname); module.exports = merge(baseConfig, { // The display name when running multiple projects displayName, + + // The TradingView Advanced Charts engine is browser/WebView code that relies + // on `window`, `document`, and `requestAnimationFrame`, so its tests run in a + // DOM environment. (Upstream in mobile these were per-file `@jest-environment + // jsdom` docblocks; here it is the package default.) + testEnvironment: 'jsdom', + + // Reset the node-oriented `customExportConditions` inherited from the base + // config so jsdom resolves browser export conditions. + testEnvironmentOptions: {}, }); diff --git a/packages/advanced-chart-core/package.json b/packages/advanced-chart-core/package.json index 09ad1a87560..bac94dd844c 100644 --- a/packages/advanced-chart-core/package.json +++ b/packages/advanced-chart-core/package.json @@ -25,6 +25,10 @@ "types": "./dist/index.d.ts", "default": "./dist/index.js" }, + "./host": { + "types": "./dist/host-entry.d.ts", + "default": "./dist/host-entry.js" + }, "./package.json": "./package.json" }, "publishConfig": { @@ -41,8 +45,6 @@ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/advanced-chart-core", "lint:tsconfigs": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts", "lint:tsconfigs:fix": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts --fix", - "messenger-action-types:check": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --check", - "messenger-action-types:generate": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --generate", "publish:preview": "yarn npm publish --tag preview", "since-latest-release": "../../scripts/since-latest-release.sh", "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter", @@ -56,11 +58,11 @@ "@typescript/native": "npm:typescript@^7.0.2", "deepmerge": "^4.3.1", "jest": "^30.4.2", + "jest-environment-jsdom": "^30.4.1", "rimraf": "^6.1.3", "ts-jest": "^29.4.14", "tsx": "^4.23.15", "typedoc": "^0.25.13", - "typedoc-plugin-missing-exports": "^2.0.0", "typescript": "npm:@typescript/typescript6@^6.0.2" }, "engines": { diff --git a/packages/advanced-chart-core/src/__tests__/index.test.ts b/packages/advanced-chart-core/src/__tests__/index.test.ts index 56181317a21..ac36b9a2f4b 100644 --- a/packages/advanced-chart-core/src/__tests__/index.test.ts +++ b/packages/advanced-chart-core/src/__tests__/index.test.ts @@ -1,7 +1,80 @@ -import { greeter } from '../index.js'; +import { _resetStateForTests } from '../core/state.js'; +import type { ChartConfig, ChartTheme } from '../core/types.js'; +import { _resetHandlersForTests } from '../messages/handler.js'; +import { _resetOhlcvIngestionForTests } from '../widget/ohlcvIngestion.js'; +import { _resetThemeForTests } from '../widget/theme.js'; -describe('greeter', () => { - it('should greet', () => { - expect(greeter('World')).toBe('Hello, World!'); +const baseTheme: ChartTheme = { + backgroundColor: 'rgb(0,0,0)', + borderColor: 'rgb(17,17,17)', + textColor: 'rgb(255,255,255)', + textDefaultColor: 'rgb(255,255,255)', + sectionBackgroundColor: 'rgb(34,34,34)', + crosshairBackgroundColor: 'rgb(51,51,51)', + crosshairTextColor: 'rgb(238,238,238)', + legendTextColor: 'rgb(170,170,170)', + textAlternativeColor: 'rgb(187,187,187)', + successColor: 'rgb(0,255,0)', + lineColor: 'rgb(171,205,239)', + errorColor: 'rgb(255,0,0)', + primaryColor: 'rgb(0,51,255)', + currentPriceColor: 'rgb(34,34,0)', +}; + +const baseConfig: ChartConfig = { + libraryUrl: 'https://cdn.example.com/', + theme: baseTheme, +}; + +type MockBridge = { + postMessage: jest.Mock; +}; + +describe('src/index.ts entry point', () => { + let bridge: MockBridge; + + beforeEach(() => { + _resetStateForTests(); + _resetHandlersForTests(); + _resetThemeForTests(); + _resetOhlcvIngestionForTests(); + bridge = { postMessage: jest.fn() }; + window.ReactNativeWebView = bridge; + window.CONFIG = baseConfig; + + jest + .spyOn(document, 'createElement') + .mockImplementation(((tag: string) => + tag === 'script' + ? ({} as unknown as HTMLScriptElement) + : ({} as HTMLElement)) as never); + jest + .spyOn(document.head, 'appendChild') + .mockImplementation(((node: Node) => node) as never); + jest.spyOn(window, 'addEventListener').mockImplementation(); + jest.spyOn(document, 'addEventListener').mockImplementation(); + + jest.resetModules(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + delete window.CONFIG; + delete window.ReactNativeWebView; + }); + + it('calls bootstrap() and emits DEBUG on import', async () => { + await import('../index.js'); + expect(bridge.postMessage).toHaveBeenCalledWith( + expect.stringContaining('modular-bootstrap-ready'), + ); + }); + + it('reports error to RN when bootstrap throws', async () => { + delete window.CONFIG; + await import('../index.js'); + expect(bridge.postMessage).toHaveBeenCalledWith( + expect.stringContaining('"type":"ERROR"'), + ); }); }); diff --git a/packages/advanced-chart-core/src/core/__tests__/bootstrap.test.ts b/packages/advanced-chart-core/src/core/__tests__/bootstrap.test.ts new file mode 100644 index 00000000000..d58663f26f5 --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/bootstrap.test.ts @@ -0,0 +1,411 @@ +import { + _resetHandlersForTests, + dispatchInboundMessage, +} from '../../messages/handler.js'; +import { _resetOhlcvIngestionForTests } from '../../widget/ohlcvIngestion.js'; +import { _resetThemeForTests } from '../../widget/theme.js'; +import { bootstrap } from '../bootstrap.js'; +import { _resetLoadLibraryForTests } from '../loadLibrary.js'; +import { + _resetStateForTests, + getTheme, + getSubPaneHeightRatio, +} from '../state.js'; +import type { ChartConfig, ChartTheme } from '../types.js'; + +const baseTheme: ChartTheme = { + backgroundColor: 'rgb(0,0,0)', + borderColor: 'rgb(17,17,17)', + textColor: 'rgb(255,255,255)', + textDefaultColor: 'rgb(255,255,255)', + sectionBackgroundColor: 'rgb(34,34,34)', + crosshairBackgroundColor: 'rgb(51,51,51)', + crosshairTextColor: 'rgb(238,238,238)', + legendTextColor: 'rgb(170,170,170)', + textAlternativeColor: 'rgb(187,187,187)', + successColor: 'rgb(0,255,0)', + lineColor: 'rgb(171,205,239)', + errorColor: 'rgb(255,0,0)', + primaryColor: 'rgb(0,51,255)', + currentPriceColor: 'rgb(34,34,0)', +}; + +const baseConfig: ChartConfig = { + libraryUrl: 'https://cdn.example.com/', + theme: baseTheme, +}; + +type MockBridge = { + postMessage: jest.Mock; +}; + +describe('core/bootstrap', () => { + let bridge: MockBridge; + + beforeEach(() => { + _resetStateForTests(); + _resetHandlersForTests(); + _resetThemeForTests(); + _resetOhlcvIngestionForTests(); + _resetLoadLibraryForTests(); + bridge = { postMessage: jest.fn() }; + window.ReactNativeWebView = bridge; + window.CONFIG = baseConfig; + + // Prevent loadLibrary from actually appending a script. + const createElementImpl = (tag: string): HTMLElement => { + if (tag === 'script') { + return {} as unknown as HTMLScriptElement; + } + return {} as HTMLElement; + }; + jest + .spyOn(document, 'createElement') + .mockImplementation(createElementImpl as never); + jest + .spyOn(document.head, 'appendChild') + .mockImplementation(((node: Node) => node) as never); + jest.spyOn(window, 'addEventListener').mockImplementation(); + jest.spyOn(document, 'addEventListener').mockImplementation(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + delete window.CONFIG; + delete window.ReactNativeWebView; + }); + + it('throws when window.CONFIG is missing', () => { + delete window.CONFIG; + expect(() => bootstrap()).toThrow(/window.CONFIG is missing/u); + }); + + it('seeds theme state from CONFIG.theme', () => { + bootstrap(); + expect(getTheme()).toStrictEqual(baseTheme); + }); + + it('emits a DEBUG breadcrumb so RN can confirm the modular bundle booted', () => { + bootstrap(); + expect(bridge.postMessage).toHaveBeenCalledWith( + expect.stringContaining('"type":"DEBUG"'), + ); + expect(bridge.postMessage).toHaveBeenCalledWith( + expect.stringContaining('modular-bootstrap-ready'), + ); + }); + + it('subscribes to both window and document message events', () => { + bootstrap(); + expect(window.addEventListener).toHaveBeenCalledWith( + 'message', + expect.any(Function), + ); + expect(document.addEventListener).toHaveBeenCalledWith( + 'message', + expect.any(Function), + ); + }); + + it('registers SET_THEME_COLORS so dispatch updates state.theme', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'SET_THEME_COLORS', + payload: { lineColor: '#newline' }, + }); + expect(getTheme()?.lineColor).toBe('#newline'); + }); + + // --- subPaneHeightRatio --------------------------------------------------- + + it('sets subPaneHeightRatio when config provides a number', () => { + window.CONFIG = { + ...baseConfig, + subPaneHeightRatio: 0.35, + }; + bootstrap(); + expect(getSubPaneHeightRatio()).toBe(0.35); + }); + + it('leaves subPaneHeightRatio null when config omits it', () => { + bootstrap(); + expect(getSubPaneHeightRatio()).toBeNull(); + }); + + // --- Handler wiring: all registered message types dispatch without error --- + + it('dispatches SET_OHLCV_DATA without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'SET_OHLCV_DATA', + payload: { + data: [ + { time: 1000, open: 1, high: 2, low: 0.5, close: 1.5 }, + { time: 2000, open: 1.5, high: 3, low: 1, close: 2.5 }, + ], + }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches SET_CHART_TYPE without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'SET_CHART_TYPE', + payload: { type: 1 }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches REALTIME_UPDATE without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'REALTIME_UPDATE', + payload: { + bar: { time: 3000, open: 2, high: 4, low: 1, close: 3 }, + }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches ADD_INDICATOR without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'ADD_INDICATOR', + payload: { name: 'RSI' }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches REMOVE_INDICATOR without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'REMOVE_INDICATOR', + payload: { name: 'RSI' }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches SET_MA_VISIBILITY without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'SET_MA_VISIBILITY', + payload: { visible: ['MA5', 'MA20'] }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches TOGGLE_VOLUME without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'TOGGLE_VOLUME', + payload: { visible: true }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches SET_SUB_PANE_LAYOUT without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'SET_SUB_PANE_LAYOUT', + payload: { heightRatio: 0.4 }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + // --- Overlay/feature registrations: dispatching overlay messages ---------- + + it('dispatches SET_TRADE_MARKERS without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'SET_TRADE_MARKERS', + payload: { markers: null }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches PULSE_TRADE_MARKER without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'PULSE_TRADE_MARKER', + payload: { id: 'marker-1' }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches FOCUS_TIME without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'FOCUS_TIME', + payload: { timeMs: 1_625_000_000_000 }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches SET_POSITION_LINES without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'SET_POSITION_LINES', + payload: { position: null }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('dispatches FETCH_OLDER_BARS_RESPONSE without reporting an error', () => { + bootstrap(); + dispatchInboundMessage({ + type: 'FETCH_OLDER_BARS_RESPONSE', + payload: { + requestId: 'req-1', + seriesGeneration: 1, + bars: [], + }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + // --- buildInitialTimeframe (tested indirectly via onFirstOhlcvData) -------- + + it('onFirstOhlcvData callback fires when first SET_OHLCV_DATA arrives', () => { + bootstrap(); + // Register a spy callback that will be called on first OHLCV data + // We need to reset and re-bootstrap to install our spy before first data + _resetStateForTests(); + _resetHandlersForTests(); + _resetThemeForTests(); + _resetOhlcvIngestionForTests(); + window.CONFIG = baseConfig; + bootstrap(); + + // onFirstOhlcvData is called during bootstrap, but we can verify + // the first-data path by dispatching SET_OHLCV_DATA + dispatchInboundMessage({ + type: 'SET_OHLCV_DATA', + payload: { + data: [ + { time: 1_000_000, open: 1, high: 2, low: 0.5, close: 1.5 }, + { time: 2_000_000, open: 1.5, high: 3, low: 1, close: 2.5 }, + ], + }, + }); + // No widget exists, so the first-data callback should have been invoked + // (library load starts). Verify no ERROR was reported. + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('buildInitialTimeframe returns undefined when visibleFromMs is null', () => { + // Bootstrap without visibleFromMs set — the onFirstOhlcvData callback + // will pass undefined as the timeframe to createChartWidget. + // We verify indirectly: dispatch OHLCV data without visibleFromMs, + // the first-data path should not error. + bootstrap(); + dispatchInboundMessage({ + type: 'SET_OHLCV_DATA', + payload: { + data: [ + { time: 1_000_000, open: 1, high: 2, low: 0.5, close: 1.5 }, + { time: 2_000_000, open: 1.5, high: 3, low: 1, close: 2.5 }, + ], + }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + it('buildInitialTimeframe returns a time-range when visibleFromMs is set', () => { + bootstrap(); + // Dispatch OHLCV with visibleFromMs to exercise the time-range path + dispatchInboundMessage({ + type: 'SET_OHLCV_DATA', + payload: { + data: [ + { time: 1_625_000_000_000, open: 1, high: 2, low: 0.5, close: 1.5 }, + { time: 1_625_001_000_000, open: 1.5, high: 3, low: 1, close: 2.5 }, + ], + visibleFromMs: 1_625_000_000_000, + visibleToMs: 1_625_001_000_000, + }, + }); + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls).toHaveLength(0); + }); + + // --- Library load error path ----------------------------------------------- + + it('reports error to RN when loadTradingViewLibrary rejects', async () => { + // Override the createElement mock to simulate a script load error + const mockScript: Record = {}; + jest.spyOn(document, 'createElement').mockImplementation(((tag: string) => { + if (tag === 'script') { + return mockScript as unknown as HTMLScriptElement; + } + return {} as HTMLElement; + }) as never); + jest.spyOn(document.head, 'appendChild').mockImplementation((( + node: Node, + ) => { + // Trigger the onerror handler asynchronously to simulate load failure + if (mockScript.onerror) { + setTimeout(() => (mockScript.onerror as () => void)(), 0); + } + return node; + }) as never); + + bootstrap(); + + // Wait for the async error handler to fire + await new Promise((resolve) => setTimeout(resolve, 10)); + + const errorCalls = bridge.postMessage.mock.calls.filter((call) => + call[0].includes('"type":"ERROR"'), + ); + expect(errorCalls.length).toBeGreaterThanOrEqual(1); + expect(errorCalls[0][0]).toContain('Failed to load TradingView library'); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/bridge.test.ts b/packages/advanced-chart-core/src/core/__tests__/bridge.test.ts new file mode 100644 index 00000000000..012b0e7cfe3 --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/bridge.test.ts @@ -0,0 +1,160 @@ +import type { InboundMessage } from '../../messages/contract.js'; +import { onFromRN, postToRN, reportErrorToRN } from '../bridge.js'; + +type MockBridge = { + postMessage: jest.Mock; +}; + +const installRNBridge = (): MockBridge => { + const bridge: MockBridge = { postMessage: jest.fn() }; + window.ReactNativeWebView = bridge; + return bridge; +}; + +const clearRNBridge = (): void => { + delete window.ReactNativeWebView; +}; + +describe('core/bridge', () => { + afterEach(() => { + clearRNBridge(); + }); + + describe('postToRN', () => { + it('serializes type + payload via window.ReactNativeWebView.postMessage', () => { + const bridge = installRNBridge(); + postToRN('CHART_READY', {}); + expect(bridge.postMessage).toHaveBeenCalledTimes(1); + expect(bridge.postMessage).toHaveBeenCalledWith( + JSON.stringify({ type: 'CHART_READY', payload: {} }), + ); + }); + + it('no-ops when ReactNativeWebView is unavailable', () => { + expect(() => postToRN('DEBUG', { message: 'x' })).not.toThrow(); + }); + + it('swallows postMessage failures (cannot report bridge errors)', () => { + const bridge = installRNBridge(); + bridge.postMessage.mockImplementation(() => { + throw new Error('bridge dead'); + }); + expect(() => postToRN('DEBUG', { message: 'x' })).not.toThrow(); + }); + }); + + describe('reportErrorToRN', () => { + it('extracts Error.message and posts to ERROR channel', () => { + const bridge = installRNBridge(); + reportErrorToRN(new Error('kaboom')); + expect(bridge.postMessage).toHaveBeenCalledWith( + JSON.stringify({ type: 'ERROR', payload: { message: 'kaboom' } }), + ); + }); + + it('stringifies non-Error values', () => { + const bridge = installRNBridge(); + reportErrorToRN('oops'); + expect(bridge.postMessage).toHaveBeenCalledWith( + JSON.stringify({ type: 'ERROR', payload: { message: 'oops' } }), + ); + }); + }); + + describe('onFromRN', () => { + let listeners: { window: EventListener[]; document: EventListener[] }; + + beforeEach(() => { + listeners = { window: [], document: [] }; + jest + .spyOn(window, 'addEventListener') + .mockImplementation( + (type: string, listener: EventListenerOrEventListenerObject) => { + if (type === 'message') { + listeners.window.push(listener as EventListener); + } + }, + ); + jest + .spyOn(document, 'addEventListener') + .mockImplementation( + (type: string, listener: EventListenerOrEventListenerObject) => { + if (type === 'message') { + listeners.document.push(listener as EventListener); + } + }, + ); + jest.spyOn(window, 'removeEventListener').mockImplementation(); + jest.spyOn(document, 'removeEventListener').mockImplementation(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('subscribes to both window and document message events', () => { + onFromRN(() => undefined); + expect(listeners.window).toHaveLength(1); + expect(listeners.document).toHaveLength(1); + }); + + it('parses JSON string payloads and forwards typed messages', () => { + const handler = jest.fn(); + onFromRN(handler); + const evt = { + data: JSON.stringify({ + type: 'SET_THEME_COLORS', + payload: { lineColor: 'rgb(170,187,204)' }, + }), + } as MessageEvent; + listeners.window[0](evt); + expect(handler).toHaveBeenCalledWith({ + type: 'SET_THEME_COLORS', + payload: { lineColor: 'rgb(170,187,204)' }, + } as InboundMessage); + }); + + it('reports JSON parse errors via the ERROR channel', () => { + const bridge = installRNBridge(); + onFromRN(() => undefined); + listeners.window[0]({ data: '{not json' } as MessageEvent); + expect(bridge.postMessage).toHaveBeenCalledWith( + expect.stringContaining('"type":"ERROR"'), + ); + }); + + it('drops messages missing a string `type` field', () => { + const handler = jest.fn(); + onFromRN(handler); + listeners.window[0]({ + data: JSON.stringify({ noType: true }), + } as MessageEvent); + listeners.window[0]({ data: '"a string"' } as MessageEvent); + listeners.window[0]({ data: 'null' } as MessageEvent); + expect(handler).not.toHaveBeenCalled(); + }); + + it('rejects messages from real web origins', () => { + const handler = jest.fn(); + onFromRN(handler); + listeners.window[0]({ + origin: 'https://evil.com', + data: JSON.stringify({ type: 'SET_THEME_COLORS', payload: {} }), + } as MessageEvent); + expect(handler).not.toHaveBeenCalled(); + }); + + it('returns an unsubscribe that removes both listeners', () => { + const unsubscribe = onFromRN(() => undefined); + unsubscribe(); + expect(window.removeEventListener).toHaveBeenCalledWith( + 'message', + expect.any(Function), + ); + expect(document.removeEventListener).toHaveBeenCalledWith( + 'message', + expect.any(Function), + ); + }); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/dataLifecycle.test.ts b/packages/advanced-chart-core/src/core/__tests__/dataLifecycle.test.ts new file mode 100644 index 00000000000..5381b20d1a3 --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/dataLifecycle.test.ts @@ -0,0 +1,75 @@ +import { + onDataLifecycle, + notifyDataLifecycle, + _resetDataLifecycleForTests, +} from '../dataLifecycle.js'; + +describe('core/dataLifecycle', () => { + beforeEach(() => { + _resetDataLifecycleForTests(); + delete window.ReactNativeWebView; + }); + + it('notifies listeners when an event fires', () => { + const listener = jest.fn(); + onDataLifecycle('ohlcvReset', listener); + notifyDataLifecycle('ohlcvReset'); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it('supports multiple listeners on the same event', () => { + const a = jest.fn(); + const b = jest.fn(); + onDataLifecycle('ohlcvPrepended', a); + onDataLifecycle('ohlcvPrepended', b); + notifyDataLifecycle('ohlcvPrepended'); + expect(a).toHaveBeenCalledTimes(1); + expect(b).toHaveBeenCalledTimes(1); + }); + + it('does not cross-fire between events', () => { + const listener = jest.fn(); + onDataLifecycle('ohlcvReset', listener); + notifyDataLifecycle('ohlcvPrepended'); + expect(listener).not.toHaveBeenCalled(); + }); + + it('unsubscribe removes the listener', () => { + const listener = jest.fn(); + const unsub = onDataLifecycle('visibleRangeChanged', listener); + unsub(); + notifyDataLifecycle('visibleRangeChanged'); + expect(listener).not.toHaveBeenCalled(); + }); + + it('reports listener errors to RN without stopping other listeners', () => { + const bridge = { postMessage: jest.fn() }; + window.ReactNativeWebView = bridge; + + const bad = jest.fn(() => { + throw new Error('boom'); + }); + const good = jest.fn(); + onDataLifecycle('ohlcvReset', bad); + onDataLifecycle('ohlcvReset', good); + + notifyDataLifecycle('ohlcvReset'); + + expect(good).toHaveBeenCalledTimes(1); + expect(bridge.postMessage).toHaveBeenCalledWith( + expect.stringContaining('"type":"ERROR"'), + ); + }); + + it('_resetDataLifecycleForTests clears all listeners', () => { + const listener = jest.fn(); + onDataLifecycle('ohlcvReset', listener); + onDataLifecycle('ohlcvPrepended', listener); + onDataLifecycle('visibleRangeChanged', listener); + _resetDataLifecycleForTests(); + notifyDataLifecycle('ohlcvReset'); + notifyDataLifecycle('ohlcvPrepended'); + notifyDataLifecycle('visibleRangeChanged'); + expect(listener).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/host.test.ts b/packages/advanced-chart-core/src/core/__tests__/host.test.ts new file mode 100644 index 00000000000..adb423624eb --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/host.test.ts @@ -0,0 +1,40 @@ +import { + _resetHostTransportForTests, + getHostTransport, + setHostTransport, +} from '../host.js'; +import type { ChartHostTransport } from '../host.js'; + +const fakeHost = (): ChartHostTransport => ({ + postMessage: jest.fn(), + subscribe: jest.fn(() => () => undefined), + getConfig: jest.fn(() => undefined), +}); + +describe('core/host', () => { + afterEach(() => { + _resetHostTransportForTests(); + delete window.ReactNativeWebView; + delete window.CONFIG; + }); + + it('defaults to the React Native adapter when none is injected', () => { + const bridge = { postMessage: jest.fn() }; + window.ReactNativeWebView = bridge; + getHostTransport().postMessage('payload'); + expect(bridge.postMessage).toHaveBeenCalledWith('payload'); + }); + + it('returns the injected transport after setHostTransport', () => { + const host = fakeHost(); + setHostTransport(host); + expect(getHostTransport()).toBe(host); + }); + + it('re-defaults after _resetHostTransportForTests', () => { + const host = fakeHost(); + setHostTransport(host); + _resetHostTransportForTests(); + expect(getHostTransport()).not.toBe(host); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/loadLibrary.test.ts b/packages/advanced-chart-core/src/core/__tests__/loadLibrary.test.ts new file mode 100644 index 00000000000..3b0f1fed368 --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/loadLibrary.test.ts @@ -0,0 +1,90 @@ +import { + loadTradingViewLibrary, + _resetLoadLibraryForTests, +} from '../loadLibrary.js'; +import { _resetStateForTests } from '../state.js'; + +type ScriptStub = { + type?: string; + src?: string; + onload?: () => void; + onerror?: () => void; +}; + +describe('core/loadLibrary', () => { + let script: ScriptStub; + let appendSpy: jest.SpyInstance; + + beforeEach(() => { + _resetStateForTests(); + _resetLoadLibraryForTests(); + delete window.ReactNativeWebView; + script = {}; + const createElementImpl = (tag: string): HTMLElement => { + if (tag === 'script') { + return script as unknown as HTMLScriptElement; + } + return {} as HTMLElement; + }; + jest + .spyOn(document, 'createElement') + .mockImplementation(createElementImpl as never); + appendSpy = jest + .spyOn(document.head, 'appendChild') + .mockImplementation(((node: Node) => node) as never); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('appends the charting_library.js script with the correct URL', async () => { + const promise = loadTradingViewLibrary('https://cdn.example.com/'); + expect(script.src).toBe('https://cdn.example.com/charting_library.js'); + expect(appendSpy).toHaveBeenCalledTimes(1); + + script.onload?.(); + expect(await promise).toBeUndefined(); + }); + + it('rejects when the script onerror fires', async () => { + const promise = loadTradingViewLibrary('https://cdn.example.com/'); + script.onerror?.(); + await expect(promise).rejects.toThrow( + /Failed to load TradingView library/u, + ); + }); + + it('resolves immediately on subsequent calls once loaded', async () => { + const first = loadTradingViewLibrary('https://cdn.example.com/'); + script.onload?.(); + await first; + + // Reset spies to confirm no second script tag is appended. + appendSpy.mockClear(); + await loadTradingViewLibrary('https://cdn.example.com/'); + expect(appendSpy).not.toHaveBeenCalled(); + }); + + it('second call before onload only appends once', async () => { + const first = loadTradingViewLibrary('https://cdn.example.com/'); + const second = loadTradingViewLibrary('https://cdn.example.com/'); + + expect(appendSpy).toHaveBeenCalledTimes(1); + expect(second).toBe(first); + + script.onload?.(); + await first; + await second; + }); + + it('rejects subsequent calls if the prior load errored', async () => { + const first = loadTradingViewLibrary('https://cdn.example.com/'); + script.onerror?.(); + await expect(first).rejects.toThrow(/Failed to load TradingView library/u); + + await expect( + loadTradingViewLibrary('https://cdn.example.com/'), + ).rejects.toThrow(/Failed to load TradingView library/u); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/resolution.test.ts b/packages/advanced-chart-core/src/core/__tests__/resolution.test.ts new file mode 100644 index 00000000000..9da10883eaa --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/resolution.test.ts @@ -0,0 +1,38 @@ +import { detectResolution, INTERVAL_MS_TO_TV } from '../resolution.js'; + +const bars = (intervals: number[]): { time: number }[] => { + const out: { time: number }[] = [{ time: 0 }]; + let time = 0; + for (const ms of intervals) { + time += ms; + out.push({ time }); + } + return out; +}; + +describe('detectResolution', () => { + it('returns default "5" for fewer than 2 bars', () => { + expect(detectResolution([])).toBe('5'); + expect(detectResolution([{ time: 0 }])).toBe('5'); + }); + + it.each(Object.entries(INTERVAL_MS_TO_TV))( + 'maps %s ms steps → %s', + (intervalMs, expected) => { + const data = bars(Array(5).fill(Number(intervalMs))); + expect(detectResolution(data)).toBe(expected); + }, + ); + + it('uses the median diff to ignore single-bar gaps', () => { + // 4× one-minute diffs + 1× ten-minute gap. Median = 60_000 → "1". + const data = bars([60_000, 60_000, 10 * 60_000, 60_000, 60_000]); + expect(detectResolution(data)).toBe('1'); + }); + + it('snaps to the closest defined interval', () => { + // 6.5 min between bars → closest mapped is 5min ("5") not 15min ("15"). + const data = bars([390_000, 390_000, 390_000]); + expect(detectResolution(data)).toBe('5'); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/state.test.ts b/packages/advanced-chart-core/src/core/__tests__/state.test.ts new file mode 100644 index 00000000000..ddf583d3da9 --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/state.test.ts @@ -0,0 +1,69 @@ +import { + _resetStateForTests, + getCurrentResolution, + getCurrentSymbol, + getLibraryError, + getTheme, + getWidget, + isChartReady, + isLibraryLoaded, + setChartReady, + setCurrentResolution, + setCurrentSymbol, + setLibraryError, + setLibraryLoaded, + setTheme, + setWidget, +} from '../state.js'; +import type { ChartTheme, TVChartingLibraryWidget } from '../types.js'; + +const stubWidget = {} as TVChartingLibraryWidget; +const stubTheme = { backgroundColor: 'rgb(0,0,0)' } as ChartTheme; + +describe('core/state', () => { + beforeEach(() => { + _resetStateForTests(); + }); + + it('defaults to unmounted state', () => { + expect(getWidget()).toBeNull(); + expect(isChartReady()).toBe(false); + expect(getCurrentSymbol()).toBe('ASSET'); + expect(getCurrentResolution()).toBe('5'); + expect(getTheme()).toBeNull(); + expect(isLibraryLoaded()).toBe(false); + expect(getLibraryError()).toBeNull(); + }); + + it('stores and returns the widget reference', () => { + setWidget(stubWidget); + expect(getWidget()).toBe(stubWidget); + setWidget(null); + expect(getWidget()).toBeNull(); + }); + + it('tracks chart-ready, symbol, resolution, theme, library state', () => { + setChartReady(true); + setCurrentSymbol('BTC/USD'); + setCurrentResolution('60'); + setTheme(stubTheme); + setLibraryLoaded(true); + setLibraryError('boom'); + + expect(isChartReady()).toBe(true); + expect(getCurrentSymbol()).toBe('BTC/USD'); + expect(getCurrentResolution()).toBe('60'); + expect(getTheme()).toBe(stubTheme); + expect(isLibraryLoaded()).toBe(true); + expect(getLibraryError()).toBe('boom'); + }); + + it('_resetStateForTests restores defaults', () => { + setChartReady(true); + setCurrentSymbol('FOO'); + _resetStateForTests(); + + expect(isChartReady()).toBe(false); + expect(getCurrentSymbol()).toBe('ASSET'); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/timeUtils.test.ts b/packages/advanced-chart-core/src/core/__tests__/timeUtils.test.ts new file mode 100644 index 00000000000..c97aebbacf6 --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/timeUtils.test.ts @@ -0,0 +1,56 @@ +import { + chartRawTimeToUnixMs, + getApproxBarDurationSec, + normalizeChartUnixSec, +} from '../timeUtils.js'; + +describe('normalizeChartUnixSec', () => { + it('returns null for non-finite input', () => { + expect(normalizeChartUnixSec(NaN)).toBeNull(); + expect(normalizeChartUnixSec(Infinity)).toBeNull(); + expect(normalizeChartUnixSec('not a number')).toBeNull(); + }); + + it('treats values ≥ 1e12 as milliseconds', () => { + expect(normalizeChartUnixSec(1_700_000_000_000)).toBe(1_700_000_000); + }); + + it('treats smaller values as seconds and floors', () => { + expect(normalizeChartUnixSec(1_700_000_000.7)).toBe(1_700_000_000); + }); +}); + +describe('chartRawTimeToUnixMs', () => { + it('returns null for non-finite input', () => { + expect(chartRawTimeToUnixMs(NaN)).toBeNull(); + }); + + it('passes ms-magnitude values through', () => { + expect(chartRawTimeToUnixMs(1_700_000_000_000)).toBe(1_700_000_000_000); + }); + + it('multiplies sub-1e12 values by 1000 (preserves fractional seconds)', () => { + expect(chartRawTimeToUnixMs(1_700_000_000.5)).toBe(1_700_000_000_500); + }); +}); + +describe('getApproxBarDurationSec', () => { + it('returns default 300 with fewer than 2 bars', () => { + expect(getApproxBarDurationSec([])).toBe(300); + expect(getApproxBarDurationSec([{ time: 0 }])).toBe(300); + }); + + it('returns the gap between the last two bars in seconds', () => { + expect( + getApproxBarDurationSec([ + { time: 0 }, + { time: 60_000 }, + { time: 120_000 }, + ]), + ).toBe(60); + }); + + it('clamps to minimum 60 seconds', () => { + expect(getApproxBarDurationSec([{ time: 0 }, { time: 30_000 }])).toBe(60); + }); +}); diff --git a/packages/advanced-chart-core/src/core/__tests__/timezone.test.ts b/packages/advanced-chart-core/src/core/__tests__/timezone.test.ts new file mode 100644 index 00000000000..b5f836c9c41 --- /dev/null +++ b/packages/advanced-chart-core/src/core/__tests__/timezone.test.ts @@ -0,0 +1,53 @@ +import { + CANONICAL_TO_TV, + resolveUserTimezone, + TV_SUPPORTED_TIMEZONES, +} from '../timezone.js'; + +const stubIntlTimezone = (zone: string | undefined): void => { + jest.spyOn(Intl, 'DateTimeFormat').mockImplementation( + () => + ({ + resolvedOptions: () => ({ timeZone: zone }) as ResolvedOptions, + }) as unknown as Intl.DateTimeFormat, + ); +}; + +type ResolvedOptions = { + timeZone: string | undefined; +}; + +describe('resolveUserTimezone', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('returns a TV-supported zone when Intl reports one directly', () => { + stubIntlTimezone('Europe/Paris'); + expect(resolveUserTimezone()).toBe('Europe/Paris'); + expect(TV_SUPPORTED_TIMEZONES).toContain('Europe/Paris'); + }); + + it('maps canonical aliases to TV legacy names', () => { + stubIntlTimezone('America/Denver'); + expect(resolveUserTimezone()).toBe(CANONICAL_TO_TV['America/Denver']); + expect(resolveUserTimezone()).toBe('US/Mountain'); + }); + + it('falls back to Etc/UTC when Intl returns an unsupported zone', () => { + stubIntlTimezone('Africa/Timbuktu'); // not in TV_SUPPORTED_TIMEZONES + expect(resolveUserTimezone()).toBe('Etc/UTC'); + }); + + it('falls back to Etc/UTC when Intl throws', () => { + jest.spyOn(Intl, 'DateTimeFormat').mockImplementation(() => { + throw new Error('Intl broken'); + }); + expect(resolveUserTimezone()).toBe('Etc/UTC'); + }); + + it('falls back to Etc/UTC when Intl reports an empty timezone', () => { + stubIntlTimezone(undefined); + expect(resolveUserTimezone()).toBe('Etc/UTC'); + }); +}); diff --git a/packages/advanced-chart-core/src/core/bootstrap.ts b/packages/advanced-chart-core/src/core/bootstrap.ts new file mode 100644 index 00000000000..4cb9c76c921 --- /dev/null +++ b/packages/advanced-chart-core/src/core/bootstrap.ts @@ -0,0 +1,230 @@ +// Entry orchestration. Called once from src/index.ts when the IIFE evaluates +// inside the WebView. +// +// Responsibilities (Phase 1 + 2): +// 1. Read window.CONFIG (must be inlined by AdvancedChartTemplate before this +// script runs). +// 2. Seed core state with the symbol / resolution / theme from CONFIG. +// 3. Wire the RN→WV bridge to the message dispatcher. +// 4. Register Phase 1 + 2 message handlers: +// SET_THEME_COLORS (Phase 1), SET_OHLCV_DATA, REALTIME_UPDATE, +// SET_CHART_TYPE (Phase 2). +// 5. Begin loading the TradingView library so it's ready when the first +// SET_OHLCV_DATA arrives. +// 6. On first SET_OHLCV_DATA: createChartWidget with the default datafeed, +// apply visual overrides, attach crosshair + visible-range listeners. + +import { + handleAddIndicator, + handleRemoveIndicator, + handleSetMAVisibility, +} from '../features/indicators/index.js'; +import { + attachLegendResizeListener, + setupLegendOverlay, +} from '../features/indicators/legend.js'; +import { handleSetSubPaneLayout } from '../features/indicators/subPane.js'; +import { + handleToggleVolume, + registerVolumeThemeSync, +} from '../features/volume/index.js'; +import { + attachCrosshairListener, + attachTapDismiss, +} from '../interaction/crosshair.js'; +import { attachVisibleRangeListeners } from '../interaction/visibleRange.js'; +import { + dispatchInboundMessage, + registerHandler, +} from '../messages/handler.js'; +import { registerFocusTimeOverlay } from '../overlays/focusTime/index.js'; +import { registerPositionLinesOverlay } from '../overlays/positionLines/index.js'; +import { slbScheduleInitialCentering } from '../overlays/socialLeaderboard/index.js'; +import { registerTradeMarkerPulseHandler } from '../overlays/tradeMarkers/animation.js'; +import { registerTradeMarkerOverlay } from '../overlays/tradeMarkers/index.js'; +import { attachMarkerHitTest } from '../overlays/tradeMarkers/markerHitTest.js'; +import { registerRnBackedPaginationHandler } from '../pagination/rnBacked.js'; +import { handleSetChartType } from '../widget/chartType.js'; +import { customDatafeed } from '../widget/datafeed.js'; +import { + createChartWidget, + scheduleChartLayoutSettledNotify, +} from '../widget/initChart.js'; +import { + handleRealtimeUpdate, + handleSetOHLCVData, + onFirstOhlcvData, +} from '../widget/ohlcvIngestion.js'; +import { advancedChartPriceFormatterFactory } from '../widget/priceFormatter.js'; +import { applyScaleLayout } from '../widget/scaleLayout.js'; +import { + applyThemeColors, + flushPendingTheme, + initThemeFromConfig, +} from '../widget/theme.js'; +import { applyVisualOverrides } from '../widget/visualOverrides.js'; +import { onFromRN, postToRN, reportErrorToRN } from './bridge.js'; +import { getHostTransport } from './host.js'; +import { loadTradingViewLibrary } from './loadLibrary.js'; +import { + getOhlcvData, + getVisibleFromMs, + getVisibleToMs, + setConfig, + setSubPaneHeightRatio, +} from './state.js'; +import { getApproxBarDurationSec } from './timeUtils.js'; +import type { ChartConfig } from './types.js'; + +/** + * When RN passes an explicit visible-range start (e.g. a specific period like + * 1D/1W/1M), build a `{ type: 'time-range', from, to }` timeframe so the + * initial view snaps to that window instead of defaulting to `Date.now()`. + * Padded by 2 bar durations so the last bar isn't glued to the right edge. + * Ported from chartLogic.js initChart's `tfOption` computation (~line 5284). + * + * @returns A `time-range` timeframe pinned to the requested window, or + * `undefined` when RN did not pass an explicit visible-range start. + */ +function buildInitialTimeframe(): + | { type: 'time-range'; from: number; to: number } + | undefined { + const visibleFromMs = getVisibleFromMs(); + if (visibleFromMs === null) { + return undefined; + } + const visibleToMs = getVisibleToMs() ?? Date.now(); + const initBarPadSec = getApproxBarDurationSec(getOhlcvData()) * 2; + return { + type: 'time-range', + from: Math.floor(visibleFromMs / 1000), + to: Math.ceil(visibleToMs / 1000) + initBarPadSec, + }; +} + +function readConfig(): ChartConfig { + const config = getHostTransport().getConfig(); + if (!config) { + throw new Error( + 'window.CONFIG is missing — AdvancedChartTemplate must inline ' + + 'CONFIG before chartLogic runs.', + ); + } + return config; +} + +/** + * Phase 1 + 2 bootstrap. Returns the resolved CONFIG so callers (and tests) + * can inspect what booted. Idempotent on its inbound subscription — the + * WebView is not expected to bootstrap twice. + * + * @returns The resolved chart configuration read from `window.CONFIG`. + */ +export function bootstrap(): ChartConfig { + const config = readConfig(); + setConfig(config); + + initThemeFromConfig(config.theme); + if (typeof config.subPaneHeightRatio === 'number') { + setSubPaneHeightRatio(config.subPaneHeightRatio); + } + + registerHandler('SET_THEME_COLORS', (payload) => { + applyThemeColors(payload); + }); + registerHandler('SET_OHLCV_DATA', (payload) => { + handleSetOHLCVData(payload); + }); + registerHandler('REALTIME_UPDATE', (payload) => { + handleRealtimeUpdate(payload); + }); + registerHandler('SET_CHART_TYPE', (payload) => { + handleSetChartType(payload); + }); + registerHandler('ADD_INDICATOR', (payload) => { + handleAddIndicator(payload, config); + }); + registerHandler('REMOVE_INDICATOR', (payload) => { + handleRemoveIndicator(payload); + }); + registerHandler('SET_MA_VISIBILITY', (payload) => { + handleSetMAVisibility(payload, config); + }); + registerHandler('TOGGLE_VOLUME', (payload) => { + handleToggleVolume(payload); + }); + registerHandler('SET_SUB_PANE_LAYOUT', (payload) => { + handleSetSubPaneLayout(payload); + }); + + registerTradeMarkerOverlay(); + registerTradeMarkerPulseHandler(); + registerFocusTimeOverlay(); + registerPositionLinesOverlay(); + registerRnBackedPaginationHandler(); + registerVolumeThemeSync(); + + onFromRN((message) => { + dispatchInboundMessage(message); + }); + + // Library load is fire-and-forget; the first-data handler awaits readiness + // again before constructing the widget, so this is purely a head-start. + loadTradingViewLibrary(config.libraryUrl).catch((error) => { + reportErrorToRN(error); + }); + + onFirstOhlcvData(() => { + loadTradingViewLibrary(config.libraryUrl) + .then(() => { + return createChartWidget(config, { + datafeed: customDatafeed, + customFormatters: { + priceFormatterFactory: advancedChartPriceFormatterFactory, + }, + timeframe: buildInitialTimeframe(), + onReady: (widget) => { + try { + flushPendingTheme(); + applyScaleLayout(); + applyVisualOverrides(config.visualOverrides); + setupLegendOverlay(config.legendOverlay); + const chart = widget.activeChart(); + // Match legacy onChartReady: when no explicit visible range + // was passed, pin a 2-bar gap on the right. TV's default is + // wider, leaving the chart visibly offset left. + if (getVisibleFromMs() === null) { + try { + chart.getTimeScale().setRightOffset(2); + } catch (rightOffsetError) { + reportErrorToRN(rightOffsetError); + } + } + attachCrosshairListener(chart); + attachTapDismiss(widget); + attachMarkerHitTest(widget, chart); + attachVisibleRangeListeners(chart); + chart + .selection() + .onChanged() + .subscribe(null, () => { + chart.selection().clear(); + }); + attachLegendResizeListener(widget); + slbScheduleInitialCentering(); + scheduleChartLayoutSettledNotify(); + } catch (error) { + reportErrorToRN(error); + } + }, + }); + }) + .catch((error) => { + reportErrorToRN(error); + }); + }); + + postToRN('DEBUG', { message: 'modular-bootstrap-ready' }); + + return config; +} diff --git a/packages/advanced-chart-core/src/core/bridge.ts b/packages/advanced-chart-core/src/core/bridge.ts new file mode 100644 index 00000000000..405463ab6fb --- /dev/null +++ b/packages/advanced-chart-core/src/core/bridge.ts @@ -0,0 +1,104 @@ +// Typed bridge between the WebView IIFE and its host. +// +// Owns the platform-agnostic parts of host communication — JSON framing, +// inbound parsing, and message validation — and delegates the actual +// transport (outbound delivery, inbound subscription, origin filtering) to +// the injected host adapter (see core/host.ts). Preserves the same +// window.ReactNativeWebView.postMessage(...) call shape via the default RN +// adapter, so the RN-side parseWebViewMessage decodes messages unchanged. + +import type { + InboundMessage, + OutboundMessageType, + OutboundPayloads, +} from '../messages/contract.js'; +import { getHostTransport } from './host.js'; + +export function safeStringify(value: unknown): string { + try { + return JSON.stringify(value) ?? 'Unknown error'; + } catch { + return String(value); + } +} + +/** + * Posts a typed message to the host via the active transport. Equivalent to + * legacy `sendToReactNative(type, payload)` at chartLogic.js line ~98. + * Silently no-ops when the host transport is unavailable (e.g. during unit + * tests in a jsdom environment without the RN bridge stub). + * + * @param type - The outbound message type tag. + * @param payload - The payload associated with the message type. + */ +export function postToRN( + type: Type, + payload: OutboundPayloads[Type], +): void { + try { + getHostTransport().postMessage(JSON.stringify({ type, payload })); + } catch { + // postMessage / JSON.stringify failure: nothing to do — the WebView + // cannot inform the host of its own bridge failure. + } +} + +/** + * Reports a runtime error to React Native via the ERROR channel. Matches the + * legacy `sendToReactNative('ERROR', { message })` pattern used throughout + * chartLogic.js. + * + * @param error - The error (or arbitrary thrown value) to report. + */ +export function reportErrorToRN(error: unknown): void { + let message: string; + if (error instanceof Error) { + message = error.message; + } else if (typeof error === 'string') { + message = error; + } else { + message = safeStringify(error); + } + postToRN('ERROR', { message }); +} + +export type InboundMessageHandler = (message: InboundMessage) => void; + +/** + * Registers a single inbound listener. The host posts JSON strings; the + * active transport delivers each raw payload (after any transport-level + * origin filtering) and this function parses + validates it before forwarding + * a well-formed message to the handler. + * + * The returned function unsubscribes — useful for tests; the real bundle + * subscribes once at bootstrap and never unsubscribes. + * + * @param handler - Callback invoked with each well-formed inbound message. + * @returns A function that removes the registered listeners. + */ +export function onFromRN(handler: InboundMessageHandler): () => void { + return getHostTransport().subscribe((raw: unknown): void => { + let parsed: unknown; + try { + parsed = typeof raw === 'string' ? JSON.parse(raw) : raw; + } catch (parseError) { + reportErrorToRN(parseError); + return; + } + if (!parsed || typeof parsed !== 'object') { + return; + } + const candidate = parsed as { type?: unknown }; + if (typeof candidate.type !== 'string') { + return; + } + // Trusting the type narrowing here is fine because messages/handler.ts + // re-validates via a switch on candidate.type before dispatching to a + // typed handler. Phase 1 only routes SET_THEME_COLORS, but the listener + // forwards every well-formed message so the handler can decide. + handler(parsed as InboundMessage); + }); +} + +/** Re-export for callers that want the type tag union. */ +export type { InboundMessageType } from '../messages/contract.js'; diff --git a/packages/advanced-chart-core/src/core/dataLifecycle.ts b/packages/advanced-chart-core/src/core/dataLifecycle.ts new file mode 100644 index 00000000000..ce228d6ff08 --- /dev/null +++ b/packages/advanced-chart-core/src/core/dataLifecycle.ts @@ -0,0 +1,59 @@ +// Lightweight event bus for data lifecycle events overlays need to react to. +// +// The widget modules (ohlcvIngestion, pagination, visibleRange) publish +// events after they mutate the OHLCV series or the visible range; +// overlay modules (tradeMarkers, positionLines) subscribe and re-place +// their shapes. Keeps overlays decoupled from widget/* — overlays never +// import from widget/*, matching the ESLint `no-restricted-paths` +// direction described in the plan. +// +// The events are intentionally void — subscribers read whatever state +// they need from core/state.ts. Errors inside a subscriber are logged +// to RN so a broken overlay doesn't take the widget down with it. + +import { reportErrorToRN } from './bridge.js'; + +export type DataLifecycleEvent = + | 'ohlcvReset' + | 'ohlcvPrepended' + | 'visibleRangeChanged'; + +type Listener = () => void; + +const listeners: Record = { + ohlcvReset: [], + ohlcvPrepended: [], + visibleRangeChanged: [], +}; + +export function onDataLifecycle( + event: DataLifecycleEvent, + listener: Listener, +): () => void { + listeners[event].push(listener); + return () => { + const bucket = listeners[event]; + const idx = bucket.indexOf(listener); + if (idx !== -1) { + bucket.splice(idx, 1); + } + }; +} + +export function notifyDataLifecycle(event: DataLifecycleEvent): void { + const bucket = listeners[event]; + for (const listener of bucket) { + try { + listener(); + } catch (error) { + reportErrorToRN(error); + } + } +} + +/** Test-only: clear every listener across every event. */ +export function _resetDataLifecycleForTests(): void { + listeners.ohlcvReset = []; + listeners.ohlcvPrepended = []; + listeners.visibleRangeChanged = []; +} diff --git a/packages/advanced-chart-core/src/core/host.ts b/packages/advanced-chart-core/src/core/host.ts new file mode 100644 index 00000000000..4fc85ba09fc --- /dev/null +++ b/packages/advanced-chart-core/src/core/host.ts @@ -0,0 +1,66 @@ +// Platform host transport layer. +// +// Abstracts the *platform-specific* transport (how the WebView talks to its +// host and where it reads its inlined CONFIG) behind a single injectable +// interface. The engine's message bridge (core/bridge.ts) and config accessor +// (core/state.ts getConfig) depend on this interface instead of naming a +// concrete global, so the same engine can run inside a React Native WebView +// or a browser extension iframe. +// +// Adapters live in src/platform/*. The React Native adapter is the default so +// that existing consumers (and the mobile IIFE) keep their exact behavior +// without any wiring. + +import { createReactNativeHost } from '../platform/reactNativeHost.js'; +import type { ChartConfig } from './types.js'; + +/** Callback invoked with each raw inbound payload delivered by the host. */ +export type InboundTransportListener = (raw: unknown) => void; + +/** + * The platform transport contract. An adapter owns the three things that + * differ between hosts: how outbound messages are delivered, how inbound + * messages are received (including any origin filtering), and where the + * inlined chart CONFIG comes from. + */ +export type ChartHostTransport = { + /** Deliver a serialized outbound message to the host. */ + postMessage(serialized: string): void; + /** + * Subscribe to raw inbound messages from the host. The adapter is + * responsible for any transport-level filtering (e.g. origin checks). The + * returned function unsubscribes. + */ + subscribe(onMessage: InboundTransportListener): () => void; + /** Return the inlined chart configuration, or `undefined` when absent. */ + getConfig(): ChartConfig | undefined; +}; + +let activeHost: ChartHostTransport | null = null; + +/** + * Injects the host transport the engine should use. The mobile IIFE and the + * extension entry call this before bootstrap; tests may call it to provide a + * fake transport. + * + * @param host - The transport adapter to activate. + */ +export function setHostTransport(host: ChartHostTransport): void { + activeHost = host; +} + +/** + * Returns the active host transport, lazily defaulting to the React Native + * adapter so untouched consumers keep their current behavior. + * + * @returns The active host transport. + */ +export function getHostTransport(): ChartHostTransport { + activeHost ??= createReactNativeHost(); + return activeHost; +} + +/** Test-only: clear the injected host so the next access re-defaults. */ +export function _resetHostTransportForTests(): void { + activeHost = null; +} diff --git a/packages/advanced-chart-core/src/core/loadLibrary.ts b/packages/advanced-chart-core/src/core/loadLibrary.ts new file mode 100644 index 00000000000..1597e75f6eb --- /dev/null +++ b/packages/advanced-chart-core/src/core/loadLibrary.ts @@ -0,0 +1,68 @@ +// Loads the TradingView Advanced Charts library from window.CONFIG.libraryUrl +// by injecting a