diff --git a/.eslintignore b/.eslintignore index 517b6298d6..570bf43335 100644 --- a/.eslintignore +++ b/.eslintignore @@ -13,3 +13,6 @@ /website/docs/api/** /website/versioned_docs/**/api/** /website/build/** + +/plugin-examples +/packages/create-lwc-plugin diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 0584405a63..87c6a17013 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -36,6 +36,15 @@ jobs: - name: Build documentation website working-directory: ./website run: npm run build + - name: Install plugin example dependencies + working-directory: ./plugin-examples + run: npm install + - name: Build plugin examples website + working-directory: ./plugin-examples + run: npm run build:examples:site + - name: Build plugin examples website + working-directory: ./plugin-examples + run: npm run build:examples:site - name: Deploy uses: peaceiris/actions-gh-pages@v3 diff --git a/packages/create-lwc-plugin/.gitignore b/packages/create-lwc-plugin/.gitignore new file mode 100644 index 0000000000..76add878f8 --- /dev/null +++ b/packages/create-lwc-plugin/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist \ No newline at end of file diff --git a/packages/create-lwc-plugin/BUILDING.md b/packages/create-lwc-plugin/BUILDING.md new file mode 100644 index 0000000000..cdb0d7209a --- /dev/null +++ b/packages/create-lwc-plugin/BUILDING.md @@ -0,0 +1,46 @@ +# Local Development of the create-lwc-plugin + +The minimal supported version of [NodeJS](https://nodejs.org/) for development is 18. + +1. Install the dependencies + + ```shell + npm install + ``` + +2. Create a development stub + + ```shell + npm run dev + ``` + +3. Running the CLI locally + + ```shell + node index.js + ``` + +## Publishing new version + +1. Install the dependencies + + ```shell + npm install + ``` + +2. Bump the version number in the `package.json` +3. Build the package + + ```shell + npm run prepublishOnly + ``` + +4. Run `npx publint@latest` and ensure that there aren't any issues with the generated `package.json`. +5. Publish the package + + ```shell + npm publish + ``` + +Hint: append `--dry-run` to the end of the publish command to see the results of +the publish command without actually uploading the package to NPM. diff --git a/packages/create-lwc-plugin/LICENSE b/packages/create-lwc-plugin/LICENSE new file mode 100644 index 0000000000..4011352503 --- /dev/null +++ b/packages/create-lwc-plugin/LICENSE @@ -0,0 +1,304 @@ +# create-lwc-plugin license + +create-lwc-plugin is released under the Apache license: + + 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 2023 TradingView, Inc. + + 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. + +## Licenses of bundled dependencies + +The published create-lwc-plugin artifact additionally contains code with the following licenses: +ISC, MIT + +## Bundled dependencies + +### @clack/prompts + +MIT License + +Copyright (c) Nate Moore + +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. + +--- + +`ansi-regex` is adapted from https://github.com/chalk/ansi-regex + +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. + +### picocolors + +ISC License + +Copyright (c) 2021 Alexey Raspopov, Kostiantyn Denysov, Anton Verinov + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +## unbuild + +MIT License + +Copyright (c) Pooya Parsa + +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. + +### Vite + +MIT License + +Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors + +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. diff --git a/packages/create-lwc-plugin/README.md b/packages/create-lwc-plugin/README.md new file mode 100644 index 0000000000..534d5f8b6d --- /dev/null +++ b/packages/create-lwc-plugin/README.md @@ -0,0 +1,82 @@ +# create-lwc-plugin + +**create-lwc-plugin** is an npm package designed to simplify the process of +creating a new plugin for Lightweight Charts™. With this generator, you can +quickly scaffold a project from a template for either + +- a Drawing primitive plugin, or +- a Custom series plugin. + +By using this wizard-like tool, you can customize the initial setup of their +plugin project by answering a few questions. This allows for a seamless and +efficient starting point, saving valuable time and effort. + +Whether you are developing a new Drawing primitive plugin or a Custom series +plugin for Lightweight Charts, this generator provides a structured and +organized foundation. It ensures that your plugin adheres to the best practices +and conventions of Lightweight Charts, making it easier to develop, maintain, +and contribute to the community. + +Getting started with your Lightweight Charts plugin development has never been +easier. Let the Lightweight Charts™ Plugin Scaffold Generator +(`create-lwc-plugin`) handle the initial setup, so you can focus on creating +outstanding plugins for Lightweight Charts™. + +✨ Need some examples for inspiration? Check out the +[plugin-examples](https://github.com/tradingview/lightweight-charts/tree/master/plugin-examples) +folder in the Lightweight Charts repo. + +## Scaffolding Your First Lightweight Charts™ Plugin + +With NPM: + +```bash +npm create lwc-plugin@latest +``` + +With Yarn: + +```bash +yarn create lwc-plugin +``` + +With PNPM: + +```bash +pnpm create lwc-plugin +``` + +## Using the generated project + +### Running Locally (during development) + +```shell +npm install +npm run dev +``` + +Visit `localhost:5173` in the browser. + +### Compiling the Plugin + +```shell +npm run compile +``` + +Check the output in the `dist` folder. + +### Publishing To NPM + +You can configure the contents of the package's `package.json` within the +`compile.mjs` script. + +Once you have compiled the plugin (see above section) then you can publish the +package to NPM with these commands: + +```shell +cd dist +npm publish +``` + +Hint: append `--dry-run` to the end of the publish command to see the results of +the publish command without actually uploading the package to NPM. diff --git a/packages/create-lwc-plugin/build.config.ts b/packages/create-lwc-plugin/build.config.ts new file mode 100644 index 0000000000..b426440ae2 --- /dev/null +++ b/packages/create-lwc-plugin/build.config.ts @@ -0,0 +1,13 @@ +import { defineBuildConfig } from 'unbuild'; + +export default defineBuildConfig({ + entries: ['src/index'], + clean: true, + rollup: { + inlineDependencies: true, + esbuild: { + target: 'node18', + minify: true, + }, + }, +}); diff --git a/packages/create-lwc-plugin/index.js b/packages/create-lwc-plugin/index.js new file mode 100755 index 0000000000..b5585bdb14 --- /dev/null +++ b/packages/create-lwc-plugin/index.js @@ -0,0 +1,3 @@ +#!/usr/bin/env node + +import './dist/index.mjs'; diff --git a/packages/create-lwc-plugin/package.json b/packages/create-lwc-plugin/package.json new file mode 100644 index 0000000000..08cdaf9fcf --- /dev/null +++ b/packages/create-lwc-plugin/package.json @@ -0,0 +1,41 @@ +{ + "name": "create-lwc-plugin", + "version": "0.1.0", + "type": "module", + "license": "MIT", + "author": "TradingView, Inc.", + "description": "Wizard-like CLI tool for scaffolding a new plugin for Lightweight Charts™", + "keywords": ["lightweight-charts", "lwc-plugin", "plugins"], + "bin": { + "create-lwc-plugin": "index.js" + }, + "files": [ + "index.js", + "template-*", + "dist" + ], + "scripts": { + "dev": "unbuild --stub && echo 'now run `node index.js`'", + "build": "unbuild", + "typecheck": "tsc --noEmit", + "prepublishOnly": "npm run build" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/tradingview/lightweight-charts.git", + "directory": "packages/create-lwc-plugin" + }, + "bugs": { + "url": "https://github.com/slicedsilver/create-lwc-plugin/issues" + }, + "homepage": "https://tradingview.github.io/lightweight-charts/", + "devDependencies": { + "@clack/prompts": "^0.7.0", + "@types/node": "^20.5.1", + "picocolors": "^1.0.0", + "unbuild": "^1.2.1" + } +} diff --git a/packages/create-lwc-plugin/src/helpers/io.ts b/packages/create-lwc-plugin/src/helpers/io.ts new file mode 100644 index 0000000000..da2fcd1dfc --- /dev/null +++ b/packages/create-lwc-plugin/src/helpers/io.ts @@ -0,0 +1,54 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +export function formatTargetDir(targetDir: string | undefined) { + return targetDir?.trim().replace(/\/+$/g, ''); +} + +export function copy(src: string, dest: string, contentReplacer?: (content: string) => string) { + const stat = fs.statSync(src); + if (stat.isDirectory()) { + copyDir(src, dest, contentReplacer); + } else { + const content = fs.readFileSync(src).toString(); + fs.writeFileSync(dest, contentReplacer ? contentReplacer(content) : content); + } +} + +export function copyDir(srcDir: string, destDir: string, contentReplacer?: (content: string) => string) { + fs.mkdirSync(destDir, { recursive: true }); + for (const file of fs.readdirSync(srcDir)) { + const srcFile = path.resolve(srcDir, file); + const destFile = path.resolve(destDir, file); + copy(srcFile, destFile, contentReplacer); + } +} + +export function dirExists(dir: string) { + return fs.existsSync(dir); +} + +export function isEmpty(path: string) { + const files = fs.readdirSync(path); + return files.length === 0 || (files.length === 1 && files[0] === '.git'); +} + +export function emptyDir(dir: string) { + if (!fs.existsSync(dir)) { + return; + } + for (const file of fs.readdirSync(dir)) { + if (file === '.git') { + continue; + } + fs.rmSync(path.resolve(dir, file), { recursive: true, force: true }); + } +} + +// editFile(path.resolve(root, `vite.config.${isTs ? 'ts' : 'js'}`), content => { +// return content.replace('@vitejs/plugin-react', '@vitejs/plugin-react-swc'); +// }); +export function editFile(file: string, callback: (content: string) => string) { + const content = fs.readFileSync(file, 'utf-8'); + fs.writeFileSync(file, callback(content), 'utf-8'); +} diff --git a/packages/create-lwc-plugin/src/helpers/package.ts b/packages/create-lwc-plugin/src/helpers/package.ts new file mode 100644 index 0000000000..ab8713548e --- /dev/null +++ b/packages/create-lwc-plugin/src/helpers/package.ts @@ -0,0 +1,14 @@ +function pkgFromUserAgent(userAgent: string | undefined) { + if (!userAgent) return undefined; + const pkgSpec = userAgent.split(' ')[0]; + const pkgSpecArr = pkgSpec.split('/'); + return { + name: pkgSpecArr[0], + version: pkgSpecArr[1], + }; +} + +export function getPkgManagerName() { + const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent); + return pkgInfo ? pkgInfo.name : 'npm'; +} diff --git a/packages/create-lwc-plugin/src/helpers/validation.ts b/packages/create-lwc-plugin/src/helpers/validation.ts new file mode 100644 index 0000000000..b0e639c442 --- /dev/null +++ b/packages/create-lwc-plugin/src/helpers/validation.ts @@ -0,0 +1,14 @@ +export function isValidPackageName(projectName: string) { + return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test( + projectName + ); +} + +export function toValidPackageName(projectName: string) { + return projectName + .trim() + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/^[._]/, '') + .replace(/[^a-z\d\-~]+/g, '-'); +} diff --git a/packages/create-lwc-plugin/src/index.ts b/packages/create-lwc-plugin/src/index.ts new file mode 100755 index 0000000000..80a565f024 --- /dev/null +++ b/packages/create-lwc-plugin/src/index.ts @@ -0,0 +1,101 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { intro, outro, spinner, cancel } from '@clack/prompts'; +import color from 'picocolors'; +import { Answers, askQuestions } from './questions'; +import { copy } from './helpers/io'; + +const cwd = process.cwd(); + +const renameFiles: Record = { + _gitignore: '.gitignore', +}; + +async function init() { + console.log(); + intro(color.inverse(' create-lwc-plugin ')); + + let answers: Answers; + try { + answers = await askQuestions(); + } catch (e: unknown) { + if (e instanceof Error) { + cancel(e.message); + } + return process.exit(0); + } + + const s = spinner(); + + s.start('Building your new plugin project'); + const root = path.join(cwd, answers.targetFolderPath); + if (answers.targetFolderPath) { + fs.mkdirSync(root, { recursive: true }); + } + const templateDir = path.resolve( + fileURLToPath(import.meta.url), + '../..', + `template-${answers.projectType}` + ); + const commonTemplateDir = path.resolve( + fileURLToPath(import.meta.url), + '../..', + `template-common` + ); + + const entryName = 'template-entry'; + const newEntryName = answers.packageName.replace(/lwc-plugin-/, ''); + const entryFileName = `${entryName}.ts`; + const newEntryFileName = `${newEntryName}.ts`; + + const contentsReplacer = (content: string): string => { + const result = content + .replaceAll(entryName, newEntryName) + .replace(/_PLUGINNAME_/g, answers.name) + .replace(/_CLASSNAME_/g, answers.typeName) + .replace(/_PACKAGENAME_/g, answers.packageName); + if (answers.includeHints) { + return result; + } + // Comments starting with '//*' are considered 'hints' + return result.replace(/.*\/\/\*.*\r?\n/g, ''); + }; + + const write = (dir: string, file: string, content?: string) => { + const targetPath = path.join(root, renameFiles[file] ?? file); + if (content) { + fs.writeFileSync(targetPath, contentsReplacer(content)); + } else { + copy(path.join(dir, file), targetPath, contentsReplacer); + } + }; + + const files = fs.readdirSync(templateDir); + for (const file of files) { + write(templateDir, file); + } + + const commonFiles = fs.readdirSync(commonTemplateDir); + for (const file of commonFiles.filter(f => f !== 'package.json')) { + write(commonTemplateDir, file); + } + + const pkg = JSON.parse( + fs.readFileSync(path.join(commonTemplateDir, `package.json`), 'utf-8') + ); + + pkg.name = answers.packageName; + + write(root, 'package.json', JSON.stringify(pkg, null, 2) + '\n'); + + fs.renameSync(path.join(root, 'src', entryFileName), path.join(root, 'src', newEntryFileName)); + + s.stop('Built your new plugin project'); + + outro("You're all set!"); +} + +init().catch(e => { + console.error(e); +}); diff --git a/packages/create-lwc-plugin/src/questions.ts b/packages/create-lwc-plugin/src/questions.ts new file mode 100644 index 0000000000..18cab0797e --- /dev/null +++ b/packages/create-lwc-plugin/src/questions.ts @@ -0,0 +1,126 @@ +import { confirm, select, isCancel, text, log } from '@clack/prompts'; +import { isValidPackageName, toValidPackageName } from './helpers/validation'; +import color from 'picocolors'; +import { dirExists, isEmpty } from './helpers/io'; +import { resolve } from 'node:path'; + +export interface Answers { + projectType: 'series' | 'primitive'; + name: string; + packageName: string; + typeName: string; + targetFolderPath: string; + includeHints: boolean; +} + +export async function askQuestions(): Promise { + let projectType: string | symbol = ''; + while (['primitive', 'series'].includes(projectType) === false) { + const options = [ + { value: 'primitive', label: 'Drawing Primitive' }, + { value: 'series', label: 'Custom Series' }, + ]; + if (projectType !== 'help') { + options.push({ value: 'help', label: 'Help me decide' }); + } + projectType = await select({ + message: 'Pick a plugin type.', + options, + }); + if (isCancel(projectType)) throw new Error('Operation cancelled'); + if (projectType === 'help') { + log.message(`Plugins come in two types: custom series and drawing primitives. +Custom series allow developers to define new types of series, +while drawing primitives enable the creation of custom visualizations, +drawing tools, and chart annotations (and more) which can be attached +to an existing series.`); + log.info(`In the majority of cases you will most likely be better served +by using a Drawing Primitive plugin unless you are specifically +looking to create a new type of series.`); + } + } + + const name = await text({ + message: `What would you like to name the plugin?`, + placeholder: + projectType === 'series' ? 'My Custom Series' : 'My Drawing Primitive', + validate(value) { + if (value.length === 0) return 'A name is required!'; + }, + }); + if (isCancel(name)) throw new Error('Operation cancelled'); + + const suggestedPackageName = toValidPackageName('lwc-plugin-' + name); + const packageName = await text({ + message: 'Package Name for the Plugin?', + placeholder: suggestedPackageName, + initialValue: suggestedPackageName, + validate(value) { + if (value.length === 0) return 'A class name is required!'; + if (!value.startsWith('lwc-plugin-')) + return 'A package name should start with `lwc-plugin-`'; + if (!isValidPackageName(value)) + return 'The name is not a valid npm package name!'; + }, + }); + if (isCancel(packageName)) throw new Error('Operation cancelled'); + + let suggestedTypeName = name.replace(/[^a-zA-Z0-9]/g, ''); + suggestedTypeName = + suggestedTypeName[0].toUpperCase() + suggestedTypeName.slice(1); + + const typeName = await text({ + message: 'Class Name for the Plugin?', + placeholder: suggestedTypeName, + initialValue: suggestedTypeName, + validate(value) { + if (value.length === 0) return 'A class name is required!'; + if (/\s/.test(value)) return 'A class name may not contain any spaces!'; + if (/\-/.test(value)) return 'A class name may not contain any hyphens!'; + if (/^\d/.test(value)) return 'A class name may not start with a digit!'; + if (/^[a-zA-Z0-9]+$/.test(value) === false) + return 'A class name may only contain letters and numbers!'; + if (/^[a-z]/.test(value)) + return 'A class name should start with a capital letter!'; + }, + }); + if (isCancel(typeName)) throw new Error('Operation cancelled'); + + const includeHints = await confirm({ + message: 'Include hint comments?', + }); + if (isCancel(includeHints)) throw new Error('Operation cancelled'); + + const targetFolderPath = await text({ + message: `Relative Folder Path for Created Plugin? ${color.dim( + '(leave blank to use current directory)' + )}`, + placeholder: packageName, + initialValue: packageName, + validate(value) { + const cwd = process.cwd(); + const path = resolve(cwd, value); + if (value && dirExists(path) && !isEmpty(path)) return 'folder already exists, and it is not empty!'; + if (!value && !isEmpty(path)) return 'current directory is not empty!'; + }, + }); + if (isCancel(targetFolderPath)) throw new Error('Operation cancelled'); + + const shouldContinue = await confirm({ + message: `Scaffold a new plugin project into the ${color.bold( + targetFolderPath || 'current' + )} folder?`, + active: 'Start', + inactive: 'Cancel', + }); + if (isCancel(shouldContinue) || !shouldContinue) + throw new Error('Operation cancelled'); + return { + projectType: projectType as 'series' | 'primitive', + name, + packageName, + typeName, + targetFolderPath, + includeHints, + }; +} diff --git a/packages/create-lwc-plugin/template-common/README.md b/packages/create-lwc-plugin/template-common/README.md new file mode 100644 index 0000000000..b0673eb5fd --- /dev/null +++ b/packages/create-lwc-plugin/template-common/README.md @@ -0,0 +1,38 @@ +# _PLUGINNAME_ - Lightweight Charts™ Plugin + +Description of the Plugin. + +- Developed for Lightweight Charts version: `v4.1.0` + +## Running Locally + +```shell +npm install +npm run dev +``` + +Visit `localhost:5173` in the browser. + +## Compiling + +```shell +npm run compile +``` + +Check the output in the `dist` folder. + +## Publishing To NPM + +You can configure the contents of the package's `package.json` within the +`compile.mjs` script. + +Once you have compiled the plugin (see above section) then you can publish the +package to NPM with these commands: + +```shell +cd dist +npm publish +``` + +Hint: append `--dry-run` to the end of the publish command to see the results of +the publish command without actually uploading the package to NPM. diff --git a/packages/create-lwc-plugin/template-common/_gitignore b/packages/create-lwc-plugin/template-common/_gitignore new file mode 100644 index 0000000000..a90cc1392a --- /dev/null +++ b/packages/create-lwc-plugin/template-common/_gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +typings +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/packages/create-lwc-plugin/template-common/compile.mjs b/packages/create-lwc-plugin/template-common/compile.mjs new file mode 100644 index 0000000000..9ecd494b8f --- /dev/null +++ b/packages/create-lwc-plugin/template-common/compile.mjs @@ -0,0 +1,116 @@ +import { dirname, resolve } from 'node:path'; +import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { build, defineConfig } from 'vite'; +import { fileURLToPath } from 'url'; +import { generateDtsBundle } from 'dts-bundle-generator'; + +function buildPackageJson(packageName) { + /* + Define the contents of the package's package.json here. + */ + return { + name: packageName, + version: '1.0.0', + keywords: ['lwc-plugin', 'lightweight-charts'], + type: 'module', + main: `./${packageName}.umd.cjs`, + module: `./${packageName}.js`, + types: `./${packageName}.d.ts`, + exports: { + import: { + types: `./${packageName}.d.ts`, + default: `./${packageName}.js`, + }, + require: { + types: `./${packageName}.d.cts`, + default: `./${packageName}.umd.cjs`, + }, + }, + }; +} + +const __filename = fileURLToPath(import.meta.url); +const currentDir = dirname(__filename); + +const pluginFileName = 'template-entry'; +const pluginFile = resolve(currentDir, 'src', `${pluginFileName}.ts`); + +const pluginsToBuild = [ + { + filepath: pluginFile, + exportName: '_PACKAGENAME_', + name: '_CLASSNAME_', + }, +]; + +const compiledFolder = resolve(currentDir, 'dist'); +if (!existsSync(compiledFolder)) { + mkdirSync(compiledFolder); +} + +const buildConfig = ({ + filepath, + name, + exportName, + formats = ['es', 'umd'], +}) => { + return defineConfig({ + publicDir: false, + build: { + outDir: `dist`, + emptyOutDir: true, + copyPublicDir: false, + lib: { + entry: filepath, + name, + formats, + fileName: exportName, + }, + rollupOptions: { + external: ['lightweight-charts', 'fancy-canvas'], + output: { + globals: { + 'lightweight-charts': 'LightweightCharts', + }, + }, + }, + }, + }); +}; + +const startTime = Date.now().valueOf(); +console.log('⚡️ Starting'); +console.log('Bundling the plugin...'); +const promises = pluginsToBuild.map(file => { + return build(buildConfig(file)); +}); +await Promise.all(promises); +console.log('Generating the package.json file...'); +pluginsToBuild.forEach(file => { + const packagePath = resolve(compiledFolder, 'package.json'); + const content = JSON.stringify( + buildPackageJson(file.exportName), + undefined, + 4 + ); + writeFileSync(packagePath, content, { encoding: 'utf-8' }); +}); +console.log('Generating the typings files...'); +pluginsToBuild.forEach(file => { + try { + const esModuleTyping = generateDtsBundle([ + { + filePath: `./typings/${pluginFileName}.d.ts`, + }, + ]); + const typingFilePath = resolve(compiledFolder, `${file.exportName}.d.ts`); + writeFileSync(typingFilePath, esModuleTyping.join('\n'), { + encoding: 'utf-8', + }); + copyFileSync(typingFilePath, resolve(compiledFolder, `${file.exportName}.d.cts`)); + } catch (e) { + console.error('Error generating typings for: ', file.exportName); + } +}); +const endTime = Date.now().valueOf(); +console.log(`🎉 Done (${endTime - startTime}ms)`); diff --git a/packages/create-lwc-plugin/template-common/index.html b/packages/create-lwc-plugin/template-common/index.html new file mode 100644 index 0000000000..3f1b3a1b19 --- /dev/null +++ b/packages/create-lwc-plugin/template-common/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/packages/create-lwc-plugin/template-common/package.json b/packages/create-lwc-plugin/template-common/package.json new file mode 100644 index 0000000000..eaa476ba3d --- /dev/null +++ b/packages/create-lwc-plugin/template-common/package.json @@ -0,0 +1,17 @@ +{ + "name": "to-be-replaced", + "type": "module", + "scripts": { + "dev": "vite --config src/vite.config.js", + "compile": "tsc && node compile.mjs" + }, + "devDependencies": { + "typescript": "^5.0.4", + "vite": "^4.3.1" + }, + "dependencies": { + "dts-bundle-generator": "^8.0.1", + "fancy-canvas": "^2.1.0", + "lightweight-charts": "^4.1.0-rc2" + } +} diff --git a/packages/create-lwc-plugin/template-common/src/helpers/dimensions/common.ts b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/common.ts new file mode 100644 index 0000000000..394c6bb9ad --- /dev/null +++ b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/common.ts @@ -0,0 +1,6 @@ +export interface BitmapPositionLength { + /** coordinate for use with a bitmap rendering scope */ + position: number; + /** length for use with a bitmap rendering scope */ + length: number; +} diff --git a/packages/create-lwc-plugin/template-common/src/helpers/dimensions/crosshair-width.ts b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/crosshair-width.ts new file mode 100644 index 0000000000..9d14991aaf --- /dev/null +++ b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/crosshair-width.ts @@ -0,0 +1,23 @@ +/** + * Default grid / crosshair line width in Bitmap sizing + * @param horizontalPixelRatio - horizontal pixel ratio + * @returns default grid / crosshair line width in Bitmap sizing + */ +export function gridAndCrosshairBitmapWidth( + horizontalPixelRatio: number +): number { + return Math.max(1, Math.floor(horizontalPixelRatio)); +} + +/** + * Default grid / crosshair line width in Media sizing + * @param horizontalPixelRatio - horizontal pixel ratio + * @returns default grid / crosshair line width in Media sizing + */ +export function gridAndCrosshairMediaWidth( + horizontalPixelRatio: number +): number { + return ( + gridAndCrosshairBitmapWidth(horizontalPixelRatio) / horizontalPixelRatio + ); +} diff --git a/packages/create-lwc-plugin/template-common/src/helpers/dimensions/full-width.ts b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/full-width.ts new file mode 100644 index 0000000000..6f4d40dd41 --- /dev/null +++ b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/full-width.ts @@ -0,0 +1,29 @@ +import { BitmapPositionLength } from './common'; + +/** + * Calculates the position and width which will completely full the space for the bar. + * Useful if you want to draw something that will not have any gaps between surrounding bars. + * @param xMedia - x coordinate of the bar defined in media sizing + * @param halfBarSpacingMedia - half the width of the current barSpacing (un-rounded) + * @param horizontalPixelRatio - horizontal pixel ratio + * @returns position and width which will completely full the space for the bar + */ +export function fullBarWidth( + xMedia: number, + halfBarSpacingMedia: number, + horizontalPixelRatio: number +): BitmapPositionLength { + const fullWidthLeftMedia = xMedia - halfBarSpacingMedia; + const fullWidthRightMedia = xMedia + halfBarSpacingMedia; + const fullWidthLeftBitmap = Math.round( + fullWidthLeftMedia * horizontalPixelRatio + ); + const fullWidthRightBitmap = Math.round( + fullWidthRightMedia * horizontalPixelRatio + ); + const fullWidthBitmap = fullWidthRightBitmap - fullWidthLeftBitmap; + return { + position: fullWidthLeftBitmap, + length: fullWidthBitmap, + }; +} diff --git a/packages/create-lwc-plugin/template-common/src/helpers/dimensions/positions.ts b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/positions.ts new file mode 100644 index 0000000000..a021b072b0 --- /dev/null +++ b/packages/create-lwc-plugin/template-common/src/helpers/dimensions/positions.ts @@ -0,0 +1,48 @@ +import { BitmapPositionLength } from './common'; + +function centreOffset(lineBitmapWidth: number): number { + return Math.floor(lineBitmapWidth * 0.5); +} + +/** + * Calculates the bitmap position for an item with a desired length (height or width), and centred according to + * an position coordinate defined in media sizing. + * @param positionMedia - position coordinate for the bar (in media coordinates) + * @param pixelRatio - pixel ratio. Either horizontal for x positions, or vertical for y positions + * @param desiredWidthMedia - desired width (in media coordinates) + * @returns Position of of the start point and length dimension. + */ +export function positionsLine( + positionMedia: number, + pixelRatio: number, + desiredWidthMedia: number = 1, + widthIsBitmap?: boolean +): BitmapPositionLength { + const scaledPosition = Math.round(pixelRatio * positionMedia); + const lineBitmapWidth = widthIsBitmap + ? desiredWidthMedia + : Math.round(desiredWidthMedia * pixelRatio); + const offset = centreOffset(lineBitmapWidth); + const position = scaledPosition - offset; + return { position, length: lineBitmapWidth }; +} + +/** + * Determines the bitmap position and length for a dimension of a shape to be drawn. + * @param position1Media - media coordinate for the first point + * @param position2Media - media coordinate for the second point + * @param pixelRatio - pixel ratio for the corresponding axis (vertical or horizontal) + * @returns Position of of the start point and length dimension. + */ +export function positionsBox( + position1Media: number, + position2Media: number, + pixelRatio: number +): BitmapPositionLength { + const scaledPosition1 = Math.round(pixelRatio * position1Media); + const scaledPosition2 = Math.round(pixelRatio * position2Media); + return { + position: Math.min(scaledPosition1, scaledPosition2), + length: Math.abs(scaledPosition2 - scaledPosition1) + 1, + }; +} diff --git a/packages/create-lwc-plugin/template-common/src/helpers/time.ts b/packages/create-lwc-plugin/template-common/src/helpers/time.ts new file mode 100644 index 0000000000..ed654758a1 --- /dev/null +++ b/packages/create-lwc-plugin/template-common/src/helpers/time.ts @@ -0,0 +1,34 @@ +import { Time, isUTCTimestamp, isBusinessDay } from 'lightweight-charts'; + +export function convertTime(t: Time): number { + if (isUTCTimestamp(t)) return t * 1000; + if (isBusinessDay(t)) return new Date(t.year, t.month, t.day).valueOf(); + const [year, month, day] = t.split('-').map(parseInt); + return new Date(year, month, day).valueOf(); +} + +export function displayTime(time: Time): string { + if (typeof time == 'string') return time; + const date = isBusinessDay(time) + ? new Date(time.year, time.month, time.day) + : new Date(time * 1000); + return date.toLocaleDateString(); +} + +export function formattedDateAndTime(timestamp: number | undefined): [string, string] { + if (!timestamp) return ['', '']; + const dateObj = new Date(timestamp); + + // Format date string + const year = dateObj.getFullYear(); + const month = dateObj.toLocaleString('default', { month: 'short' }); + const date = dateObj.getDate().toString().padStart(2, '0'); + const formattedDate = `${date} ${month} ${year}`; + + // Format time string + const hours = dateObj.getHours().toString().padStart(2, '0'); + const minutes = dateObj.getMinutes().toString().padStart(2, '0'); + const formattedTime = `${hours}:${minutes}`; + + return [formattedDate, formattedTime]; +} diff --git a/packages/create-lwc-plugin/template-common/src/vite-env.d.ts b/packages/create-lwc-plugin/template-common/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/packages/create-lwc-plugin/template-common/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/packages/create-lwc-plugin/template-common/src/vite.config.js b/packages/create-lwc-plugin/template-common/src/vite.config.js new file mode 100644 index 0000000000..a7ae019b73 --- /dev/null +++ b/packages/create-lwc-plugin/template-common/src/vite.config.js @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite'; + +const input = { + main: './src/example/index.html', +}; + +export default defineConfig({ + build: { + rollupOptions: { + input, + }, + }, +}); diff --git a/packages/create-lwc-plugin/template-common/tsconfig.json b/packages/create-lwc-plugin/template-common/tsconfig.json new file mode 100644 index 0000000000..99e948c965 --- /dev/null +++ b/packages/create-lwc-plugin/template-common/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ESNext", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ESNext", "DOM"], + "moduleResolution": "Node", + "strict": true, + "resolveJsonModule": true, + "isolatedModules": true, + "esModuleInterop": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "skipLibCheck": true, + "declaration": true, + "declarationDir": "typings", + "emitDeclarationOnly": true + }, + "include": ["src"] +} diff --git a/packages/create-lwc-plugin/template-primitive/src/axis-pane-renderer.ts b/packages/create-lwc-plugin/template-primitive/src/axis-pane-renderer.ts new file mode 100644 index 0000000000..1125c37f6b --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/axis-pane-renderer.ts @@ -0,0 +1,44 @@ +import { CanvasRenderingTarget2D } from 'fancy-canvas'; +import { ISeriesPrimitivePaneRenderer } from 'lightweight-charts'; +import { positionsBox } from './helpers/dimensions/positions'; + +export class _CLASSNAME_AxisPaneRenderer implements ISeriesPrimitivePaneRenderer { + _p1: number | null; + _p2: number | null; + _fillColor: string; + _vertical: boolean = false; + + constructor( + p1: number | null, + p2: number | null, + fillColor: string, + vertical: boolean + ) { + this._p1 = p1; + this._p2 = p2; + this._fillColor = fillColor; + this._vertical = vertical; + } + + draw(target: CanvasRenderingTarget2D) { + target.useBitmapCoordinateSpace(scope => { + if (this._p1 === null || this._p2 === null) return; + const ctx = scope.context; + ctx.save(); + ctx.globalAlpha = 0.5; + const positions = positionsBox( + this._p1, + this._p2, + this._vertical ? scope.verticalPixelRatio : scope.horizontalPixelRatio + ); + ctx.fillStyle = this._fillColor; + if (this._vertical) { + ctx.fillRect(0, positions.position, 15, positions.length); + } else { + ctx.fillRect(positions.position, 0, positions.length, 15); + } + + ctx.restore(); + }); + } +} diff --git a/packages/create-lwc-plugin/template-primitive/src/axis-pane-view.ts b/packages/create-lwc-plugin/template-primitive/src/axis-pane-view.ts new file mode 100644 index 0000000000..0b2caac371 --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/axis-pane-view.ts @@ -0,0 +1,55 @@ +import { + Coordinate, + ISeriesPrimitivePaneView, + SeriesPrimitivePaneViewZOrder, +} from 'lightweight-charts'; +import { _CLASSNAME_AxisPaneRenderer } from './axis-pane-renderer'; +import { _CLASSNAME_DataSource } from './data-source'; + +abstract class _CLASSNAME_AxisPaneView implements ISeriesPrimitivePaneView { + _source: _CLASSNAME_DataSource; + _p1: number | null = null; + _p2: number | null = null; + _vertical: boolean = false; + + constructor(source: _CLASSNAME_DataSource, vertical: boolean) { + this._source = source; + this._vertical = vertical; + } + + abstract getPoints(): [Coordinate | null, Coordinate | null]; + + update() { + [this._p1, this._p2] = this.getPoints(); + } + + renderer() { + return new _CLASSNAME_AxisPaneRenderer( + this._p1, + this._p2, + this._source.options.fillColor, + this._vertical + ); + } + zOrder(): SeriesPrimitivePaneViewZOrder { + return 'bottom'; + } +} + +export class _CLASSNAME_PriceAxisPaneView extends _CLASSNAME_AxisPaneView { + getPoints(): [Coordinate | null, Coordinate | null] { + const series = this._source.series; + const y1 = series.priceToCoordinate(this._source.p1.price); + const y2 = series.priceToCoordinate(this._source.p2.price); + return [y1, y2]; + } +} + +export class _CLASSNAME_TimeAxisPaneView extends _CLASSNAME_AxisPaneView { + getPoints(): [Coordinate | null, Coordinate | null] { + const timeScale = this._source.chart.timeScale(); + const x1 = timeScale.timeToCoordinate(this._source.p1.time); + const x2 = timeScale.timeToCoordinate(this._source.p2.time); + return [x1, x2]; + } +} diff --git a/packages/create-lwc-plugin/template-primitive/src/axis-view.ts b/packages/create-lwc-plugin/template-primitive/src/axis-view.ts new file mode 100644 index 0000000000..2f3f2f0570 --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/axis-view.ts @@ -0,0 +1,57 @@ +import { Coordinate, ISeriesPrimitiveAxisView } from 'lightweight-charts'; +import { Point, _CLASSNAME_DataSource } from './data-source'; + +abstract class _CLASSNAME_AxisView implements ISeriesPrimitiveAxisView { + _source: _CLASSNAME_DataSource; + _p: Point; + _pos: Coordinate | null = null; + constructor(source: _CLASSNAME_DataSource, p: Point) { + this._source = source; + this._p = p; + } + abstract update(): void; + abstract text(): string; + + coordinate() { + return this._pos ?? -1; + } + + visible(): boolean { + return this._source.options.showLabels; + } + + tickVisible(): boolean { + return this._source.options.showLabels; + } + + textColor() { + return this._source.options.labelTextColor; + } + backColor() { + return this._source.options.labelColor; + } + movePoint(p: Point) { + this._p = p; + this.update(); + } +} + +export class _CLASSNAME_TimeAxisView extends _CLASSNAME_AxisView { + update() { + const timeScale = this._source.chart.timeScale(); + this._pos = timeScale.timeToCoordinate(this._p.time); + } + text() { + return this._source.options.timeLabelFormatter(this._p.time); + } +} + +export class _CLASSNAME_PriceAxisView extends _CLASSNAME_AxisView { + update() { + const series = this._source.series; + this._pos = series.priceToCoordinate(this._p.price); + } + text() { + return this._source.options.priceLabelFormatter(this._p.price); + } +} diff --git a/packages/create-lwc-plugin/template-primitive/src/data-source.ts b/packages/create-lwc-plugin/template-primitive/src/data-source.ts new file mode 100644 index 0000000000..f56ffef4c3 --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/data-source.ts @@ -0,0 +1,20 @@ +import { + IChartApi, + ISeriesApi, + SeriesOptionsMap, + Time, +} from 'lightweight-charts'; +import { _CLASSNAME_Options } from './options'; + +export interface Point { + time: Time; + price: number; +} + +export interface _CLASSNAME_DataSource { + chart: IChartApi; + series: ISeriesApi; + options: _CLASSNAME_Options; + p1: Point; + p2: Point; +} diff --git a/packages/create-lwc-plugin/template-primitive/src/example/example.ts b/packages/create-lwc-plugin/template-primitive/src/example/example.ts new file mode 100644 index 0000000000..2b1a151c17 --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/example/example.ts @@ -0,0 +1,23 @@ +import { createChart } from 'lightweight-charts'; +import { generateLineData } from '../sample-data'; +import { _CLASSNAME_ } from '../template-entry'; + +const chart = ((window as unknown as any).chart = createChart('chart', { + autoSize: true, +})); + +const lineSeries = chart.addLineSeries({ + color: '#000000', +}); +const data = generateLineData(); +lineSeries.setData(data); + +const time1 = data[data.length - 50].time; +const time2 = data[data.length - 10].time; + +const primitive = new _CLASSNAME_( + { price: 100, time: time1 }, + { price: 500, time: time2 } +); + +lineSeries.attachPrimitive(primitive); diff --git a/packages/create-lwc-plugin/template-primitive/src/example/index.html b/packages/create-lwc-plugin/template-primitive/src/example/index.html new file mode 100644 index 0000000000..ed1334b874 --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/example/index.html @@ -0,0 +1,26 @@ + + + + + + Template Drawing Primitive Plugin Example + + + +
+ + + diff --git a/packages/create-lwc-plugin/template-primitive/src/helpers/assertions.ts b/packages/create-lwc-plugin/template-primitive/src/helpers/assertions.ts new file mode 100644 index 0000000000..e68742f3cf --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/helpers/assertions.ts @@ -0,0 +1,33 @@ +/** + * Ensures that value is defined. + * Throws if the value is undefined, returns the original value otherwise. + * + * @param value - The value, or undefined. + * @returns The passed value, if it is not undefined + */ +export function ensureDefined(value: undefined): never; +export function ensureDefined(value: T | undefined): T; +export function ensureDefined(value: T | undefined): T { + if (value === undefined) { + throw new Error('Value is undefined'); + } + + return value; +} + +/** + * Ensures that value is not null. + * Throws if the value is null, returns the original value otherwise. + * + * @param value - The value, or null. + * @returns The passed value, if it is not null + */ +export function ensureNotNull(value: null): never; +export function ensureNotNull(value: T | null): T; +export function ensureNotNull(value: T | null): T { + if (value === null) { + throw new Error('Value is null'); + } + + return value; +} diff --git a/packages/create-lwc-plugin/template-primitive/src/options.ts b/packages/create-lwc-plugin/template-primitive/src/options.ts new file mode 100644 index 0000000000..91f34ea865 --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/options.ts @@ -0,0 +1,27 @@ +import { Time, isBusinessDay } from 'lightweight-charts'; + +export interface _CLASSNAME_Options { + //* Define the options for the primitive. + fillColor: string; + labelColor: string; + labelTextColor: string; + showLabels: boolean; + priceLabelFormatter: (price: number) => string; + timeLabelFormatter: (time: Time) => string; +} + +export const defaultOptions: _CLASSNAME_Options = { + //* Define the default values for all the primitive options. + fillColor: 'rgba(200, 50, 100, 0.75)', + labelColor: 'rgba(200, 50, 100, 1)', + labelTextColor: 'white', + showLabels: true, + priceLabelFormatter: (price: number) => price.toFixed(2), + timeLabelFormatter: (time: Time) => { + if (typeof time == 'string') return time; + const date = isBusinessDay(time) + ? new Date(time.year, time.month, time.day) + : new Date(time * 1000); + return date.toLocaleDateString(); + }, +} as const; diff --git a/packages/create-lwc-plugin/template-primitive/src/pane-renderer.ts b/packages/create-lwc-plugin/template-primitive/src/pane-renderer.ts new file mode 100644 index 0000000000..663cda036c --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/pane-renderer.ts @@ -0,0 +1,46 @@ +import { CanvasRenderingTarget2D } from 'fancy-canvas'; +import { ISeriesPrimitivePaneRenderer } from 'lightweight-charts'; +import { ViewPoint } from './pane-view'; +import { positionsBox } from './helpers/dimensions/positions'; + +export class _CLASSNAME_PaneRenderer implements ISeriesPrimitivePaneRenderer { + _p1: ViewPoint; + _p2: ViewPoint; + _fillColor: string; + + constructor(p1: ViewPoint, p2: ViewPoint, fillColor: string) { + this._p1 = p1; + this._p2 = p2; + this._fillColor = fillColor; + } + + draw(target: CanvasRenderingTarget2D) { + target.useBitmapCoordinateSpace(scope => { + if ( + this._p1.x === null || + this._p1.y === null || + this._p2.x === null || + this._p2.y === null + ) + return; + const ctx = scope.context; + const horizontalPositions = positionsBox( + this._p1.x, + this._p2.x, + scope.horizontalPixelRatio + ); + const verticalPositions = positionsBox( + this._p1.y, + this._p2.y, + scope.verticalPixelRatio + ); + ctx.fillStyle = this._fillColor; + ctx.fillRect( + horizontalPositions.position, + verticalPositions.position, + horizontalPositions.length, + verticalPositions.length + ); + }); + } +} diff --git a/packages/create-lwc-plugin/template-primitive/src/pane-view.ts b/packages/create-lwc-plugin/template-primitive/src/pane-view.ts new file mode 100644 index 0000000000..0ddf569262 --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/pane-view.ts @@ -0,0 +1,37 @@ +import { Coordinate, ISeriesPrimitivePaneView } from 'lightweight-charts'; +import { _CLASSNAME_PaneRenderer } from './pane-renderer'; +import { _CLASSNAME_DataSource } from './data-source'; + +export interface ViewPoint { + x: Coordinate | null; + y: Coordinate | null; +} + +export class _CLASSNAME_PaneView implements ISeriesPrimitivePaneView { + _source: _CLASSNAME_DataSource; + _p1: ViewPoint = { x: null, y: null }; + _p2: ViewPoint = { x: null, y: null }; + + constructor(source: _CLASSNAME_DataSource) { + this._source = source; + } + + update() { + const series = this._source.series; + const y1 = series.priceToCoordinate(this._source.p1.price); + const y2 = series.priceToCoordinate(this._source.p2.price); + const timeScale = this._source.chart.timeScale(); + const x1 = timeScale.timeToCoordinate(this._source.p1.time); + const x2 = timeScale.timeToCoordinate(this._source.p2.time); + this._p1 = { x: x1, y: y1 }; + this._p2 = { x: x2, y: y2 }; + } + + renderer() { + return new _CLASSNAME_PaneRenderer( + this._p1, + this._p2, + this._source.options.fillColor + ); + } +} diff --git a/packages/create-lwc-plugin/template-primitive/src/plugin-base.ts b/packages/create-lwc-plugin/template-primitive/src/plugin-base.ts new file mode 100644 index 0000000000..def9684a9b --- /dev/null +++ b/packages/create-lwc-plugin/template-primitive/src/plugin-base.ts @@ -0,0 +1,56 @@ +import { + DataChangedScope, + IChartApi, + ISeriesApi, + ISeriesPrimitive, + SeriesAttachedParameter, + SeriesOptionsMap, + Time, +} from 'lightweight-charts'; +import { ensureDefined } from './helpers/assertions'; + +//* PluginBase is a useful base to build a plugin upon which +//* already handles creating getters for the chart and series, +//* and provides a requestUpdate method. +export abstract class PluginBase implements ISeriesPrimitive