├── .gitignore
├── .npmignore
├── CHANGELOG.md
├── GENERATOR_DOC.md
├── LICENSE
├── README.md
├── api
├── Global.d.ts
├── Joplin.d.ts
├── JoplinCommands.d.ts
├── JoplinContentScripts.d.ts
├── JoplinData.d.ts
├── JoplinFilters.d.ts
├── JoplinInterop.d.ts
├── JoplinPlugins.d.ts
├── JoplinSettings.d.ts
├── JoplinViews.d.ts
├── JoplinViewsDialogs.d.ts
├── JoplinViewsMenuItems.d.ts
├── JoplinViewsMenus.d.ts
├── JoplinViewsPanels.d.ts
├── JoplinViewsToolbarButtons.d.ts
├── JoplinWorkspace.d.ts
├── index.ts
└── types.ts
├── jest.config.js
├── package-lock.json
├── package.json
├── plugin.config.json
├── src
├── index.ts
├── lib
│ ├── calc.ts
│ ├── parser.ts
│ └── table.ts
├── manifest.json
└── tests
│ ├── calc.test.ts
│ └── table.test.ts
├── tsconfig.json
└── webpack.config.js
/.gitignore:
--------------------------------------------------------------------------------
1 | dist/*
2 | node_modules/
3 | dist/
4 | publish/
5 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | *.md
2 | !README.md
3 | /*.jpl
4 | /api
5 | /src
6 | /dist
7 | tsconfig.json
8 | webpack.config.js
9 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # CHANGELOG
2 |
3 | 1.0.1
4 |
5 | - FIX: bad parsing when formula has spaces inside
6 | - FIX: bad or missing cell values should not be taken into the cell range
7 | - TEST: bad cell value
8 | - TEST: formula with spaces
9 |
10 | 1.0.2
11 |
12 | - FIX: Unnecessary double quotes removed from computaion output
13 |
14 | 1.0.3
15 |
16 | - FIX: markdown parsing (checkbox issue)
17 | - FEAT: Table cells support strings or numbers
18 |
19 | 1.0.4
20 |
21 | - FIX: computed values are lost after changing note focus
22 |
23 | 1.0.5
24 |
25 | - FEAT: parse tables inside code blocks
26 |
--------------------------------------------------------------------------------
/GENERATOR_DOC.md:
--------------------------------------------------------------------------------
1 | # generator-joplin
2 |
3 | Scaffolds out a new Joplin plugin
4 |
5 | ## Installation
6 |
7 | First, install [Yeoman](http://yeoman.io) and generator-joplin using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)).
8 |
9 | ```bash
10 | npm install -g yo
11 | npm install -g generator-joplin
12 | ```
13 |
14 | Then generate your new project:
15 |
16 | ```bash
17 | yo joplin
18 | ```
19 |
20 | ## Development
21 |
22 | To test the generator for development purposes, follow the instructions there: https://yeoman.io/authoring/#running-the-generator
23 | This is a template to create a new Joplin plugin.
24 |
25 | ## Structure
26 |
27 | The main two files you will want to look at are:
28 |
29 | - `/src/index.ts`, which contains the entry point for the plugin source code.
30 | - `/src/manifest.json`, which is the plugin manifest. It contains information such as the plugin a name, version, etc.
31 |
32 | The file `/plugin.config.json` could also be useful if you intend to use [external scripts](#external-script-files), such as content scripts or webview scripts.
33 |
34 | ## Building the plugin
35 |
36 | The plugin is built using Webpack, which creates the compiled code in `/dist`. A JPL archive will also be created at the root, which can use to distribute the plugin.
37 |
38 | To build the plugin, simply run `npm run dist`.
39 |
40 | The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript.
41 |
42 | ## Publishing the plugin
43 |
44 | To publish the plugin, add it to npmjs.com by running `npm publish`. Later on, a script will pick up your plugin and add it automatically to the Joplin plugin repository as long as the package satisfies these conditions:
45 |
46 | - In `package.json`, the name starts with "joplin-plugin-". For example, "joplin-plugin-toc".
47 | - In `package.json`, the keywords include "joplin-plugin".
48 | - In the `publish/` directory, there should be a .jpl and .json file (which are built by `npm run dist`)
49 |
50 | In general all this is done automatically by the plugin generator, which will set the name and keywords of package.json, and will put the right files in the "publish" directory. But if something doesn't work and your plugin doesn't appear in the repository, double-check the above conditions.
51 |
52 | ## Updating the plugin framework
53 |
54 | To update the plugin framework, run `npm run update`.
55 |
56 | In general this command tries to do the right thing - in particular it's going to merge the changes in package.json and .gitignore instead of overwriting. It will also leave "/src" as well as README.md untouched.
57 |
58 | The file that may cause problem is "webpack.config.js" because it's going to be overwritten. For that reason, if you want to change it, consider creating a separate JavaScript file and include it in webpack.config.js. That way, when you update, you only have to restore the line that include your file.
59 |
60 | ## External script files
61 |
62 | By default, the compiler (webpack) is going to compile `src/index.ts` only (as well as any file it imports), and any other file will simply be copied to the plugin package. In some cases this is sufficient, however if you have [content scripts](https://joplinapp.org/api/references/plugin_api/classes/joplincontentscripts.html) or [webview scripts](https://joplinapp.org/api/references/plugin_api/classes/joplinviewspanels.html#addscript) you might want to compile them too, in particular in these two cases:
63 |
64 | - The script is a TypeScript file - in which case it has to be compiled to JavaScript.
65 |
66 | - The script requires modules you've added to package.json. In that case, the script, whether JS or TS, must be compiled so that the dependencies are bundled with the JPL file.
67 |
68 | To get such an external script file to compile, you need to add it to the `extraScripts` array in `plugin.config.json`. The path you add should be relative to /src. For example, if you have a file in "/src/webviews/index.ts", the path should be set to "webviews/index.ts". Once compiled, the file will always be named with a .js extension. So you will get "webviews/index.js" in the plugin package, and that's the path you should use to reference the file.
69 |
70 | ## License
71 |
72 | MIT © Laurent Cozic
73 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Oskar Świda
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Joplin Markdown table calculations plugin
2 |
3 | ### NOTE: unfortunately, I'm not able to maintain this project anymore. There are couple of things which should be done (like moving it to newer formula library or better integration with the current Joplin API) but I won't be able to do it in any reasonable future.
4 |
5 | [Joplin editor](https://github.com/laurent22/joplin) plugin for making calculations in markdown tables. Inspired by an Emacs Org mode feature which allows to make TBLFM comments under the table and perform calculations.
6 |
7 | > IMPORTANT: This plugin is not a spreadsheet emulator and I'm not able to mimic whole spreadsheet functionality. If you need specific behaviours, please use your favourite spreadsheet package instead.
8 |
9 | ## References/thanks
10 |
11 | Big thanks to authors of two projects which are the calculation engine core:
12 |
13 | - [Markdown-it](https://github.com/markdown-it/markdown-it) with the wonderful Markdown parser, I've used it to locate and extract table data in a Markdown document.
14 | - [Hot formula parser](https://github.com/handsontable/formula-parser) - incredible useful library for evauating mathematical formulas.
15 |
16 | ## Features
17 |
18 | - Define table formulas in Markdown files
19 | - Recalculate all formulas in a file using custom command
20 |
21 | ## Usage: formula list
22 |
23 | To define a set of table formulas, you can add a special HTML comment below a given Markdown table (TBLFM is a tribute to an Emacs Org mode :) . Only **the first comment directly under the table** will be taken into account.
24 | You can use **TBLFM** or **TABLE_FORMULAS** strings to indicate formula list.
25 |
26 | ```markdown
27 | | Column A | Column B | Column C |
28 | | :------- | :------- | :------- |
29 | | 123 | 456 | 789 |
30 | | 0 | 0 | 0 |
31 |
32 | ```
33 |
34 | The comment can span multiple lines and contain multiple formulas separated by a semicolon. Formulas are calculated in the following order: first row then all its columns fron the left to the right, second row ... etc. Table cells are described using spreadsheet notation, columns designated with letters like A,B,C .. Z (and even more AA, AB etc.) and rows with integers 1,2,3 ... You can also use range notation like `A1:E23`. Moreover, `hot-formula-parser` contains also a big set of predefined functions which can be used in formulas.
35 | For list of the formula functions and their use, please look at: (however, I didn't check all of them).
36 |
37 | ## Usage: inline cell formulas
38 |
39 | There is also a possibility to define formulas directly inside the cell. To do so, you need to insert a special comment inside the cell content with **FM** or **FORMULA** indicator.
40 |
41 | ```markdown
42 | | Column A | Column B | Column C |
43 | | :------- | :------- | :--------------- |
44 | | 123 | 456 | 789 |
45 | | 0 | 0 | |
46 | ```
47 |
48 | **WARNING! If you use both cases in the same table, inline cell formulas are overwritten by the formulas put into the list below the table!**
49 |
50 | ## Plugin command
51 |
52 | The plugin registers `markdownCalculate` command and adds it to the editor toolbar (the `fa-square-root-alt` icon).
53 |
54 | ## Important Notes
55 |
56 | 1. WYSIWYG editor removes HTML comments, so you will loose formula definitions.
57 | 2. Table values are updated using internal `editor.setText` command, so you will be unable to undo changes.
58 | 3. Cell values are converted to float numbers. If conversion fail, the cell value will be returned as a string. However, you need to remember that strings like `7/18/2011 7:45:00 AM` will be properly parsed as float `7`. To use them as strings, they have to be written in double quote `"7/18/2011 7:45:00 AM"`.
59 |
60 | ## Building the plugin
61 |
62 | To build the plugin, simply run `npm run dist`.
63 |
--------------------------------------------------------------------------------
/api/Global.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import Joplin from './Joplin';
3 | /**
4 | * @ignore
5 | */
6 | export default class Global {
7 | private joplin_;
8 | private requireWhiteList_;
9 | constructor(implementation: any, plugin: Plugin, store: any);
10 | get joplin(): Joplin;
11 | private requireWhiteList;
12 | require(filePath: string): any;
13 | get process(): any;
14 | }
15 |
--------------------------------------------------------------------------------
/api/Joplin.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import JoplinData from './JoplinData';
3 | import JoplinPlugins from './JoplinPlugins';
4 | import JoplinWorkspace from './JoplinWorkspace';
5 | import JoplinFilters from './JoplinFilters';
6 | import JoplinCommands from './JoplinCommands';
7 | import JoplinViews from './JoplinViews';
8 | import JoplinInterop from './JoplinInterop';
9 | import JoplinSettings from './JoplinSettings';
10 | import JoplinContentScripts from './JoplinContentScripts';
11 | /**
12 | * This is the main entry point to the Joplin API. You can access various services using the provided accessors.
13 | *
14 | * **This is a beta API**
15 | *
16 | * Please note that the plugin API is relatively new and should be considered Beta state. Besides possible bugs, what it means is that there might be necessary breaking changes from one version to the next. Whenever such change is needed, best effort will be done to:
17 | *
18 | * - Maintain backward compatibility;
19 | * - When possible, deprecate features instead of removing them;
20 | * - Document breaking changes in the changelog;
21 | *
22 | * So if you are developing a plugin, please keep an eye on the changelog as everything will be in there with information about how to update your code. There won't be any major API rewrite or architecture changes, but possibly small tweaks like function signature change, type change, etc.
23 | *
24 | * Eventually, the plugin API will be versioned to make this process smoother.
25 | */
26 | export default class Joplin {
27 | private data_;
28 | private plugins_;
29 | private workspace_;
30 | private filters_;
31 | private commands_;
32 | private views_;
33 | private interop_;
34 | private settings_;
35 | private contentScripts_;
36 | constructor(implementation: any, plugin: Plugin, store: any);
37 | get data(): JoplinData;
38 | get plugins(): JoplinPlugins;
39 | get workspace(): JoplinWorkspace;
40 | get contentScripts(): JoplinContentScripts;
41 | /**
42 | * @ignore
43 | *
44 | * Not sure if it's the best way to hook into the app
45 | * so for now disable filters.
46 | */
47 | get filters(): JoplinFilters;
48 | get commands(): JoplinCommands;
49 | get views(): JoplinViews;
50 | get interop(): JoplinInterop;
51 | get settings(): JoplinSettings;
52 | }
53 |
--------------------------------------------------------------------------------
/api/JoplinCommands.d.ts:
--------------------------------------------------------------------------------
1 | import { Command } from './types';
2 | /**
3 | * This class allows executing or registering new Joplin commands. Commands
4 | * can be executed or associated with
5 | * {@link JoplinViewsToolbarButtons | toolbar buttons} or
6 | * {@link JoplinViewsMenuItems | menu items}.
7 | *
8 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command)
9 | *
10 | * ## Executing Joplin's internal commands
11 | *
12 | * It is also possible to execute internal Joplin's commands which, as of
13 | * now, are not well documented. You can find the list directly on GitHub
14 | * though at the following locations:
15 | *
16 | * * [Main screen commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/gui/MainScreen/commands)
17 | * * [Global commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/commands)
18 | * * [Editor commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/gui/NoteEditor/commands/editorCommandDeclarations.ts)
19 | *
20 | * To view what arguments are supported, you can open any of these files
21 | * and look at the `execute()` command.
22 | */
23 | export default class JoplinCommands {
24 | /**
25 | * desktop Executes the given
26 | * command.
27 | *
28 | * The command can take any number of arguments, and the supported
29 | * arguments will vary based on the command. For custom commands, this
30 | * is the `args` passed to the `execute()` function. For built-in
31 | * commands, you can find the supported arguments by checking the links
32 | * above.
33 | *
34 | * ```typescript
35 | * // Create a new note in the current notebook:
36 | * await joplin.commands.execute('newNote');
37 | *
38 | * // Create a new sub-notebook under the provided notebook
39 | * // Note: internally, notebooks are called "folders".
40 | * await joplin.commands.execute('newFolder', "SOME_FOLDER_ID");
41 | * ```
42 | */
43 | execute(commandName: string, ...args: any[]): Promise;
44 | /**
45 | * desktop Registers a new command.
46 | *
47 | * ```typescript
48 | * // Register a new commmand called "testCommand1"
49 | *
50 | * await joplin.commands.register({
51 | * name: 'testCommand1',
52 | * label: 'My Test Command 1',
53 | * iconName: 'fas fa-music',
54 | * execute: () => {
55 | * alert('Testing plugin command 1');
56 | * },
57 | * });
58 | * ```
59 | */
60 | register(command: Command): Promise;
61 | }
62 |
--------------------------------------------------------------------------------
/api/JoplinContentScripts.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import { ContentScriptType } from './types';
3 | export default class JoplinContentScripts {
4 | private plugin;
5 | constructor(plugin: Plugin);
6 | /**
7 | * Registers a new content script. Unlike regular plugin code, which runs in
8 | * a separate process, content scripts run within the main process code and
9 | * thus allow improved performances and more customisations in specific
10 | * cases. It can be used for example to load a Markdown or editor plugin.
11 | *
12 | * Note that registering a content script in itself will do nothing - it
13 | * will only be loaded in specific cases by the relevant app modules (eg.
14 | * the Markdown renderer or the code editor). So it is not a way to inject
15 | * and run arbitrary code in the app, which for safety and performance
16 | * reasons is not supported.
17 | *
18 | * The plugin generator provides a way to build any content script you might
19 | * want to package as well as its dependencies. See the [Plugin Generator
20 | * doc](https://github.com/laurent22/joplin/blob/dev/packages/generator-joplin/README.md)
21 | * for more information.
22 | *
23 | * * [View the renderer demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/content_script)
24 | * * [View the editor demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/codemirror_content_script)
25 | *
26 | * See also the [postMessage demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages)
27 | *
28 | * @param type Defines how the script will be used. See the type definition for more information about each supported type.
29 | * @param id A unique ID for the content script.
30 | * @param scriptPath Must be a path relative to the plugin main script. For example, if your file content_script.js is next to your index.ts file, you would set `scriptPath` to `"./content_script.js`.
31 | */
32 | register(type: ContentScriptType, id: string, scriptPath: string): Promise;
33 | /**
34 | * Listens to a messages sent from the content script using postMessage().
35 | * See {@link ContentScriptType} for more information as well as the
36 | * [postMessage
37 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages)
38 | */
39 | onMessage(contentScriptId: string, callback: any): Promise;
40 | }
41 |
--------------------------------------------------------------------------------
/api/JoplinData.d.ts:
--------------------------------------------------------------------------------
1 | import { Path } from './types';
2 | /**
3 | * This module provides access to the Joplin data API: https://joplinapp.org/api/references/rest_api/
4 | * This is the main way to retrieve data, such as notes, notebooks, tags, etc.
5 | * or to update them or delete them.
6 | *
7 | * This is also what you would use to search notes, via the `search` endpoint.
8 | *
9 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/simple)
10 | *
11 | * In general you would use the methods in this class as if you were using a REST API. There are four methods that map to GET, POST, PUT and DELETE calls.
12 | * And each method takes these parameters:
13 | *
14 | * * `path`: This is an array that represents the path to the resource in the form `["resouceName", "resourceId", "resourceLink"]` (eg. ["tags", ":id", "notes"]). The "resources" segment is the name of the resources you want to access (eg. "notes", "folders", etc.). If not followed by anything, it will refer to all the resources in that collection. The optional "resourceId" points to a particular resources within the collection. Finally, an optional "link" can be present, which links the resource to a collection of resources. This can be used in the API for example to retrieve all the notes associated with a tag.
15 | * * `query`: (Optional) The query parameters. In a URL, this is the part after the question mark "?". In this case, it should be an object with key/value pairs.
16 | * * `data`: (Optional) Applies to PUT and POST calls only. The request body contains the data you want to create or modify, for example the content of a note or folder.
17 | * * `files`: (Optional) Used to create new resources and associate them with files.
18 | *
19 | * Please refer to the [Joplin API documentation](https://joplinapp.org/api/references/rest_api/) for complete details about each call. As the plugin runs within the Joplin application **you do not need an authorisation token** to use this API.
20 | *
21 | * For example:
22 | *
23 | * ```typescript
24 | * // Get a note ID, title and body
25 | * const noteId = 'some_note_id';
26 | * const note = await joplin.data.get(['notes', noteId], { fields: ['id', 'title', 'body'] });
27 | *
28 | * // Get all folders
29 | * const folders = await joplin.data.get(['folders']);
30 | *
31 | * // Set the note body
32 | * await joplin.data.put(['notes', noteId], null, { body: "New note body" });
33 | *
34 | * // Create a new note under one of the folders
35 | * await joplin.data.post(['notes'], null, { body: "my new note", title: "some title", parent_id: folders[0].id });
36 | * ```
37 | */
38 | export default class JoplinData {
39 | private api_;
40 | private pathSegmentRegex_;
41 | private serializeApiBody;
42 | private pathToString;
43 | get(path: Path, query?: any): Promise;
44 | post(path: Path, query?: any, body?: any, files?: any[]): Promise;
45 | put(path: Path, query?: any, body?: any, files?: any[]): Promise;
46 | delete(path: Path, query?: any): Promise;
47 | }
48 |
--------------------------------------------------------------------------------
/api/JoplinFilters.d.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * @ignore
3 | *
4 | * Not sure if it's the best way to hook into the app
5 | * so for now disable filters.
6 | */
7 | export default class JoplinFilters {
8 | on(name: string, callback: Function): Promise;
9 | off(name: string, callback: Function): Promise;
10 | }
11 |
--------------------------------------------------------------------------------
/api/JoplinInterop.d.ts:
--------------------------------------------------------------------------------
1 | import { ExportModule, ImportModule } from './types';
2 | /**
3 | * Provides a way to create modules to import external data into Joplin or to export notes into any arbitrary format.
4 | *
5 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/json_export)
6 | *
7 | * To implement an import or export module, you would simply define an object with various event handlers that are called
8 | * by the application during the import/export process.
9 | *
10 | * See the documentation of the [[ExportModule]] and [[ImportModule]] for more information.
11 | *
12 | * You may also want to refer to the Joplin API documentation to see the list of properties for each item (note, notebook, etc.) - https://joplinapp.org/api/references/rest_api/
13 | */
14 | export default class JoplinInterop {
15 | registerExportModule(module: ExportModule): Promise;
16 | registerImportModule(module: ImportModule): Promise;
17 | }
18 |
--------------------------------------------------------------------------------
/api/JoplinPlugins.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import { ContentScriptType, Script } from './types';
3 | /**
4 | * This class provides access to plugin-related features.
5 | */
6 | export default class JoplinPlugins {
7 | private plugin;
8 | constructor(plugin: Plugin);
9 | /**
10 | * Registers a new plugin. This is the entry point when creating a plugin. You should pass a simple object with an `onStart` method to it.
11 | * That `onStart` method will be executed as soon as the plugin is loaded.
12 | *
13 | * ```typescript
14 | * joplin.plugins.register({
15 | * onStart: async function() {
16 | * // Run your plugin code here
17 | * }
18 | * });
19 | * ```
20 | */
21 | register(script: Script): Promise;
22 | /**
23 | * @deprecated Use joplin.contentScripts.register()
24 | */
25 | registerContentScript(type: ContentScriptType, id: string, scriptPath: string): Promise;
26 | }
27 |
--------------------------------------------------------------------------------
/api/JoplinSettings.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import { SettingItem, SettingSection } from './types';
3 | export interface ChangeEvent {
4 | /**
5 | * Setting keys that have been changed
6 | */
7 | keys: string[];
8 | }
9 | export declare type ChangeHandler = (event: ChangeEvent)=> void;
10 | /**
11 | * This API allows registering new settings and setting sections, as well as getting and setting settings. Once a setting has been registered it will appear in the config screen and be editable by the user.
12 | *
13 | * Settings are essentially key/value pairs.
14 | *
15 | * Note: Currently this API does **not** provide access to Joplin's built-in settings. This is by design as plugins that modify user settings could give unexpected results
16 | *
17 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/settings)
18 | */
19 | export default class JoplinSettings {
20 | private plugin_;
21 | constructor(plugin: Plugin);
22 | private get keyPrefix();
23 | private namespacedKey;
24 | /**
25 | * Registers a new setting. Note that registering a setting item is dynamic and will be gone next time Joplin starts.
26 | * What it means is that you need to register the setting every time the plugin starts (for example in the onStart event).
27 | * The setting value however will be preserved from one launch to the next so there is no risk that it will be lost even if for some
28 | * reason the plugin fails to start at some point.
29 | */
30 | registerSetting(key: string, settingItem: SettingItem): Promise;
31 | /**
32 | * Registers a new setting section. Like for registerSetting, it is dynamic and needs to be done every time the plugin starts.
33 | */
34 | registerSection(name: string, section: SettingSection): Promise;
35 | /**
36 | * Gets a setting value (only applies to setting you registered from your plugin)
37 | */
38 | value(key: string): Promise;
39 | /**
40 | * Sets a setting value (only applies to setting you registered from your plugin)
41 | */
42 | setValue(key: string, value: any): Promise;
43 | /**
44 | * Gets a global setting value, including app-specific settings and those set by other plugins.
45 | *
46 | * The list of available settings is not documented yet, but can be found by looking at the source code:
47 | *
48 | * https://github.com/laurent22/joplin/blob/dev/packages/lib/models/Setting.ts#L142
49 | */
50 | globalValue(key: string): Promise;
51 | /**
52 | * Called when one or multiple settings of your plugin have been changed.
53 | * - For performance reasons, this event is triggered with a delay.
54 | * - You will only get events for your own plugin settings.
55 | */
56 | onChange(handler: ChangeHandler): Promise;
57 | }
58 |
--------------------------------------------------------------------------------
/api/JoplinViews.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import JoplinViewsDialogs from './JoplinViewsDialogs';
3 | import JoplinViewsMenuItems from './JoplinViewsMenuItems';
4 | import JoplinViewsMenus from './JoplinViewsMenus';
5 | import JoplinViewsToolbarButtons from './JoplinViewsToolbarButtons';
6 | import JoplinViewsPanels from './JoplinViewsPanels';
7 | /**
8 | * This namespace provides access to view-related services.
9 | *
10 | * All view services provide a `create()` method which you would use to create the view object, whether it's a dialog, a toolbar button or a menu item.
11 | * In some cases, the `create()` method will return a [[ViewHandle]], which you would use to act on the view, for example to set certain properties or call some methods.
12 | */
13 | export default class JoplinViews {
14 | private store;
15 | private plugin;
16 | private dialogs_;
17 | private panels_;
18 | private menuItems_;
19 | private menus_;
20 | private toolbarButtons_;
21 | private implementation_;
22 | constructor(implementation: any, plugin: Plugin, store: any);
23 | get dialogs(): JoplinViewsDialogs;
24 | get panels(): JoplinViewsPanels;
25 | get menuItems(): JoplinViewsMenuItems;
26 | get menus(): JoplinViewsMenus;
27 | get toolbarButtons(): JoplinViewsToolbarButtons;
28 | }
29 |
--------------------------------------------------------------------------------
/api/JoplinViewsDialogs.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import { ButtonSpec, ViewHandle, DialogResult } from './types';
3 | /**
4 | * Allows creating and managing dialogs. A dialog is modal window that
5 | * contains a webview and a row of buttons. You can update the update the
6 | * webview using the `setHtml` method. Dialogs are hidden by default and
7 | * you need to call `open()` to open them. Once the user clicks on a
8 | * button, the `open` call will return an object indicating what button was
9 | * clicked on.
10 | *
11 | * ## Retrieving form values
12 | *
13 | * If your HTML content included one or more forms, a `formData` object
14 | * will also be included with the key/value for each form.
15 | *
16 | * ## Special button IDs
17 | *
18 | * The following buttons IDs have a special meaning:
19 | *
20 | * - `ok`, `yes`, `submit`, `confirm`: They are considered "submit" buttons
21 | * - `cancel`, `no`, `reject`: They are considered "dismiss" buttons
22 | *
23 | * This information is used by the application to determine what action
24 | * should be done when the user presses "Enter" or "Escape" within the
25 | * dialog. If they press "Enter", the first "submit" button will be
26 | * automatically clicked. If they press "Escape" the first "dismiss" button
27 | * will be automatically clicked.
28 | *
29 | * [View the demo
30 | * plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/dialog)
31 | */
32 | export default class JoplinViewsDialogs {
33 | private store;
34 | private plugin;
35 | private implementation_;
36 | constructor(implementation: any, plugin: Plugin, store: any);
37 | private controller;
38 | /**
39 | * Creates a new dialog
40 | */
41 | create(id: string): Promise;
42 | /**
43 | * Displays a message box with OK/Cancel buttons. Returns the button index that was clicked - "0" for OK and "1" for "Cancel"
44 | */
45 | showMessageBox(message: string): Promise;
46 | /**
47 | * Sets the dialog HTML content
48 | */
49 | setHtml(handle: ViewHandle, html: string): Promise;
50 | /**
51 | * Adds and loads a new JS or CSS files into the dialog.
52 | */
53 | addScript(handle: ViewHandle, scriptPath: string): Promise;
54 | /**
55 | * Sets the dialog buttons.
56 | */
57 | setButtons(handle: ViewHandle, buttons: ButtonSpec[]): Promise;
58 | /**
59 | * Opens the dialog
60 | */
61 | open(handle: ViewHandle): Promise;
62 | }
63 |
--------------------------------------------------------------------------------
/api/JoplinViewsMenuItems.d.ts:
--------------------------------------------------------------------------------
1 | import { CreateMenuItemOptions, MenuItemLocation } from './types';
2 | import Plugin from '../Plugin';
3 | /**
4 | * Allows creating and managing menu items.
5 | *
6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command)
7 | */
8 | export default class JoplinViewsMenuItems {
9 | private store;
10 | private plugin;
11 | constructor(plugin: Plugin, store: any);
12 | /**
13 | * Creates a new menu item and associate it with the given command. You can specify under which menu the item should appear using the `location` parameter.
14 | */
15 | create(id: string, commandName: string, location?: MenuItemLocation, options?: CreateMenuItemOptions): Promise;
16 | }
17 |
--------------------------------------------------------------------------------
/api/JoplinViewsMenus.d.ts:
--------------------------------------------------------------------------------
1 | import { MenuItem, MenuItemLocation } from './types';
2 | import Plugin from '../Plugin';
3 | /**
4 | * Allows creating menus.
5 | *
6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/menu)
7 | */
8 | export default class JoplinViewsMenus {
9 | private store;
10 | private plugin;
11 | constructor(plugin: Plugin, store: any);
12 | private registerCommandAccelerators;
13 | /**
14 | * Creates a new menu from the provided menu items and place it at the given location. As of now, it is only possible to place the
15 | * menu as a sub-menu of the application build-in menus.
16 | */
17 | create(id: string, label: string, menuItems: MenuItem[], location?: MenuItemLocation): Promise;
18 | }
19 |
--------------------------------------------------------------------------------
/api/JoplinViewsPanels.d.ts:
--------------------------------------------------------------------------------
1 | import Plugin from '../Plugin';
2 | import { ViewHandle } from './types';
3 | /**
4 | * Allows creating and managing view panels. View panels currently are
5 | * displayed at the right of the sidebar and allows displaying any HTML
6 | * content (within a webview) and update it in real-time. For example it
7 | * could be used to display a table of content for the active note, or
8 | * display various metadata or graph.
9 | *
10 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/toc)
11 | */
12 | export default class JoplinViewsPanels {
13 | private store;
14 | private plugin;
15 | constructor(plugin: Plugin, store: any);
16 | private controller;
17 | /**
18 | * Creates a new panel
19 | */
20 | create(id: string): Promise;
21 | /**
22 | * Sets the panel webview HTML
23 | */
24 | setHtml(handle: ViewHandle, html: string): Promise;
25 | /**
26 | * Adds and loads a new JS or CSS files into the panel.
27 | */
28 | addScript(handle: ViewHandle, scriptPath: string): Promise;
29 | /**
30 | * Called when a message is sent from the webview (using postMessage).
31 | *
32 | * To post a message from the webview to the plugin use:
33 | *
34 | * ```javascript
35 | * const response = await webviewApi.postMessage(message);
36 | * ```
37 | *
38 | * - `message` can be any JavaScript object, string or number
39 | * - `response` is whatever was returned by the `onMessage` handler
40 | *
41 | * Using this mechanism, you can have two-way communication between the
42 | * plugin and webview.
43 | *
44 | * See the [postMessage
45 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages) for more details.
46 | *
47 | */
48 | onMessage(handle: ViewHandle, callback: Function): Promise;
49 | /**
50 | * Shows the panel
51 | */
52 | show(handle: ViewHandle, show?: boolean): Promise;
53 | /**
54 | * Hides the panel
55 | */
56 | hide(handle: ViewHandle): Promise;
57 | /**
58 | * Tells whether the panel is visible or not
59 | */
60 | visible(handle: ViewHandle): Promise;
61 | }
62 |
--------------------------------------------------------------------------------
/api/JoplinViewsToolbarButtons.d.ts:
--------------------------------------------------------------------------------
1 | import { ToolbarButtonLocation } from './types';
2 | import Plugin from '../Plugin';
3 | /**
4 | * Allows creating and managing toolbar buttons.
5 | *
6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command)
7 | */
8 | export default class JoplinViewsToolbarButtons {
9 | private store;
10 | private plugin;
11 | constructor(plugin: Plugin, store: any);
12 | /**
13 | * Creates a new toolbar button and associate it with the given command.
14 | */
15 | create(id: string, commandName: string, location: ToolbarButtonLocation): Promise;
16 | }
17 |
--------------------------------------------------------------------------------
/api/JoplinWorkspace.d.ts:
--------------------------------------------------------------------------------
1 | import { FolderEntity } from '../../database/types';
2 | import { Disposable } from './types';
3 | declare enum ItemChangeEventType {
4 | Create = 1,
5 | Update = 2,
6 | Delete = 3,
7 | }
8 | interface ItemChangeEvent {
9 | id: string;
10 | event: ItemChangeEventType;
11 | }
12 | interface SyncStartEvent {
13 | withErrors: boolean;
14 | }
15 | declare type ItemChangeHandler = (event: ItemChangeEvent)=> void;
16 | declare type SyncStartHandler = (event: SyncStartEvent)=> void;
17 | /**
18 | * The workspace service provides access to all the parts of Joplin that
19 | * are being worked on - i.e. the currently selected notes or notebooks as
20 | * well as various related events, such as when a new note is selected, or
21 | * when the note content changes.
22 | *
23 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins)
24 | */
25 | export default class JoplinWorkspace {
26 | private store;
27 | constructor(store: any);
28 | /**
29 | * Called when a new note or notes are selected.
30 | */
31 | onNoteSelectionChange(callback: Function): Promise;
32 | /**
33 | * Called when the content of a note changes.
34 | * @deprecated Use `onNoteChange()` instead, which is reliably triggered whenever the note content, or any note property changes.
35 | */
36 | onNoteContentChange(callback: Function): Promise;
37 | /**
38 | * Called when the content of a note changes.
39 | */
40 | onNoteChange(handler: ItemChangeHandler): Promise;
41 | /**
42 | * Called when an alarm associated with a to-do is triggered.
43 | */
44 | onNoteAlarmTrigger(handler: Function): Promise;
45 | /**
46 | * Called when the synchronisation process is starting.
47 | */
48 | onSyncStart(handler: SyncStartHandler): Promise;
49 | /**
50 | * Called when the synchronisation process has finished.
51 | */
52 | onSyncComplete(callback: Function): Promise;
53 | /**
54 | * Gets the currently selected note
55 | */
56 | selectedNote(): Promise;
57 | /**
58 | * Gets the currently selected folder. In some cases, for example during
59 | * search or when viewing a tag, no folder is actually selected in the user
60 | * interface. In that case, that function would return the last selected
61 | * folder.
62 | */
63 | selectedFolder(): Promise;
64 | /**
65 | * Gets the IDs of the selected notes (can be zero, one, or many). Use the data API to retrieve information about these notes.
66 | */
67 | selectedNoteIds(): Promise;
68 | }
69 | export {};
70 |
--------------------------------------------------------------------------------
/api/index.ts:
--------------------------------------------------------------------------------
1 | import type Joplin from './Joplin';
2 |
3 | declare const joplin: Joplin;
4 |
5 | export default joplin;
6 |
--------------------------------------------------------------------------------
/api/types.ts:
--------------------------------------------------------------------------------
1 | // =================================================================
2 | // Command API types
3 | // =================================================================
4 |
5 | export interface Command {
6 | /**
7 | * Name of command - must be globally unique
8 | */
9 | name: string;
10 |
11 | /**
12 | * Label to be displayed on menu items or keyboard shortcut editor for example.
13 | * If it is missing, it's assumed it's a private command, to be called programmatically only.
14 | * In that case the command will not appear in the shortcut editor or command panel, and logically
15 | * should not be used as a menu item.
16 | */
17 | label?: string;
18 |
19 | /**
20 | * Icon to be used on toolbar buttons for example
21 | */
22 | iconName?: string;
23 |
24 | /**
25 | * Code to be ran when the command is executed. It may return a result.
26 | */
27 | execute(...args: any[]): Promise;
28 |
29 | /**
30 | * Defines whether the command should be enabled or disabled, which in turns affects
31 | * the enabled state of any associated button or menu item.
32 | *
33 | * The condition should be expressed as a "when-clause" (as in Visual Studio Code). It's a simple boolean expression that evaluates to
34 | * `true` or `false`. It supports the following operators:
35 | *
36 | * Operator | Symbol | Example
37 | * -- | -- | --
38 | * Equality | == | "editorType == markdown"
39 | * Inequality | != | "currentScreen != config"
40 | * Or | \|\| | "noteIsTodo \|\| noteTodoCompleted"
41 | * And | && | "oneNoteSelected && !inConflictFolder"
42 | *
43 | * Currently the supported context variables aren't documented, but you can [find the list here](https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts).
44 | *
45 | * Note: Commands are enabled by default unless you use this property.
46 | */
47 | enabledCondition?: string;
48 | }
49 |
50 | // =================================================================
51 | // Interop API types
52 | // =================================================================
53 |
54 | export enum FileSystemItem {
55 | File = 'file',
56 | Directory = 'directory',
57 | }
58 |
59 | export enum ImportModuleOutputFormat {
60 | Markdown = 'md',
61 | Html = 'html',
62 | }
63 |
64 | /**
65 | * Used to implement a module to export data from Joplin. [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/json_export) for an example.
66 | *
67 | * In general, all the event handlers you'll need to implement take a `context` object as a first argument. This object will contain the export or import path as well as various optional properties, such as which notes or notebooks need to be exported.
68 | *
69 | * To get a better sense of what it will contain it can be useful to print it using `console.info(context)`.
70 | */
71 | export interface ExportModule {
72 | /**
73 | * The format to be exported, eg "enex", "jex", "json", etc.
74 | */
75 | format: string;
76 |
77 | /**
78 | * The description that will appear in the UI, for example in the menu item.
79 | */
80 | description: string;
81 |
82 | /**
83 | * Whether the module will export a single file or multiple files in a directory. It affects the open dialog that will be presented to the user when using your exporter.
84 | */
85 | target: FileSystemItem;
86 |
87 | /**
88 | * Only applies to single file exporters or importers
89 | * It tells whether the format can package multiple notes into one file.
90 | * For example JEX or ENEX can, but HTML cannot.
91 | */
92 | isNoteArchive: boolean;
93 |
94 | /**
95 | * The extensions of the files exported by your module. For example, it is `["htm", "html"]` for the HTML module, and just `["jex"]` for the JEX module.
96 | */
97 | fileExtensions?: string[];
98 |
99 | /**
100 | * Called when the export process starts.
101 | */
102 | onInit(context: ExportContext): Promise;
103 |
104 | /**
105 | * Called when an item needs to be processed. An "item" can be any Joplin object, such as a note, a folder, a notebook, etc.
106 | */
107 | onProcessItem(context: ExportContext, itemType: number, item: any): Promise;
108 |
109 | /**
110 | * Called when a resource file needs to be exported.
111 | */
112 | onProcessResource(context: ExportContext, resource: any, filePath: string): Promise;
113 |
114 | /**
115 | * Called when the export process is done.
116 | */
117 | onClose(context: ExportContext): Promise;
118 | }
119 |
120 | export interface ImportModule {
121 | /**
122 | * The format to be exported, eg "enex", "jex", "json", etc.
123 | */
124 | format: string;
125 |
126 | /**
127 | * The description that will appear in the UI, for example in the menu item.
128 | */
129 | description: string;
130 |
131 | /**
132 | * Only applies to single file exporters or importers
133 | * It tells whether the format can package multiple notes into one file.
134 | * For example JEX or ENEX can, but HTML cannot.
135 | */
136 | isNoteArchive: boolean;
137 |
138 | /**
139 | * The type of sources that are supported by the module. Tells whether the module can import files or directories or both.
140 | */
141 | sources: FileSystemItem[];
142 |
143 | /**
144 | * Tells the file extensions of the exported files.
145 | */
146 | fileExtensions?: string[];
147 |
148 | /**
149 | * Tells the type of notes that will be generated, either HTML or Markdown (default).
150 | */
151 | outputFormat?: ImportModuleOutputFormat;
152 |
153 | /**
154 | * Called when the import process starts. There is only one event handler within which you should import the complete data.
155 | */
156 | onExec(context: ImportContext): Promise;
157 | }
158 |
159 | export interface ExportOptions {
160 | format?: string;
161 | path?: string;
162 | sourceFolderIds?: string[];
163 | sourceNoteIds?: string[];
164 | // modulePath?: string;
165 | target?: FileSystemItem;
166 | }
167 |
168 | export interface ExportContext {
169 | destPath: string;
170 | options: ExportOptions;
171 |
172 | /**
173 | * You can attach your own custom data using this propery - it will then be passed to each event handler, allowing you to keep state from one event to the next.
174 | */
175 | userData?: any;
176 | }
177 |
178 | export interface ImportContext {
179 | sourcePath: string;
180 | options: any;
181 | warnings: string[];
182 | }
183 |
184 | // =================================================================
185 | // Misc types
186 | // =================================================================
187 |
188 | export interface Script {
189 | onStart?(event: any): Promise;
190 | }
191 |
192 | export interface Disposable {
193 | // dispose():void;
194 | }
195 |
196 | // =================================================================
197 | // Menu types
198 | // =================================================================
199 |
200 | export interface CreateMenuItemOptions {
201 | accelerator: string;
202 | }
203 |
204 | export enum MenuItemLocation {
205 | File = 'file',
206 | Edit = 'edit',
207 | View = 'view',
208 | Note = 'note',
209 | Tools = 'tools',
210 | Help = 'help',
211 |
212 | /**
213 | * @deprecated Do not use - same as NoteListContextMenu
214 | */
215 | Context = 'context',
216 |
217 | // If adding an item here, don't forget to update isContextMenuItemLocation()
218 |
219 | /**
220 | * When a command is called from the note list context menu, the
221 | * command will receive the following arguments:
222 | *
223 | * - `noteIds:string[]`: IDs of the notes that were right-clicked on.
224 | */
225 | NoteListContextMenu = 'noteListContextMenu',
226 |
227 | EditorContextMenu = 'editorContextMenu',
228 |
229 | /**
230 | * When a command is called from a folder context menu, the
231 | * command will receive the following arguments:
232 | *
233 | * - `folderId:string`: ID of the folder that was right-clicked on
234 | */
235 | FolderContextMenu = 'folderContextMenu',
236 |
237 | /**
238 | * When a command is called from a tag context menu, the
239 | * command will receive the following arguments:
240 | *
241 | * - `tagId:string`: ID of the tag that was right-clicked on
242 | */
243 | TagContextMenu = 'tagContextMenu',
244 | }
245 |
246 | export function isContextMenuItemLocation(location: MenuItemLocation): boolean {
247 | return [
248 | MenuItemLocation.Context,
249 | MenuItemLocation.NoteListContextMenu,
250 | MenuItemLocation.EditorContextMenu,
251 | MenuItemLocation.FolderContextMenu,
252 | MenuItemLocation.TagContextMenu,
253 | ].includes(location);
254 | }
255 |
256 | export interface MenuItem {
257 | /**
258 | * Command that should be associated with the menu item. All menu item should
259 | * have a command associated with them unless they are a sub-menu.
260 | */
261 | commandName?: string;
262 |
263 | /**
264 | * Accelerator associated with the menu item
265 | */
266 | accelerator?: string;
267 |
268 | /**
269 | * Menu items that should appear below this menu item. Allows creating a menu tree.
270 | */
271 | submenu?: MenuItem[];
272 |
273 | /**
274 | * Menu item label. If not specified, the command label will be used instead.
275 | */
276 | label?: string;
277 | }
278 |
279 | // =================================================================
280 | // View API types
281 | // =================================================================
282 |
283 | export interface ButtonSpec {
284 | id: ButtonId;
285 | title?: string;
286 | onClick?(): void;
287 | }
288 |
289 | export type ButtonId = string;
290 |
291 | export enum ToolbarButtonLocation {
292 | /**
293 | * This toolbar in the top right corner of the application. It applies to the note as a whole, including its metadata.
294 | */
295 | NoteToolbar = 'noteToolbar',
296 |
297 | /**
298 | * This toolbar is right above the text editor. It applies to the note body only.
299 | */
300 | EditorToolbar = 'editorToolbar',
301 | }
302 |
303 | export type ViewHandle = string;
304 |
305 | export interface EditorCommand {
306 | name: string;
307 | value?: any;
308 | }
309 |
310 | export interface DialogResult {
311 | id: ButtonId;
312 | formData?: any;
313 | }
314 |
315 | // =================================================================
316 | // Settings types
317 | // =================================================================
318 |
319 | export enum SettingItemType {
320 | Int = 1,
321 | String = 2,
322 | Bool = 3,
323 | Array = 4,
324 | Object = 5,
325 | Button = 6,
326 | }
327 |
328 | // Redefine a simplified interface to mask internal details
329 | // and to remove function calls as they would have to be async.
330 | export interface SettingItem {
331 | value: any;
332 | type: SettingItemType;
333 | public: boolean;
334 | label: string;
335 |
336 | description?: string;
337 | isEnum?: boolean;
338 | section?: string;
339 | options?: any;
340 | appTypes?: string[];
341 | secure?: boolean;
342 | advanced?: boolean;
343 | minimum?: number;
344 | maximum?: number;
345 | step?: number;
346 | }
347 |
348 | export interface SettingSection {
349 | label: string;
350 | iconName?: string;
351 | description?: string;
352 | name?: string;
353 | }
354 |
355 | // =================================================================
356 | // Data API types
357 | // =================================================================
358 |
359 | /**
360 | * An array of at least one element and at most three elements.
361 | *
362 | * - **[0]**: Resource name (eg. "notes", "folders", "tags", etc.)
363 | * - **[1]**: (Optional) Resource ID.
364 | * - **[2]**: (Optional) Resource link.
365 | */
366 | export type Path = string[];
367 |
368 | // =================================================================
369 | // Content Script types
370 | // =================================================================
371 |
372 | export type PostMessageHandler = (id: string, message: any)=> Promise;
373 |
374 | /**
375 | * When a content script is initialised, it receives a `context` object.
376 | */
377 | export interface ContentScriptContext {
378 | /**
379 | * The plugin ID that registered this content script
380 | */
381 | pluginId: string;
382 |
383 | /**
384 | * The content script ID, which may be necessary to post messages
385 | */
386 | contentScriptId: string;
387 |
388 | /**
389 | * Can be used by CodeMirror content scripts to post a message to the plugin
390 | */
391 | postMessage: PostMessageHandler;
392 | }
393 |
394 | export enum ContentScriptType {
395 | /**
396 | * Registers a new Markdown-It plugin, which should follow the template
397 | * below.
398 | *
399 | * ```javascript
400 | * module.exports = {
401 | * default: function(context) {
402 | * return {
403 | * plugin: function(markdownIt, options) {
404 | * // ...
405 | * },
406 | * assets: {
407 | * // ...
408 | * },
409 | * }
410 | * }
411 | * }
412 | * ```
413 | * See [the
414 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/content_script)
415 | * for a simple Markdown-it plugin example.
416 | *
417 | * ## Exported members
418 | *
419 | * - The `context` argument is currently unused but could be used later on
420 | * to provide access to your own plugin so that the content script and
421 | * plugin can communicate.
422 | *
423 | * - The **required** `plugin` key is the actual Markdown-It plugin - check
424 | * the [official doc](https://github.com/markdown-it/markdown-it) for more
425 | * information. The `options` parameter is of type
426 | * [RuleOptions](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml.ts),
427 | * which contains a number of options, mostly useful for Joplin's internal
428 | * code.
429 | *
430 | * - Using the **optional** `assets` key you may specify assets such as JS
431 | * or CSS that should be loaded in the rendered HTML document. Check for
432 | * example the Joplin [Mermaid
433 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts)
434 | * to see how the data should be structured.
435 | *
436 | * ## Posting messages from the content script to your plugin
437 | *
438 | * The application provides the following function to allow executing
439 | * commands from the rendered HTML code:
440 | *
441 | * ```javascript
442 | * const response = await webviewApi.postMessage(contentScriptId, message);
443 | * ```
444 | *
445 | * - `contentScriptId` is the ID you've defined when you registered the
446 | * content script. You can retrieve it from the
447 | * {@link ContentScriptContext | context}.
448 | * - `message` can be any basic JavaScript type (number, string, plain
449 | * object), but it cannot be a function or class instance.
450 | *
451 | * When you post a message, the plugin can send back a `response` thus
452 | * allowing two-way communication:
453 | *
454 | * ```javascript
455 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => {
456 | * // Process message
457 | * return response; // Can be any object, string or number
458 | * });
459 | * ```
460 | *
461 | * See {@link JoplinContentScripts.onMessage} for more details, as well as
462 | * the [postMessage
463 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages).
464 | *
465 | * ## Registering an existing Markdown-it plugin
466 | *
467 | * To include a regular Markdown-It plugin, that doesn't make use of any
468 | * Joplin-specific features, you would simply create a file such as this:
469 | *
470 | * ```javascript
471 | * module.exports = {
472 | * default: function(context) {
473 | * return {
474 | * plugin: require('markdown-it-toc-done-right');
475 | * }
476 | * }
477 | * }
478 | * ```
479 | */
480 | MarkdownItPlugin = 'markdownItPlugin',
481 |
482 | /**
483 | * Registers a new CodeMirror plugin, which should follow the template
484 | * below.
485 | *
486 | * ```javascript
487 | * module.exports = {
488 | * default: function(context) {
489 | * return {
490 | * plugin: function(CodeMirror) {
491 | * // ...
492 | * },
493 | * codeMirrorResources: [],
494 | * codeMirrorOptions: {
495 | * // ...
496 | * },
497 | * assets: {
498 | * // ...
499 | * },
500 | * }
501 | * }
502 | * }
503 | * ```
504 | *
505 | * - The `context` argument is currently unused but could be used later on
506 | * to provide access to your own plugin so that the content script and
507 | * plugin can communicate.
508 | *
509 | * - The `plugin` key is your CodeMirror plugin. This is where you can
510 | * register new commands with CodeMirror or interact with the CodeMirror
511 | * instance as needed.
512 | *
513 | * - The `codeMirrorResources` key is an array of CodeMirror resources that
514 | * will be loaded and attached to the CodeMirror module. These are made up
515 | * of addons, keymaps, and modes. For example, for a plugin that want's to
516 | * enable clojure highlighting in code blocks. `codeMirrorResources` would
517 | * be set to `['mode/clojure/clojure']`.
518 | *
519 | * - The `codeMirrorOptions` key contains all the
520 | * [CodeMirror](https://codemirror.net/doc/manual.html#config) options
521 | * that will be set or changed by this plugin. New options can alse be
522 | * declared via
523 | * [`CodeMirror.defineOption`](https://codemirror.net/doc/manual.html#defineOption),
524 | * and then have their value set here. For example, a plugin that enables
525 | * line numbers would set `codeMirrorOptions` to `{'lineNumbers': true}`.
526 | *
527 | * - Using the **optional** `assets` key you may specify **only** CSS assets
528 | * that should be loaded in the rendered HTML document. Check for example
529 | * the Joplin [Mermaid
530 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts)
531 | * to see how the data should be structured.
532 | *
533 | * One of the `plugin`, `codeMirrorResources`, or `codeMirrorOptions` keys
534 | * must be provided for the plugin to be valid. Having multiple or all
535 | * provided is also okay.
536 | *
537 | * See also the [demo
538 | * plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/codemirror_content_script)
539 | * for an example of all these keys being used in one plugin.
540 | *
541 | * ## Posting messages from the content script to your plugin
542 | *
543 | * In order to post messages to the plugin, you can use the postMessage
544 | * function passed to the {@link ContentScriptContext | context}.
545 | *
546 | * ```javascript
547 | * const response = await context.postMessage('messageFromCodeMirrorContentScript');
548 | * ```
549 | *
550 | * When you post a message, the plugin can send back a `response` thus
551 | * allowing two-way communication:
552 | *
553 | * ```javascript
554 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => {
555 | * // Process message
556 | * return response; // Can be any object, string or number
557 | * });
558 | * ```
559 | *
560 | * See {@link JoplinContentScripts.onMessage} for more details, as well as
561 | * the [postMessage
562 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages).
563 | *
564 | */
565 | CodeMirrorPlugin = 'codeMirrorPlugin',
566 | }
567 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "roots": [
3 | "/src"
4 | ],
5 | "testMatch": [
6 | "**/__tests__/**/*.+(ts|tsx|js)",
7 | "**/?(*.)+(spec|test).+(ts|tsx|js)"
8 | ],
9 | "transform": {
10 | "^.+\\.(ts|tsx)$": "ts-jest"
11 | },
12 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "joplin-plugin-markdown-calc",
3 | "version": "1.0.5",
4 | "description": "Plugin for automatic calculations of markdown table formulas.",
5 | "scripts": {
6 | "dist": "webpack --joplin-plugin-config buildMain && webpack --joplin-plugin-config buildExtraScripts && webpack --joplin-plugin-config createArchive",
7 | "test": "jest",
8 | "prepare": "npm run dist",
9 | "update": "npm install -g generator-joplin && yo joplin --update"
10 | },
11 | "keywords": [
12 | "joplin-plugin"
13 | ],
14 | "author": "Oskar Świda",
15 | "license": "MIT",
16 | "devDependencies": {
17 | "@types/jest": "^26.0.15",
18 | "@types/node": "^14.0.14",
19 | "copy-webpack-plugin": "^6.1.0",
20 | "jest": "^26.6.3",
21 | "ts-jest": "^26.4.4",
22 | "ts-loader": "^7.0.5",
23 | "typescript": "^3.9.3",
24 | "webpack": "^4.43.0",
25 | "webpack-cli": "^3.3.11",
26 | "chalk": "^4.1.0",
27 | "fs-extra": "^9.0.1",
28 | "glob": "^7.1.6",
29 | "on-build-webpack": "^0.1.0",
30 | "tar": "^6.0.5",
31 | "yargs": "^16.2.0"
32 | },
33 | "dependencies": {
34 | "@types/markdown-it": "^10.0.3",
35 | "hot-formula-parser": "^4.0.0",
36 | "markdown-it": "^12.0.2"
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/plugin.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "extraScripts": []
3 | }
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import joplin from "api";
2 | import { ToolbarButtonLocation } from "api/types";
3 | import { TableCalculator } from "./lib/calc";
4 |
5 | // Register plugin
6 | joplin.plugins.register({
7 | onStart: async function () {
8 | async function calculate() {
9 | const note = await joplin.workspace.selectedNote();
10 | if (!note) {
11 | alert("Please select a note.");
12 | return;
13 | }
14 | const calc = new TableCalculator();
15 | // Fetch tables
16 | const body_lines = calc.prepareTables(note.body as string);
17 | // Execute calculations
18 | calc.execute(body_lines);
19 | // update note body
20 | const newBody = body_lines.join("\n");
21 | await joplin.commands.execute("editor.setText", newBody);
22 | await joplin.data.put(["notes", note.id], null, { body: newBody });
23 | await joplin.commands.execute("editor.focus");
24 | }
25 |
26 | // Register new command
27 | await joplin.commands.register({
28 | name: "markdownCalculate",
29 | label: "Calculate table formulas",
30 | iconName: "fas fa-square-root-alt",
31 | execute: async () => {
32 | await calculate();
33 | },
34 | });
35 |
36 | joplin.views.toolbarButtons.create(
37 | "markdownCalculateBtn",
38 | "markdownCalculate",
39 | ToolbarButtonLocation.EditorToolbar
40 | );
41 | },
42 | });
43 |
--------------------------------------------------------------------------------
/src/lib/calc.ts:
--------------------------------------------------------------------------------
1 | import MarkdownIt = require("markdown-it");
2 | import { TableParser } from "./parser";
3 | import { MTTable } from "./table";
4 |
5 | // Markdown table formula calculator.
6 | export class TableCalculator {
7 | tables: MTTable[] = [];
8 | tblpos: { [id: number]: MTTable } = {};
9 |
10 | // Prepare tables and formulas
11 | prepareTables(body: string): string[] {
12 | const md = new MarkdownIt({ html: true });
13 | const data = md.parse(body, {});
14 | const body_lines = body.split("\n");
15 | for (let i = 0; i < data.length; i++) {
16 | if (data[i].type === "tbody_open") {
17 | // end line in a map points to the line AFTER the table
18 | this.addTable(data[i].map[0], data[i].map[1] - 1, body_lines);
19 | } else if (data[i].type === "html_block") {
20 | this.checkFormulaList(data[i].map[0], data[i].content);
21 | } else if (data[i].type === "fence" && data[i].tag === "code") {
22 | // parse table inside code block (no recursion)
23 | const block_data = md.parse(data[i].content, {});
24 | for (let j = 0; j < block_data.length; j++) {
25 | if (block_data[j].type === "tbody_open") {
26 | this.addTable(
27 | data[i].map[0] + block_data[j].map[0] + 1,
28 | data[i].map[0] + block_data[j].map[1],
29 | body_lines
30 | );
31 | } else if (block_data[j].type === "html_block") {
32 | this.checkFormulaList(
33 | data[i].map[0] + block_data[j].map[0] + 1,
34 | block_data[j].content
35 | );
36 | }
37 | }
38 | }
39 | }
40 | return body_lines;
41 | }
42 |
43 | // Add a table for processing.
44 | addTable(sline: number, eline: number, body: string[]) {
45 | const table = new MTTable(sline, eline);
46 | this.tables.push(table);
47 | this.tblpos[eline] = table;
48 | table.parse(body);
49 | }
50 |
51 | // Execute calculations.
52 | execute(body: string[]) {
53 | for (let i = 0; i < this.tables.length; i++) {
54 | this.processTable(this.tables[i], body);
55 | }
56 | }
57 |
58 | // Process a single table and update note body.
59 | processTable(table: MTTable, body: string[]) {
60 | const parser = new TableParser(table);
61 | for (let r = 0; r < table.rows.length; r++) {
62 | for (let c = 0; c < table.rows[r].cells.length; c++) {
63 | const cell = table.rows[r].cells[c];
64 | if (cell.formula) {
65 | cell.value = parser.parse(cell.formula);
66 | }
67 | }
68 | }
69 | table.update(body);
70 | }
71 |
72 | // Check if a comment can be a formula list.
73 | // If positive - parse the comment.
74 | // Formula comment has to be placed at the next line after the table.
75 | checkFormulaList(line: number, data: string) {
76 | const table = this.tblpos[line - 1];
77 | if (table) {
78 | table.parseList(data);
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/lib/parser.ts:
--------------------------------------------------------------------------------
1 | import { CellCoordinate, MTTable } from "./table";
2 |
3 | let FormulaParser = require("hot-formula-parser").Parser;
4 |
5 | interface CalcResult {
6 | result: any;
7 | error: any;
8 | }
9 |
10 | // Formula parser wrapper.
11 | export class TableParser {
12 | parser: typeof FormulaParser;
13 | table: MTTable;
14 |
15 | constructor(table: MTTable) {
16 | this.table = table;
17 | const self = this;
18 | this.parser = new FormulaParser();
19 | this.parser.on("callCellValue", (cellCoord: CellCoordinate, done: any) => {
20 | const value = self.table.get(cellCoord);
21 | done(value);
22 | });
23 | this.parser.on(
24 | "callRangeValue",
25 | (
26 | startCellCoord: CellCoordinate,
27 | endCellCoord: CellCoordinate,
28 | done: any
29 | ) => {
30 | const fragment = self.table.getfragment(startCellCoord, endCellCoord);
31 | done(fragment);
32 | }
33 | );
34 | }
35 |
36 | parse(frm: string): string {
37 | let res: CalcResult = this.parser.parse(frm);
38 | if (res.error == null) {
39 | return String(res.result);
40 | } else {
41 | return String(res.error);
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/lib/table.ts:
--------------------------------------------------------------------------------
1 | import Token = require("markdown-it/lib/token");
2 | import { extractLabel } from "hot-formula-parser";
3 |
4 | export const CELL_DELIMITER = "|";
5 | export const FORMULA_REGEXP: RegExp = /(.*)(.*)/g;
6 | export const FORMULA_LIST_REGEXP: RegExp = //g;
7 | export const FORMULA_SEP = ";";
8 |
9 | // Cell coordinate type used by a parser
10 | export interface Coordinate {
11 | index: number;
12 | label: string;
13 | isAbsolute: boolean;
14 | }
15 |
16 | export interface CellCoordinate {
17 | label: string;
18 | row: Coordinate;
19 | column: Coordinate;
20 | }
21 |
22 | // Markdown table cell
23 | export interface MTCell {
24 | value: string; // cell value
25 | formula: string | null; // formula inside the cell
26 | formulaPrefix: string | null; // only for replace purposes
27 | }
28 |
29 | // Markdown table row
30 | export class MTRow {
31 | cells: MTCell[] = [];
32 |
33 | parse(data: string, line: number) {
34 | const parts = data.split(CELL_DELIMITER);
35 | for (let i = 1; i < parts.length - 1; i++) {
36 | let cvalue = parts[i];
37 | let frm = null;
38 | let frmpx = null;
39 | FORMULA_REGEXP.lastIndex = 0; // reset if reuse
40 | // find formula
41 | const rx = FORMULA_REGEXP.exec(parts[i]);
42 | if (rx && rx.length == 5) {
43 | frm = rx[3].trim();
44 | cvalue = "";
45 | // Only one value present is taken into consideration
46 | if (rx[1].trim() != "") {
47 | cvalue = rx[1].trim();
48 | } else if (rx[4].trim() != "") {
49 | cvalue = rx[4].trim();
50 | }
51 | frmpx = rx[2];
52 | }
53 | this.cells.push({
54 | value: cvalue,
55 | formula: frm,
56 | formulaPrefix: frmpx,
57 | });
58 | }
59 | }
60 |
61 | // Serialize to markdown text.
62 | serialize() {
63 | const values = this.cells.map((it) => {
64 | if (it.formula && it.formulaPrefix) {
65 | return ` ${it.value}`;
66 | } else {
67 | return it.value;
68 | }
69 | });
70 | return CELL_DELIMITER + values.join(CELL_DELIMITER) + CELL_DELIMITER;
71 | }
72 | }
73 |
74 | // Markdown table
75 | export class MTTable {
76 | rows: MTRow[] = [];
77 | startLine: number;
78 | endLine: number;
79 |
80 | // Only table body lines are taken into account
81 | constructor(sline: number, eline: number) {
82 | this.startLine = sline;
83 | this.endLine = eline;
84 | }
85 |
86 | // Parse table rows from the whole note data
87 | parse(data: string[]) {
88 | for (let i = this.startLine; i <= this.endLine; i++) {
89 | const row = new MTRow();
90 | row.parse(data[i], this.startLine + i);
91 | this.rows.push(row);
92 | }
93 | }
94 |
95 | // Parse formulas taken from a comment below the table.
96 | // WARNING: formula list definitions override inline cell formulas!
97 | parseList(comment: string) {
98 | FORMULA_LIST_REGEXP.lastIndex = 0; // reset regex before reuse
99 | const rx = FORMULA_LIST_REGEXP.exec(comment);
100 | if (rx && rx.length == 3) {
101 | const flist = rx[2].split(FORMULA_SEP);
102 | flist.forEach((f: string) => {
103 | const parts = f.trim().split("=");
104 | if (parts && parts.length == 2) {
105 | const cell = this.findCell(parts[0].trim());
106 | if (cell) {
107 | cell.formula = parts[1].trim();
108 | cell.formulaPrefix = null;
109 | }
110 | }
111 | });
112 | }
113 | }
114 |
115 | // Find cell with a given label.
116 | findCell(id: string): MTCell | null {
117 | const coords = extractLabel(id) as Coordinate[];
118 | const rowidx = coords[0].index;
119 | const colidx = coords[1].index;
120 | if ((rowidx as number) >= this.rows.length) {
121 | return null;
122 | }
123 | const row = this.rows[rowidx];
124 | if ((colidx as number) >= row.cells.length) {
125 | return null;
126 | }
127 | return row.cells[colidx];
128 | }
129 |
130 | // Find cell with a given label and return CellCoordinate.
131 | cellCoordinate(id: string): CellCoordinate {
132 | const coords = extractLabel(id) as Coordinate[];
133 | return { row: coords[0], column: coords[1], label: id } as CellCoordinate;
134 | }
135 |
136 | // Get data from a given coordinate, convert to number
137 | get(coord: CellCoordinate): number | string {
138 | const rowidx = coord.row.index;
139 | const colidx = coord.column.index;
140 | const strval = this.getat(rowidx, colidx);
141 | const value = Number.parseFloat(strval);
142 | if (!Number.isNaN(value)) {
143 | return value;
144 | }
145 | return strval;
146 | }
147 |
148 | getfragment(
149 | startCellCoord: CellCoordinate,
150 | endCellCoord: CellCoordinate
151 | ): string[] {
152 | let fragment = [];
153 | for (
154 | var row = startCellCoord.row.index;
155 | row <= endCellCoord.row.index;
156 | row++
157 | ) {
158 | var colFragment = [];
159 |
160 | for (
161 | var col = startCellCoord.column.index;
162 | col <= endCellCoord.column.index;
163 | col++
164 | ) {
165 | const strval = this.getat(row, col);
166 | const value = Number.parseFloat(strval);
167 | if (!Number.isNaN(value)) {
168 | colFragment.push(value);
169 | } else {
170 | colFragment.push(strval);
171 | }
172 | }
173 | fragment.push(colFragment);
174 | }
175 | return fragment;
176 | }
177 |
178 | getat(row: number, column: number): string {
179 | // TODO: input validation
180 | return this.rows[row].cells[column].value;
181 | }
182 |
183 | // Update text lines with a calculated data.
184 | update(data: string[]) {
185 | for (let i = 0; i < this.rows.length; i++) {
186 | data[this.startLine + i] = this.rows[i].serialize();
187 | }
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/src/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "manifest_version": 1,
3 | "id": "osw.joplin.markdowncalc",
4 | "app_min_version": "1.6.6",
5 | "repository_url": "https://github.com/oswida/joplin-markdown-calc",
6 | "name": "Markdown table calculations",
7 | "description": "Plugin for automatic calculations of markdown table formulas.",
8 | "version": "1.0.5",
9 | "author": "Oskar Świda",
10 | "homepage_url": "https://github.com/oswida/joplin-markdown-calc",
11 | "keywords": ["markdown", "orgmode", "calc", "table"]
12 | }
13 |
--------------------------------------------------------------------------------
/src/tests/calc.test.ts:
--------------------------------------------------------------------------------
1 | import { TableCalculator } from "../lib/calc";
2 | import { MTTable } from "../lib/table";
3 | import MarkdownIt = require("markdown-it");
4 |
5 | const SAMPLE3 = `|A|B|C|
6 | |--|--|--|
7 | |1|2|3|
8 | |4|5|6|
9 | |7|8|9|
10 |
11 |
12 | Some text which is not important
13 | |D|E|F|
14 | |--|--|--|
15 | |10|20|30|
16 | |40|0|60|
17 | |70|80|90|
18 | |100|110|120|
19 |
20 | `;
21 |
22 | const SAMPLE4 = `|A|B|C|
23 | |--|--|--|
24 | |1|2|3|
25 | |4|5|6|
26 | |7|8|9|
27 |
28 |
29 | Some text which is not important
30 | |D|E|F|
31 | |--|--|--|
32 | |10|20|30|
33 | |40|0|60|
34 | |70|80|90|
35 | |100|110|120|
36 |
37 | `;
38 |
39 | const SAMPLE5 = `|A|B|C|
40 | |--|--|--|
41 | ||2|3|
42 | |4|5|6|
43 | |7|8||
44 | `;
45 |
46 | const SAMPLE6 = `|A|B|C|
47 | |--|--|--|
48 | ||2|3|
49 | |4|5|6|
50 | |7|8||
51 |
52 | `;
53 |
54 | const SAMPLE7 = `|A|B|C|
55 | |--|--|--|
56 | |1|2|3|
57 | |4|5|6|
58 | |7|8|9|
59 |
60 | `;
61 |
62 | const SAMPLE8 = `
63 | |A|B|C|
64 | |--|--|--|
65 | |1|2|3|
66 | |4|5|6|
67 | |7|8|9|
68 |
69 | `;
70 |
71 | const SAMPLE9 = `
72 | |A|B|C|
73 | |--|--|--|
74 | |aa|2||
75 | |4|5|6|
76 | |7|8|9|
77 |
78 | `;
79 |
80 | const SAMPLE10 = `|A|B|C|
81 | |--|--|--|
82 | |aaa|2|3|
83 | |4||6|
84 | |7|8|9|
85 |
86 | `;
87 |
88 | const SAMPLE11 = `
89 | Table inside code block
90 |
91 | \`\`\`
92 | code data...
93 | |A|B|C|
94 | |--|--|--|
95 | |12|2|5|
96 | |4|5|6|
97 | |7|8|9|
98 |
99 | another code data...
100 | \`\`\`
101 | other....
102 | `;
103 |
104 | const calcSample = (text: string): [TableCalculator, string[]] => {
105 | const md = new MarkdownIt({ html: true });
106 | const data = md.parse(text, null);
107 | const body_lines = text.split("\n");
108 | const calc = new TableCalculator();
109 | for (let i = 0; i < data.length; i++) {
110 | if (data[i].type === "tbody_open") {
111 | // end line in a map points to the line AFTER the table
112 | calc.addTable(data[i].map[0], data[i].map[1] - 1, body_lines);
113 | } else if (data[i].type === "html_block") {
114 | calc.checkFormulaList(data[i].map[0], data[i].content);
115 | }
116 | }
117 | calc.execute(body_lines);
118 | return [calc, body_lines];
119 | };
120 |
121 | test("Table formula computing", () => {
122 | const [calc, body_lines] = calcSample(SAMPLE3);
123 |
124 | const table = new MTTable(2, 4);
125 | table.parse(body_lines);
126 | expect(table.rows.length).toBe(3);
127 | expect(table.findCell("A3").value).toBe("7");
128 | expect(table.findCell("B3").value).toBe("5");
129 | expect(table.findCell("C3").value).toBe("21");
130 |
131 | const table2 = new MTTable(10, 13);
132 | table2.parse(body_lines);
133 | expect(table2.rows.length).toBe(4);
134 | expect(table2.findCell("C1").value).toBe("30");
135 | expect(table2.findCell("C2").value).toBe("60");
136 | expect(table2.findCell("C3").value).toBe("2100");
137 | expect(table2.findCell("B2").value).toBe("50");
138 | });
139 |
140 | test("Calculation order", () => {
141 | const [calc, body_lines] = calcSample(SAMPLE4);
142 |
143 | const table = new MTTable(2, 4);
144 | table.parse(body_lines);
145 | expect(table.rows.length).toBe(3);
146 | expect(table.findCell("A3").value).toBe("7");
147 | expect(table.findCell("B3").value).toBe("5");
148 | expect(table.findCell("C3").value).toBe("35");
149 |
150 | const table2 = new MTTable(10, 13);
151 | table2.parse(body_lines);
152 | expect(table2.rows.length).toBe(4);
153 | expect(table2.findCell("C1").value).toBe("30");
154 | expect(table2.findCell("C2").value).toBe("60");
155 | expect(table2.findCell("C3").value).toBe("2100");
156 | expect(table2.findCell("B2").value).toBe("130");
157 | });
158 |
159 | test("Cell formula calculation", () => {
160 | const [calc, body_lines] = calcSample(SAMPLE5);
161 | const table = new MTTable(2, 4);
162 | table.parse(body_lines);
163 |
164 | const a1 = table.findCell("A1");
165 | expect(a1.value).toBe("-3");
166 | expect(a1.formula).toBe("B2-B3");
167 | expect(a1.formulaPrefix).toBe("FM");
168 | const c3 = table.findCell("C3");
169 | expect(c3.value).toBe("0.5");
170 | expect(c3.formula).toBe("C1/C2");
171 | expect(c3.formulaPrefix).toBe("FM");
172 | });
173 |
174 | test("Cell and table formula calculation order", () => {
175 | const [calc, body_lines] = calcSample(SAMPLE6);
176 | const table = new MTTable(2, 4);
177 | table.parse(body_lines);
178 |
179 | const a1 = table.findCell("A1");
180 | expect(a1.value).toBe("-3");
181 | expect(a1.formula).toBe("B2-B3");
182 | expect(a1.formulaPrefix).toBe("FM");
183 | const c3 = table.findCell("C3");
184 | // Table formulas overwrite cell formulas
185 | // Cell formula has been replaced by the table one
186 | expect(c3.value).toBe("21");
187 | expect(c3.formula).toBe(null);
188 | expect(c3.formulaPrefix).toBe(null);
189 |
190 | const b2 = table.findCell("B2");
191 | expect(b2.value).toBe("1");
192 | });
193 |
194 | test("Formula functions and ranges", () => {
195 | const [calc, body_lines] = calcSample(SAMPLE7);
196 | const table = new MTTable(2, 4);
197 | table.parse(body_lines);
198 |
199 | const c3 = table.findCell("C3");
200 | expect(c3.value).toBe("12");
201 | const b3 = table.findCell("B3");
202 | expect(b3.value).toBe("4.5");
203 | });
204 |
205 | test("Table formulas with spaces", () => {
206 | const [calc, body_lines] = calcSample(SAMPLE8);
207 |
208 | const table = new MTTable(3, 5);
209 | table.parse(body_lines);
210 | expect(table.rows.length).toBe(3);
211 | expect(table.findCell("B2").value).toBe("12");
212 | expect(table.findCell("C3").value).toBe("5");
213 | });
214 |
215 | test("Table cells with bad numbers", () => {
216 | const [calc, body_lines] = calcSample(SAMPLE9);
217 |
218 | const table = new MTTable(3, 5);
219 | table.parse(body_lines);
220 | expect(table.rows.length).toBe(3);
221 | expect(table.findCell("B2").value).toBe("#VALUE!");
222 | expect(table.findCell("C3").value).toBe("#VALUE!");
223 | });
224 |
225 | test("Formula functions and ranges with bad values", () => {
226 | const [calc, body_lines] = calcSample(SAMPLE10);
227 | const table = new MTTable(2, 4);
228 | table.parse(body_lines);
229 |
230 | const c3 = table.findCell("C3");
231 | expect(c3.value).toBe("11");
232 | const b3 = table.findCell("B3");
233 | expect(b3.value).toBe("5");
234 | });
235 |
236 | test("Calculate formulas inside code block", () => {
237 | const calc = new TableCalculator();
238 | const body_lines = calc.prepareTables(SAMPLE11);
239 | calc.execute(body_lines);
240 | expect(body_lines[8]).toBe("|4|20|6|");
241 | expect(body_lines[9]).toBe("|7|8|16|");
242 | });
243 |
--------------------------------------------------------------------------------
/src/tests/table.test.ts:
--------------------------------------------------------------------------------
1 | import { MTTable } from "../lib/table";
2 |
3 | const SAMPLE = `|A|B|C|
4 | |--|--|--|
5 | |1|2|3|
6 | |4|5|6|
7 | |7|8|9|
8 | `;
9 |
10 | const SAMPLE2 = `|A|B|C|
11 | |--|--|--|
12 | |1|2|3|
13 | |4|5|6|
14 | |7|8|9|
15 |
16 | Some text which is not important
17 | |D|E|F|
18 | |--|--|--|
19 | |10|20|30|
20 | |40|50|60|
21 | |70|80|90|
22 | |100|110|120|
23 | `;
24 |
25 | test("Find cell by label", () => {
26 | const table = new MTTable(2, 4);
27 | table.parse(SAMPLE.split("\n"));
28 | let cell = table.findCell("A1");
29 | expect(cell.value).toBe("1");
30 | cell = table.findCell("B2");
31 | expect(cell.value).toBe("5");
32 | cell = table.findCell("C3");
33 | expect(cell.value).toBe("9");
34 | });
35 |
36 | test("Table parsing", () => {
37 | const table = new MTTable(2, 4);
38 | table.parse(SAMPLE.split("\n"));
39 | expect(table.rows.length).toBe(3);
40 | expect(table.rows[0].cells.length).toBe(3);
41 | expect(table.rows[1].cells.length).toBe(3);
42 | expect(table.rows[2].cells.length).toBe(3);
43 | expect(table.findCell("A3").value).toBe("7");
44 | expect(table.findCell("B3").value).toBe("8");
45 | expect(table.findCell("C3").value).toBe("9");
46 | });
47 |
48 | test("Multiple tables parsing", () => {
49 | const table = new MTTable(2, 4);
50 | table.parse(SAMPLE2.split("\n"));
51 | expect(table.rows.length).toBe(3);
52 | expect(table.findCell("A3").value).toBe("7");
53 | expect(table.findCell("B3").value).toBe("8");
54 | expect(table.findCell("C3").value).toBe("9");
55 | const table2 = new MTTable(9, 12);
56 | table2.parse(SAMPLE2.split("\n"));
57 | expect(table2.rows.length).toBe(4);
58 | expect(table2.findCell("C1").value).toBe("30");
59 | expect(table2.findCell("C2").value).toBe("60");
60 | expect(table2.findCell("C3").value).toBe("90");
61 | expect(table2.findCell("C4").value).toBe("120");
62 | });
63 |
64 | test("Cell range parsing", () => {
65 | const table = new MTTable(9, 12);
66 | table.parse(SAMPLE2.split("\n"));
67 | const fragment = table.getfragment(
68 | table.cellCoordinate("A1"),
69 | table.cellCoordinate("B3")
70 | );
71 | // 3 rows, 2 columns each
72 | expect(fragment.length).toBe(3);
73 | expect(fragment[0].length).toBe(2);
74 | expect(fragment[1].length).toBe(2);
75 | expect(fragment[2].length).toBe(2);
76 | expect(fragment[0][0]).toBe(10);
77 | expect(fragment[0][1]).toBe(20);
78 | expect(fragment[1][0]).toBe(40);
79 | expect(fragment[1][1]).toBe(50);
80 | expect(fragment[2][0]).toBe(70);
81 | expect(fragment[2][1]).toBe(80);
82 | });
83 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "outDir": "./dist/",
4 | "module": "commonjs",
5 | "target": "es2015",
6 | "jsx": "react",
7 | "allowJs": true,
8 | "baseUrl": "."
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | // -----------------------------------------------------------------------------
2 | // This file is used to build the plugin file (.jpl) and plugin info (.json). It
3 | // is recommended not to edit this file as it would be overwritten when updating
4 | // the plugin framework. If you do make some changes, consider using an external
5 | // JS file and requiring it here to minimize the changes. That way when you
6 | // update, you can easily restore the functionality you've added.
7 | // -----------------------------------------------------------------------------
8 |
9 | const path = require('path');
10 | const crypto = require('crypto');
11 | const fs = require('fs-extra');
12 | const chalk = require('chalk');
13 | const CopyPlugin = require('copy-webpack-plugin');
14 | const WebpackOnBuildPlugin = require('on-build-webpack');
15 | const tar = require('tar');
16 | const glob = require('glob');
17 | const execSync = require('child_process').execSync;
18 |
19 | const rootDir = path.resolve(__dirname);
20 | const userConfigFilename = './plugin.config.json';
21 | const userConfigPath = path.resolve(rootDir, userConfigFilename);
22 | const distDir = path.resolve(rootDir, 'dist');
23 | const srcDir = path.resolve(rootDir, 'src');
24 | const publishDir = path.resolve(rootDir, 'publish');
25 |
26 | const userConfig = Object.assign({}, {
27 | extraScripts: [],
28 | }, fs.pathExistsSync(userConfigPath) ? require(userConfigFilename) : {});
29 |
30 | const manifestPath = `${srcDir}/manifest.json`;
31 | const packageJsonPath = `${rootDir}/package.json`;
32 | const manifest = readManifest(manifestPath);
33 | const pluginArchiveFilePath = path.resolve(publishDir, `${manifest.id}.jpl`);
34 | const pluginInfoFilePath = path.resolve(publishDir, `${manifest.id}.json`);
35 |
36 | function validatePackageJson() {
37 | const content = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
38 | if (!content.name || content.name.indexOf('joplin-plugin-') !== 0) {
39 | console.warn(chalk.yellow(`WARNING: To publish the plugin, the package name should start with "joplin-plugin-" (found "${content.name}") in ${packageJsonPath}`));
40 | }
41 |
42 | if (!content.keywords || content.keywords.indexOf('joplin-plugin') < 0) {
43 | console.warn(chalk.yellow(`WARNING: To publish the plugin, the package keywords should include "joplin-plugin" (found "${JSON.stringify(content.keywords)}") in ${packageJsonPath}`));
44 | }
45 |
46 | if (content.scripts && content.scripts.postinstall) {
47 | console.warn(chalk.yellow(`WARNING: package.json contains a "postinstall" script. It is recommended to use a "prepare" script instead so that it is executed before publish. In ${packageJsonPath}`));
48 | }
49 | }
50 |
51 | function fileSha256(filePath) {
52 | const content = fs.readFileSync(filePath);
53 | return crypto.createHash('sha256').update(content).digest('hex');
54 | }
55 |
56 | function currentGitInfo() {
57 | try {
58 | let branch = execSync('git rev-parse --abbrev-ref HEAD', { stdio: 'pipe' }).toString().trim();
59 | const commit = execSync('git rev-parse HEAD', { stdio: 'pipe' }).toString().trim();
60 | if (branch === 'HEAD') branch = 'master';
61 | return `${branch}:${commit}`;
62 | } catch (error) {
63 | const messages = error.message ? error.message.split('\n') : [''];
64 | console.info(chalk.cyan('Could not get git commit (not a git repo?):', messages[0].trim()));
65 | console.info(chalk.cyan('Git information will not be stored in plugin info file'));
66 | return '';
67 | }
68 | }
69 |
70 | function readManifest(manifestPath) {
71 | const content = fs.readFileSync(manifestPath, 'utf8');
72 | const output = JSON.parse(content);
73 | if (!output.id) throw new Error(`Manifest plugin ID is not set in ${manifestPath}`);
74 | return output;
75 | }
76 |
77 | function createPluginArchive(sourceDir, destPath) {
78 | const distFiles = glob.sync(`${sourceDir}/**/*`, { nodir: true })
79 | .map(f => f.substr(sourceDir.length + 1));
80 |
81 | if (!distFiles.length) throw new Error('Plugin archive was not created because the "dist" directory is empty');
82 | fs.removeSync(destPath);
83 |
84 | tar.create(
85 | {
86 | strict: true,
87 | portable: true,
88 | file: destPath,
89 | cwd: sourceDir,
90 | sync: true,
91 | },
92 | distFiles
93 | );
94 |
95 | console.info(chalk.cyan(`Plugin archive has been created in ${destPath}`));
96 | }
97 |
98 | function createPluginInfo(manifestPath, destPath, jplFilePath) {
99 | const contentText = fs.readFileSync(manifestPath, 'utf8');
100 | const content = JSON.parse(contentText);
101 | content._publish_hash = `sha256:${fileSha256(jplFilePath)}`;
102 | content._publish_commit = currentGitInfo();
103 | fs.writeFileSync(destPath, JSON.stringify(content, null, '\t'), 'utf8');
104 | }
105 |
106 | function onBuildCompleted() {
107 | try {
108 | fs.removeSync(path.resolve(publishDir, 'index.js'));
109 | createPluginArchive(distDir, pluginArchiveFilePath);
110 | createPluginInfo(manifestPath, pluginInfoFilePath, pluginArchiveFilePath);
111 | validatePackageJson();
112 | } catch (error) {
113 | console.error(chalk.red(error.message));
114 | }
115 | }
116 |
117 | const baseConfig = {
118 | mode: 'production',
119 | target: 'node',
120 | stats: 'errors-only',
121 | module: {
122 | rules: [
123 | {
124 | test: /\.tsx?$/,
125 | use: 'ts-loader',
126 | exclude: /node_modules/,
127 | },
128 | ],
129 | },
130 | };
131 |
132 | const pluginConfig = Object.assign({}, baseConfig, {
133 | entry: './src/index.ts',
134 | resolve: {
135 | alias: {
136 | api: path.resolve(__dirname, 'api'),
137 | },
138 | extensions: ['.tsx', '.ts', '.js'],
139 | },
140 | output: {
141 | filename: 'index.js',
142 | path: distDir,
143 | },
144 | plugins: [
145 | new CopyPlugin({
146 | patterns: [
147 | {
148 | from: '**/*',
149 | context: path.resolve(__dirname, 'src'),
150 | to: path.resolve(__dirname, 'dist'),
151 | globOptions: {
152 | ignore: [
153 | // All TypeScript files are compiled to JS and
154 | // already copied into /dist so we don't copy them.
155 | '**/*.ts',
156 | '**/*.tsx',
157 | ],
158 | },
159 | },
160 | ],
161 | }),
162 | ],
163 | });
164 |
165 | const extraScriptConfig = Object.assign({}, baseConfig, {
166 | resolve: {
167 | alias: {
168 | api: path.resolve(__dirname, 'api'),
169 | },
170 | extensions: ['.tsx', '.ts', '.js'],
171 | },
172 | });
173 |
174 | const createArchiveConfig = {
175 | stats: 'errors-only',
176 | entry: './dist/index.js',
177 | output: {
178 | filename: 'index.js',
179 | path: publishDir,
180 | },
181 | plugins: [new WebpackOnBuildPlugin(onBuildCompleted)],
182 | };
183 |
184 | function resolveExtraScriptPath(name) {
185 | const relativePath = `./src/${name}`;
186 |
187 | const fullPath = path.resolve(`${rootDir}/${relativePath}`);
188 | if (!fs.pathExistsSync(fullPath)) throw new Error(`Could not find extra script: "${name}" at "${fullPath}"`);
189 |
190 | const s = name.split('.');
191 | s.pop();
192 | const nameNoExt = s.join('.');
193 |
194 | return {
195 | entry: relativePath,
196 | output: {
197 | filename: `${nameNoExt}.js`,
198 | path: distDir,
199 | library: 'default',
200 | libraryTarget: 'commonjs',
201 | libraryExport: 'default',
202 | },
203 | };
204 | }
205 |
206 | function buildExtraScriptConfigs(userConfig) {
207 | if (!userConfig.extraScripts.length) return [];
208 |
209 | const output = [];
210 |
211 | for (const scriptName of userConfig.extraScripts) {
212 | const scriptPaths = resolveExtraScriptPath(scriptName);
213 | output.push(Object.assign({}, extraScriptConfig, {
214 | entry: scriptPaths.entry,
215 | output: scriptPaths.output,
216 | }));
217 | }
218 |
219 | return output;
220 | }
221 |
222 | function main(processArgv) {
223 | const yargs = require('yargs/yargs');
224 | const argv = yargs(processArgv).argv;
225 |
226 | const configName = argv['joplin-plugin-config'];
227 | if (!configName) throw new Error('A config file must be specified via the --joplin-plugin-config flag');
228 |
229 | // Webpack configurations run in parallel, while we need them to run in
230 | // sequence, and to do that it seems the only way is to run webpack multiple
231 | // times, with different config each time.
232 |
233 | const configs = {
234 | // Builds the main src/index.ts and copy the extra content from /src to
235 | // /dist including scripts, CSS and any other asset.
236 | buildMain: [pluginConfig],
237 |
238 | // Builds the extra scripts as defined in plugin.config.json. When doing
239 | // so, some JavaScript files that were copied in the previous might be
240 | // overwritten here by the compiled version. This is by design. The
241 | // result is that JS files that don't need compilation, are simply
242 | // copied to /dist, while those that do need it are correctly compiled.
243 | buildExtraScripts: buildExtraScriptConfigs(userConfig),
244 |
245 | // Ths config is for creating the .jpl, which is done via the plugin, so
246 | // it doesn't actually need an entry and output, however webpack won't
247 | // run without this. So we give it an entry that we know is going to
248 | // exist and output in the publish dir. Then the plugin will delete this
249 | // temporary file before packaging the plugin.
250 | createArchive: [createArchiveConfig],
251 | };
252 |
253 | // If we are running the first config step, we clean up and create the build
254 | // directories.
255 | if (configName === 'buildMain') {
256 | fs.removeSync(distDir);
257 | fs.removeSync(publishDir);
258 | fs.mkdirpSync(publishDir);
259 | }
260 |
261 | return configs[configName];
262 | }
263 |
264 | let exportedConfigs = [];
265 |
266 | try {
267 | exportedConfigs = main(process.argv);
268 | } catch (error) {
269 | console.error(chalk.red(error.message));
270 | process.exit(1);
271 | }
272 |
273 | if (!exportedConfigs.length) {
274 | // Nothing to do - for example where there are no external scripts to
275 | // compile.
276 | process.exit(0);
277 | }
278 |
279 | module.exports = exportedConfigs;
280 |
--------------------------------------------------------------------------------