From 9d9c076b328e1398a76926cced0866872d91eb16 Mon Sep 17 00:00:00 2001 From: sahar-fehri Date: Mon, 3 Aug 2026 13:56:41 +0100 Subject: [PATCH 1/8] chore: create advanced charts core package --- .github/CODEOWNERS | 4 + codeowners.ts | 5 + packages/advanced-chart-core/CHANGELOG.md | 14 + packages/advanced-chart-core/LICENSE | 6 + packages/advanced-chart-core/LICENSE.APACHE2 | 201 ++++++ packages/advanced-chart-core/LICENSE.MIT | 21 + packages/advanced-chart-core/README.md | 15 + packages/advanced-chart-core/package.json | 69 ++ .../advanced-chart-core/src/core/bootstrap.ts | 217 +++++++ .../advanced-chart-core/src/core/bridge.ts | 115 ++++ .../src/core/dataLifecycle.ts | 57 ++ .../src/core/loadLibrary.ts | 61 ++ .../src/core/resolution.ts | 56 ++ .../advanced-chart-core/src/core/state.ts | 421 +++++++++++++ .../advanced-chart-core/src/core/timeUtils.ts | 58 ++ .../advanced-chart-core/src/core/timezone.ts | 130 ++++ .../advanced-chart-core/src/core/types.ts | 394 ++++++++++++ .../src/features/indicators/index.ts | 201 ++++++ .../src/features/indicators/legend.ts | 587 ++++++++++++++++++ .../src/features/indicators/resize.ts | 27 + .../src/features/indicators/studies.ts | 171 +++++ .../src/features/indicators/subPane.ts | 81 +++ .../src/features/volume/index.ts | 151 +++++ packages/advanced-chart-core/src/index.ts | 18 + .../src/interaction/crosshair.ts | 147 +++++ .../src/interaction/visibleRange.ts | 94 +++ .../src/messages/contract.ts | 342 ++++++++++ .../src/messages/handler.ts | 50 ++ .../src/overlays/focusTime/index.ts | 166 +++++ .../src/overlays/positionLines/index.ts | 209 +++++++ .../src/overlays/positionLines/state.ts | 34 + .../src/overlays/socialLeaderboard/index.ts | 229 +++++++ .../src/overlays/tradeMarkers/animation.ts | 113 ++++ .../src/overlays/tradeMarkers/index.ts | 365 +++++++++++ .../overlays/tradeMarkers/markerHitTest.ts | 307 +++++++++ .../src/overlays/tradeMarkers/state.ts | 93 +++ .../src/pagination/priceApi.ts | 142 +++++ .../src/pagination/rnBacked.ts | 137 ++++ .../src/widget/chartType.ts | 41 ++ .../src/widget/datafeed.ts | 255 ++++++++ .../src/widget/externalLinkBridge.ts | 138 ++++ .../src/widget/initChart.ts | 283 +++++++++ .../src/widget/ohlcvIngestion.ts | 283 +++++++++ .../src/widget/priceFormatter.ts | 142 +++++ .../src/widget/scaleLayout.ts | 89 +++ .../advanced-chart-core/src/widget/theme.ts | 264 ++++++++ .../src/widget/tvDomHelpers.ts | 50 ++ .../src/widget/visualOverrides.ts | 65 ++ .../advanced-chart-core/tsconfig.build.json | 14 + packages/advanced-chart-core/tsconfig.json | 12 + yarn.lock | 15 + 51 files changed, 7159 insertions(+) create mode 100644 packages/advanced-chart-core/CHANGELOG.md create mode 100644 packages/advanced-chart-core/LICENSE create mode 100644 packages/advanced-chart-core/LICENSE.APACHE2 create mode 100644 packages/advanced-chart-core/LICENSE.MIT create mode 100644 packages/advanced-chart-core/README.md create mode 100644 packages/advanced-chart-core/package.json create mode 100644 packages/advanced-chart-core/src/core/bootstrap.ts create mode 100644 packages/advanced-chart-core/src/core/bridge.ts create mode 100644 packages/advanced-chart-core/src/core/dataLifecycle.ts create mode 100644 packages/advanced-chart-core/src/core/loadLibrary.ts create mode 100644 packages/advanced-chart-core/src/core/resolution.ts create mode 100644 packages/advanced-chart-core/src/core/state.ts create mode 100644 packages/advanced-chart-core/src/core/timeUtils.ts create mode 100644 packages/advanced-chart-core/src/core/timezone.ts create mode 100644 packages/advanced-chart-core/src/core/types.ts create mode 100644 packages/advanced-chart-core/src/features/indicators/index.ts create mode 100644 packages/advanced-chart-core/src/features/indicators/legend.ts create mode 100644 packages/advanced-chart-core/src/features/indicators/resize.ts create mode 100644 packages/advanced-chart-core/src/features/indicators/studies.ts create mode 100644 packages/advanced-chart-core/src/features/indicators/subPane.ts create mode 100644 packages/advanced-chart-core/src/features/volume/index.ts create mode 100644 packages/advanced-chart-core/src/index.ts create mode 100644 packages/advanced-chart-core/src/interaction/crosshair.ts create mode 100644 packages/advanced-chart-core/src/interaction/visibleRange.ts create mode 100644 packages/advanced-chart-core/src/messages/contract.ts create mode 100644 packages/advanced-chart-core/src/messages/handler.ts create mode 100644 packages/advanced-chart-core/src/overlays/focusTime/index.ts create mode 100644 packages/advanced-chart-core/src/overlays/positionLines/index.ts create mode 100644 packages/advanced-chart-core/src/overlays/positionLines/state.ts create mode 100644 packages/advanced-chart-core/src/overlays/socialLeaderboard/index.ts create mode 100644 packages/advanced-chart-core/src/overlays/tradeMarkers/animation.ts create mode 100644 packages/advanced-chart-core/src/overlays/tradeMarkers/index.ts create mode 100644 packages/advanced-chart-core/src/overlays/tradeMarkers/markerHitTest.ts create mode 100644 packages/advanced-chart-core/src/overlays/tradeMarkers/state.ts create mode 100644 packages/advanced-chart-core/src/pagination/priceApi.ts create mode 100644 packages/advanced-chart-core/src/pagination/rnBacked.ts create mode 100644 packages/advanced-chart-core/src/widget/chartType.ts create mode 100644 packages/advanced-chart-core/src/widget/datafeed.ts create mode 100644 packages/advanced-chart-core/src/widget/externalLinkBridge.ts create mode 100644 packages/advanced-chart-core/src/widget/initChart.ts create mode 100644 packages/advanced-chart-core/src/widget/ohlcvIngestion.ts create mode 100644 packages/advanced-chart-core/src/widget/priceFormatter.ts create mode 100644 packages/advanced-chart-core/src/widget/scaleLayout.ts create mode 100644 packages/advanced-chart-core/src/widget/theme.ts create mode 100644 packages/advanced-chart-core/src/widget/tvDomHelpers.ts create mode 100644 packages/advanced-chart-core/src/widget/visualOverrides.ts create mode 100644 packages/advanced-chart-core/tsconfig.build.json create mode 100644 packages/advanced-chart-core/tsconfig.json 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/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/packages/advanced-chart-core/CHANGELOG.md b/packages/advanced-chart-core/CHANGELOG.md new file mode 100644 index 00000000000..c760539d1c0 --- /dev/null +++ b/packages/advanced-chart-core/CHANGELOG.md @@ -0,0 +1,14 @@ +# 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` + +[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/package.json b/packages/advanced-chart-core/package.json new file mode 100644 index 00000000000..343a5f9c257 --- /dev/null +++ b/packages/advanced-chart-core/package.json @@ -0,0 +1,69 @@ +{ + "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", + "jest": "^30.4.2", + "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/core/bootstrap.ts b/packages/advanced-chart-core/src/core/bootstrap.ts new file mode 100644 index 00000000000..1c5411eb022 --- /dev/null +++ b/packages/advanced-chart-core/src/core/bootstrap.ts @@ -0,0 +1,217 @@ +// 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 { onFromRN, postToRN, reportErrorToRN } from './bridge'; +import { loadTradingViewLibrary } from './loadLibrary'; +import { dispatchInboundMessage, registerHandler } from '../messages/handler'; +import { + applyThemeColors, + flushPendingTheme, + initThemeFromConfig, +} from '../widget/theme'; +import { customDatafeed } from '../widget/datafeed'; +import { advancedChartPriceFormatterFactory } from '../widget/priceFormatter'; +import { getApproxBarDurationSec } from './timeUtils'; +import { + handleRealtimeUpdate, + handleSetOHLCVData, + onFirstOhlcvData, +} from '../widget/ohlcvIngestion'; +import { handleSetChartType } from '../widget/chartType'; +import { applyVisualOverrides } from '../widget/visualOverrides'; +import { + createChartWidget, + scheduleChartLayoutSettledNotify, +} from '../widget/initChart'; +import { + attachCrosshairListener, + attachTapDismiss, +} from '../interaction/crosshair'; +import { attachVisibleRangeListeners } from '../interaction/visibleRange'; +import { applyScaleLayout } from '../widget/scaleLayout'; +import { + handleAddIndicator, + handleRemoveIndicator, + handleSetMAVisibility, +} from '../features/indicators'; +import { handleSetSubPaneLayout } from '../features/indicators/subPane'; +import { + attachLegendResizeListener, + setupLegendOverlay, +} from '../features/indicators/legend'; +import { + handleToggleVolume, + registerVolumeThemeSync, +} from '../features/volume'; +import { registerTradeMarkerOverlay } from '../overlays/tradeMarkers'; +import { registerTradeMarkerPulseHandler } from '../overlays/tradeMarkers/animation'; +import { attachMarkerHitTest } from '../overlays/tradeMarkers/markerHitTest'; +import { registerFocusTimeOverlay } from '../overlays/focusTime'; +import { registerPositionLinesOverlay } from '../overlays/positionLines'; +import { slbScheduleInitialCentering } from '../overlays/socialLeaderboard'; +import { registerRnBackedPaginationHandler } from '../pagination/rnBacked'; +import { + getOhlcvData, + getVisibleFromMs, + getVisibleToMs, + setSubPaneHeightRatio, +} from './state'; +import type { ChartConfig } from './types'; + +/** + * 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). + */ +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. + */ +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(() => { + 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..0c2c76972d6 --- /dev/null +++ b/packages/advanced-chart-core/src/core/bridge.ts @@ -0,0 +1,115 @@ +// 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'; + +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). + */ +export function postToRN( + type: T, + payload: OutboundPayloads[T], +): 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. + */ +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. + */ +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.origin; + 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'; 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..1794960df10 --- /dev/null +++ b/packages/advanced-chart-core/src/core/dataLifecycle.ts @@ -0,0 +1,57 @@ +// 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'; + +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..83d34351522 --- /dev/null +++ b/packages/advanced-chart-core/src/core/loadLibrary.ts @@ -0,0 +1,61 @@ +// Loads the TradingView Advanced Charts library from window.CONFIG.libraryUrl +// by injecting a