Skip to content

Commit

Permalink
add plugin examples 🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
SlicedSilver committed Aug 30, 2023
1 parent ef47716 commit 86da482
Show file tree
Hide file tree
Showing 163 changed files with 11,325 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@
/website/docs/api/**
/website/versioned_docs/**/api/**
/website/build/**

/plugin-examples
9 changes: 9 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions plugin-examples/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
node_modules
dist
compiled
typings
website
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
96 changes: 96 additions & 0 deletions plugin-examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Lightweight Charts™ Plugin Examples

This folder contains a collection of example plugins designed to extend the
functionality of Lightweight Charts™ and inspire the development of your own
plugins.

**Disclaimer:** These plugins are provided as-is, and are primarily intended as
proof-of-concept examples and starting points. They have not been fully
optimized for production and may not receive updates or improvements over time.

We believe in the power of community collaboration, and we warmly welcome any
pull requests (PRs) aimed at enhancing and fixing the existing examples.
Additionally, we encourage you to create your own plugins and share them with
the community. We would be delighted to showcase the best plugins our users
create in this readme document.

✨ If you have something cool to share or if you need assistance, please don't
hesitate to get in touch.

🚀 Need a starting point for your plugin idea? Check out
[create-lwc-plugin](https://github.com/tradingview/create-lwc-plugin) package.

📊 You can view a demo page of the plugins within this repo at his link:
[Plugin Examples](https://tradingview.github.io/lightweight-charts/plugin-examples)

## Learning More

- [Documentation for Plugins](https://tradingview.github.io/lightweight-charts/docs/next/plugins/intro)
- [Learn more about Lightweight Charts™](https://www.tradingview.com/lightweight-charts/)

## Running Locally

To run this repo locally, follow these steps:

1. Clone the repo to your local machine
2. First build the library

```shell
npm install
npm run build:prod
```

3. Switch to the Plugin Examples Folder, install and start the development server

```shell
cd plugin-examples
npm install
npm run dev
```

4. Visit `localhost:5173` in the browser.

## Compiling the Examples

```shell
npm run compile
```

Check the output in the `compiled` folder.

## Using an Example

Once you have compiled the examples then simply copy that folder into your
project and import the JS module in your code.

1. Copy the compiled plugin folder into your project, example:
`plugins/background-shade-series` (from `compiled/background-shade-series`)
2. Within your project, you can import the class as follows:

```js
import { BackgroundShadeSeries } from '../plugins/background-shade-series/background-shade-series';
// ...
const backgroundShadeSeriesPlugin = new BackgroundShadeSeries();
const myCustomSeries = chart.addCustomSeries(backgroundShadeSeriesPlugin, {
lowValue: 0,
highValue: 1000,
});
```
## Creating your own Plugin
[create-lwc-plugin](https://github.com/tradingview/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.
You can get started with this simple command:
```shell
npm create lwc-plugin@latest
```
72 changes: 72 additions & 0 deletions plugin-examples/build-website.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import {
existsSync,
mkdirSync,
readdirSync,
statSync,
readFileSync,
writeFileSync,
rmSync,
} from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const currentDir = dirname(__filename);

const distFolder = resolve(currentDir, 'dist');
const distSrcFolder = resolve(currentDir, 'dist', 'src');
const websiteFolder = resolve(currentDir, 'website');
const docsWebsiteFolder = resolve(currentDir, '..', 'website', 'build', 'plugin-examples');

function emptyDir(dir) {
if (!existsSync(dir)) {
return;
}
for (const file of readdirSync(dir)) {
rmSync(resolve(dir, file), { recursive: true, force: true });
}
}

function copy(src, dest, contentReplacer) {
const stat = statSync(src);
if (stat.isDirectory()) {
copyDir(src, dest, contentReplacer);
} else {
const content = readFileSync(src).toString();
writeFileSync(dest, contentReplacer ? contentReplacer(content) : content);
}
}

function copyDir(srcDir, destDir, contentReplacer) {
mkdirSync(destDir, { recursive: true });
for (const file of readdirSync(srcDir)) {
const srcFile = resolve(srcDir, file);
const destFile = resolve(destDir, file);
if (file !== 'src') {
copy(srcFile, destFile, contentReplacer);
}
}
}

function contentReplacer(content) {
return content
.replace(/("|')\.\.\/assets/g, '$1./assets')
.replace(/\/\.\.\/assets/g, '/assets');
}

emptyDir(websiteFolder);
copyDir(distFolder, websiteFolder, contentReplacer, 'src');
copyDir(distSrcFolder, websiteFolder, contentReplacer);
copy(
resolve(websiteFolder, 'index.html'),
resolve(websiteFolder, 'index.html'),
content => {
return content.replace(
'<head>',
'<head>\n<base href="/lightweight-charts/plugin-examples/">'
);
}
);

// Copy into the documentation site build
copyDir(websiteFolder, docsWebsiteFolder, content => content);
165 changes: 165 additions & 0 deletions plugin-examples/compile.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/* eslint-disable no-console */
import { dirname, resolve, basename, join, extname } from 'node:path';
import {
existsSync,
mkdirSync,
readdirSync,
statSync,
writeFileSync,
} from 'node:fs';
import { build, defineConfig } from 'vite';
import { fileURLToPath } from 'url';
import { generateDtsBundle } from 'dts-bundle-generator';

function findPluginFiles(folderPath, recursive) {
const pathNames = readdirSync(folderPath);
const matchingFiles = [];

pathNames.forEach(pathName => {
const fullPath = join(folderPath, pathName);
const stats = statSync(fullPath);

if (recursive && stats.isDirectory() && pathName === basename(fullPath)) {
const innerFiles = findPluginFiles(fullPath, false);
matchingFiles.push(...innerFiles);
} else if (
stats.isFile() &&
pathName === `${basename(folderPath)}${extname(pathName)}`
) {
matchingFiles.push([fullPath, basename(folderPath)]);
}
});

return matchingFiles;
}

function convertKebabToCamel(kebabCaseString) {
const words = kebabCaseString.split('-');
const camelCaseWords = words.map((word, index) => {
if (index === 0) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});

return camelCaseWords.join('');
}

const __filename = fileURLToPath(import.meta.url);
const currentDir = dirname(__filename);

const pluginsFolder = resolve(currentDir, 'src', 'plugins');
const pluginFiles = findPluginFiles(pluginsFolder, true);

const filesToBuild = pluginFiles.map(([filepath, exportName]) => {
return {
filepath,
exportName,
name: convertKebabToCamel(exportName),
};
});

const compiledFolder = resolve(currentDir, 'compiled');
if (!existsSync(compiledFolder)) {
mkdirSync(compiledFolder);
}

const buildConfig = ({
filepath,
name,
exportName,
formats = ['es', 'umd'],
}) => {
return defineConfig({
publicDir: false,
build: {
outDir: `compiled/${exportName}`,
emptyOutDir: true,
copyPublicDir: false,
lib: {
entry: filepath,
name,
formats,
fileName: exportName,
},
rollupOptions: {
external: ['lightweight-charts', 'fancy-canvas'],
output: {
globals: {
'lightweight-charts': 'LightweightCharts',
},
},
},
},
});
};

function buildPackageJson(exportName) {
return {
name: exportName,
type: 'module',
main: `./${exportName}.umd.cjs`,
module: `./${exportName}.js`,
exports: {
'.': {
import: `./${exportName}.js`,
require: `./${exportName}.umd.cjs`,
types: `./${exportName}.d.ts`,
},
},
};
}

const compile = async () => {
const startTime = Date.now().valueOf();
console.log('⚡️ Starting');
console.log('Bundling the plugins...');
const promises = filesToBuild.map(file => {
return build(buildConfig(file));
});
await Promise.all(promises);
console.log('Generating the package.json files...');
filesToBuild.forEach(file => {
const packagePath = resolve(
compiledFolder,
file.exportName,
'package.json'
);
const content = JSON.stringify(
buildPackageJson(file.exportName),
undefined,
4
);
writeFileSync(packagePath, content, { encoding: 'utf-8' });
});
console.log('Generating the typings files...');
filesToBuild.forEach(file => {
try {
const esModuleTyping = generateDtsBundle([
{
filePath: `./typings/plugins/${file.exportName}/${file.exportName}.d.ts`,
// output: {
// umdModuleName: file.name,
// },
},
]);
const typingFilePath = resolve(
compiledFolder,
file.exportName,
`${file.exportName}.d.ts`
);
writeFileSync(typingFilePath, esModuleTyping.join('\n'), {
encoding: 'utf-8',
});
} catch (e) {
console.error('Error generating typings for: ', file.exportName);
}
});
const endTime = Date.now().valueOf();
console.log(`🎉 Done (${endTime - startTime}ms)`);
};

(async () => {
await compile();
process.exit(0);
})();
9 changes: 9 additions & 0 deletions plugin-examples/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0; URL=src/" />
</head>
<body>
<p>List of example previews are <a href="src/">here</a></p>
</body>
</html>
Loading

0 comments on commit 86da482

Please sign in to comment.