diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index c795476942f..0c5b5b4f45b 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -26,6 +26,7 @@ /packages/assets-controllers @MetaMask/metamask-assets /packages/network-enablement-controller @MetaMask/metamask-assets /packages/assets-controller @MetaMask/metamask-assets +/packages/advanced-chart-core @MetaMask/metamask-assets ## Confirmations Team /packages/address-book-controller @MetaMask/confirmations @@ -184,6 +185,9 @@ /packages/approval-controller/package.json @MetaMask/confirmations @MetaMask/core-platform /packages/approval-controller/CHANGELOG.md @MetaMask/confirmations @MetaMask/core-platform /packages/approval-controller/tsconfig.* @MetaMask/confirmations @MetaMask/core-platform +/packages/advanced-chart-core/package.json @MetaMask/metamask-assets @MetaMask/core-platform +/packages/advanced-chart-core/CHANGELOG.md @MetaMask/metamask-assets @MetaMask/core-platform +/packages/advanced-chart-core/tsconfig.* @MetaMask/metamask-assets @MetaMask/core-platform /packages/assets-controllers/package.json @MetaMask/metamask-assets @MetaMask/core-platform /packages/assets-controllers/CHANGELOG.md @MetaMask/metamask-assets @MetaMask/core-platform /packages/assets-controllers/tsconfig.* @MetaMask/metamask-assets @MetaMask/core-platform diff --git a/README.md b/README.md index 733f6c8b295..151945cd99d 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ yarn skills --reset # clear saved local selection - [`@metamask/account-tree-controller`](packages/account-tree-controller) - [`@metamask/accounts-controller`](packages/accounts-controller) - [`@metamask/address-book-controller`](packages/address-book-controller) +- [`@metamask/advanced-chart-core`](packages/advanced-chart-core) - [`@metamask/ai-controllers`](packages/ai-controllers) - [`@metamask/analytics-controller`](packages/analytics-controller) - [`@metamask/analytics-data-regulation-controller`](packages/analytics-data-regulation-controller) @@ -149,6 +150,7 @@ linkStyle default opacity:0.5 account_tree_controller(["@metamask/account-tree-controller"]); accounts_controller(["@metamask/accounts-controller"]); address_book_controller(["@metamask/address-book-controller"]); + advanced_chart_core(["@metamask/advanced-chart-core"]); ai_controllers(["@metamask/ai-controllers"]); analytics_controller(["@metamask/analytics-controller"]); analytics_data_regulation_controller(["@metamask/analytics-data-regulation-controller"]); diff --git a/codeowners.ts b/codeowners.ts index db72782dc89..85c8e03789c 100644 --- a/codeowners.ts +++ b/codeowners.ts @@ -59,6 +59,9 @@ const PACKAGES: Record = { teams: ['@MetaMask/confirmations'], initializationPath: 'approval-controller', }, + 'advanced-chart-core': { + teams: ['@MetaMask/metamask-assets'], + }, 'assets-controller': { teams: ['@MetaMask/metamask-assets'], }, @@ -425,6 +428,7 @@ function buildTeamSections(): CodeownersSection[] { buildRuleForPackage('assets-controllers'), buildRuleForPackage('network-enablement-controller'), buildRuleForPackage('assets-controller'), + buildRuleForPackage('advanced-chart-core'), ], }, { @@ -638,6 +642,7 @@ function buildPackageReleaseSection(): CodeownersSection { 'announcement-controller', 'client-utils', 'approval-controller', + 'advanced-chart-core', 'assets-controllers', 'assets-controller', 'config-registry-controller', diff --git a/eslint.config.mjs b/eslint.config.mjs index faf5e8039aa..3f92c8e0bb0 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -314,6 +314,17 @@ const config = createConfig([ 'no-restricted-globals': 'off', }, }, + { + // `@metamask/advanced-chart-core` is the TradingView Advanced Charts engine + // that runs inside a WebView/iframe, so it legitimately references browser + // globals (`window`, `document`, `requestAnimationFrame`). + // TODO: Introduce a platform transport seam so these globals are injected + // rather than referenced directly. + files: ['packages/advanced-chart-core/src/**/*.ts'], + rules: { + 'no-restricted-globals': 'off', + }, + }, { files: [ 'packages/wallet-cli/src/**/*.test.{js,ts}', diff --git a/packages/advanced-chart-core/CHANGELOG.md b/packages/advanced-chart-core/CHANGELOG.md new file mode 100644 index 00000000000..5ac8b8a731e --- /dev/null +++ b/packages/advanced-chart-core/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Initial release: platform-agnostic TradingView Advanced Charts WebView engine copied verbatim from `metamask-mobile`'s `AdvancedChart/webview/src` + +### Changed + +- Conform the vendored WebView engine to the `core` monorepo lint conventions without altering its runtime behavior ([#9762](https://github.com/MetaMask/core/pull/9762)) + - Applies core naming, JSDoc, and code-quality rules in source, with narrowly-scoped rule allowances only for browser globals and external contract identifiers. + +### Fixed + +- Correct barrel imports that resolved to package directories so the compiled output loads the intended `index` modules ([#9762](https://github.com/MetaMask/core/pull/9762)) + +[Unreleased]: https://github.com/MetaMask/core/ diff --git a/packages/advanced-chart-core/LICENSE b/packages/advanced-chart-core/LICENSE new file mode 100644 index 00000000000..2bf58141733 --- /dev/null +++ b/packages/advanced-chart-core/LICENSE @@ -0,0 +1,6 @@ +This project is licensed under either of + + * MIT license ([LICENSE.MIT](LICENSE.MIT)) + * Apache License, Version 2.0 ([LICENSE.APACHE2](LICENSE.APACHE2)) + +at your option. \ No newline at end of file diff --git a/packages/advanced-chart-core/LICENSE.APACHE2 b/packages/advanced-chart-core/LICENSE.APACHE2 new file mode 100644 index 00000000000..18002eac9ae --- /dev/null +++ b/packages/advanced-chart-core/LICENSE.APACHE2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 MetaMask + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/packages/advanced-chart-core/LICENSE.MIT b/packages/advanced-chart-core/LICENSE.MIT new file mode 100644 index 00000000000..e0278643409 --- /dev/null +++ b/packages/advanced-chart-core/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 MetaMask + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/advanced-chart-core/README.md b/packages/advanced-chart-core/README.md new file mode 100644 index 00000000000..0f06894eb98 --- /dev/null +++ b/packages/advanced-chart-core/README.md @@ -0,0 +1,15 @@ +# `@metamask/advanced-chart-core` + +Platform-agnostic TradingView Advanced Charts WebView engine shared across MetaMask clients + +## Installation + +`yarn add @metamask/advanced-chart-core` + +or + +`npm install @metamask/advanced-chart-core` + +## Contributing + +This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme). diff --git a/packages/advanced-chart-core/jest.config.js b/packages/advanced-chart-core/jest.config.js new file mode 100644 index 00000000000..28a6799fc45 --- /dev/null +++ b/packages/advanced-chart-core/jest.config.js @@ -0,0 +1,26 @@ +/* + * For a detailed explanation regarding each configuration property and type check, visit: + * https://jestjs.io/docs/configuration + */ + +const merge = require('deepmerge'); +const path = require('path'); + +const baseConfig = require('../../jest.config.packages'); + +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 new file mode 100644 index 00000000000..87be663cd5c --- /dev/null +++ b/packages/advanced-chart-core/package.json @@ -0,0 +1,71 @@ +{ + "name": "@metamask/advanced-chart-core", + "version": "0.0.0", + "description": "Platform-agnostic TradingView Advanced Charts WebView engine shared across MetaMask clients", + "keywords": [ + "Ethereum", + "MetaMask" + ], + "homepage": "https://github.com/MetaMask/core/tree/main/packages/advanced-chart-core#readme", + "bugs": { + "url": "https://github.com/MetaMask/core/issues" + }, + "license": "(MIT OR Apache-2.0)", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/core.git" + }, + "files": [ + "dist/" + ], + "sideEffects": false, + "main": "./dist/index.cjs", + "types": "./dist/index.d.cts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "scripts": { + "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", + "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:docs": "typedoc", + "changelog:update": "../../scripts/update-changelog.sh @metamask/advanced-chart-core", + "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", + "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", + "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache", + "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose", + "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" + }, + "devDependencies": { + "@metamask/auto-changelog": "^6.1.0", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^30.0.0", + "deepmerge": "^4.2.2", + "jest": "^30.4.2", + "jest-environment-jsdom": "^30.4.1", + "ts-jest": "^29.4.11", + "tsx": "^4.20.5", + "typedoc": "^0.25.13", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.18 || >=20" + } +} diff --git a/packages/advanced-chart-core/src/__tests__/index.test.ts b/packages/advanced-chart-core/src/__tests__/index.test.ts new file mode 100644 index 00000000000..ac36b9a2f4b --- /dev/null +++ b/packages/advanced-chart-core/src/__tests__/index.test.ts @@ -0,0 +1,80 @@ +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'; + +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__/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..a82305be3e1 --- /dev/null +++ b/packages/advanced-chart-core/src/core/bootstrap.ts @@ -0,0 +1,227 @@ +// 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 { loadTradingViewLibrary } from './loadLibrary.js'; +import { + getOhlcvData, + getVisibleFromMs, + getVisibleToMs, + 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 = window.CONFIG; + 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(); + + 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..7b1a93ea913 --- /dev/null +++ b/packages/advanced-chart-core/src/core/bridge.ts @@ -0,0 +1,123 @@ +// Typed bridge between the WebView IIFE and React Native. +// +// Wraps the same window.ReactNativeWebView.postMessage(...) call shape that +// legacy chartLogic.js's sendToReactNative() uses, so the RN-side +// parseWebViewMessage in AdvancedChart.types.ts decodes our messages without +// any change to its consumers. + +import type { + InboundMessage, + OutboundMessageType, + OutboundPayloads, +} from '../messages/contract.js'; + +export function safeStringify(value: unknown): string { + try { + return JSON.stringify(value) ?? 'Unknown error'; + } catch { + return String(value); + } +} + +/** + * Posts a typed message to React Native via window.ReactNativeWebView. + * Equivalent to legacy `sendToReactNative(type, payload)` at chartLogic.js + * line ~98. Silently no-ops when window.ReactNativeWebView is absent (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 { + const bridge = window.ReactNativeWebView; + if (!bridge) { + return; + } + try { + bridge.postMessage(JSON.stringify({ type, payload })); + } catch { + // postMessage / JSON.stringify failure: nothing to do — the WebView + // cannot inform RN 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. React Native posts JSON strings via + * webView.postMessage; the WebView receives them on window 'message' on iOS + * and document 'message' on Android (see chartLogic.js line ~400). We + * subscribe to both so consumers don't have to. + * + * 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 { + const dispatch = (event: MessageEvent): void => { + // RN WebView inline HTML: native bridge messages arrive with an empty + // or "null" origin. Reject messages from real web origins. + const { origin } = event; + if (origin && origin !== 'null' && !origin.startsWith('file:')) { + return; + } + + let parsed: unknown; + try { + parsed = + typeof event.data === 'string' ? JSON.parse(event.data) : event.data; + } 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); + }; + + // iOS posts arrive on window; Android posts arrive on document. Subscribe + // to both to match legacy chartLogic.js handleMessage wiring. + window.addEventListener('message', dispatch as EventListener); + document.addEventListener('message', dispatch as EventListener); + + return () => { + window.removeEventListener('message', dispatch as EventListener); + document.removeEventListener('message', dispatch as EventListener); + }; +} + +/** 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/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