├── .gitignore ├── .npmignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── api ├── Global.d.ts ├── Joplin.d.ts ├── JoplinClipboard.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 ├── JoplinWindow.d.ts ├── JoplinWorkspace.d.ts ├── index.ts └── types.ts ├── assets └── tags-config.png ├── joplin-persistent-layout.code-workspace ├── package-lock.json ├── package.json ├── plugin.config.json ├── src ├── Layout.ts ├── data.ts ├── index.ts ├── manifest.json └── settings.ts ├── tsconfig.json └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | publish/ 4 | -------------------------------------------------------------------------------- /.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 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | - None 11 | 12 | ## [2.2.0] - 2021-09-26 13 | 14 | ### Added 15 | 16 | - `Previous` selection to user option `Default editor layout` 17 | 18 | ### Fixed 19 | 20 | - Mixed case tags ([#8](https://github.com/benji300/joplin-persistent-layout/issues/8) - Thanks to [@JackGruber](https://github.com/JackGruber)) 21 | - Layout is not set correctly on search ([#7](https://github.com/benji300/joplin-persistent-layout/issues/7)) ([#10](https://github.com/benji300/joplin-persistent-layout/issues/10) - Thanks to [@ken1kob](https://github.com/ken1kob)) 22 | 23 | ## [2.1.0] - 2021-08-10 24 | 25 | ### Changed 26 | 27 | - Updated plugin API to version v1.8.2 (`registerSettings`) to support app version v2.2.4 or newer 28 | 29 | ## [2.0.0] - 2021-03-29 30 | 31 | ### Added 32 | 33 | - Ability to specify custom tags to force a specific editor layout 34 | 35 | ### Removed 36 | 37 | - Command `persistEditorLayout` 38 | 39 | ## [1.1.3] - 2021-03-19 40 | 41 | ### Changed 42 | 43 | - Menu location of `persistEditorLayout` command to `Note` 44 | 45 | ### Fixed 46 | 47 | - Issue that might cause infinite loop in case a note has a lot of tags 48 | 49 | ## [1.1.2] - 2021-02-10 50 | 51 | ### Added 52 | 53 | - Command `persistEditorLayout` to editor context menu 54 | 55 | ## [1.1.1] - 2021-02-02 56 | 57 | ### Fixed 58 | 59 | - Default layout not considered at startup ([#6](https://github.com/benji300/joplin-persistent-layout/issues/6)) 60 | 61 | ## [1.1.0] - 2021-02-01 62 | 63 | ### Added 64 | 65 | - User option to specify default editor layout ([#3](https://github.com/benji300/joplin-persistent-layout/issues/3)) 66 | - Support to persist rich text editor layout ([#4](https://github.com/benji300/joplin-persistent-layout/issues/4)) 67 | 68 | ## [1.0.0] - 2021-01-29 69 | 70 | - Initial Release 71 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Benjamin Seifert 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Joplin Persistent Editor Layout 2 | 3 | Persistent Editor Layout is a plugin to extend the UX of [Joplin's](https://joplinapp.org/) desktop application. 4 | 5 | It allows to persist the editor layout for each note separately with [custom tags](#usage). 6 | 7 | > :warning: **CAUTION** - Requires Joplin **v1.8.2** or newer 8 | 9 | ## Features 10 | 11 | - Persist the editor layout (`editor / split view / viewer / rich text`) for each note separately 12 | - Ability to specify [custom tags](#usage) to force a specific layout 13 | - Persisted layout is synced across (desktop) devices, if the plugin is installed 14 | 15 | ## Installation 16 | 17 | ### Automatic (Joplin v1.6.4 and newer) 18 | 19 | - Open Joplin and navigate to `Tools > Options > Plugins` 20 | - Search for the plugin name and press install 21 | - Restart Joplin to enable the plugin 22 | 23 | ### Manual 24 | 25 | - Download the latest released JPL package (`*.jpl`) from [here](https://github.com/benji300/joplin-persistent-layout/releases) 26 | - Open Joplin and navigate to `Tools > Options > Plugins` 27 | - Press `Install plugin` and select the previously downloaded `jpl` file 28 | - Confirm selection 29 | - Restart Joplin to enable the plugin 30 | 31 | ### Uninstall 32 | 33 | - Open Joplin and navigate to `Tools > Options > Plugins` 34 | - Search for the plugin name and press `Delete` to remove the plugin completely 35 | - Alternatively you can also disable the plugin by clicking on the toggle button 36 | - Restart Joplin 37 | 38 | ## Usage 39 | 40 | To persist the layout for a note follow these steps: 41 | 42 | 1. Specify the tags for which a specific layout should be used. 43 | 44 | - To do this, go to the plugin's settings/options page and add the tags to the settings. 45 | 46 | - An example configuration could like this: 47 | 48 | ![layout-tags-config](./assets/tags-config.png) 49 | 50 | 1. Make sure that the correct value is selected in `View > Layout button sequence`. 51 | 52 | - To be able to use the layout switching correctly, this setting must be set accordingly. Otherwise the editor layout might not be switched to the expected one. 53 | 54 | - For example: If a tag is specified in option `Tags for editor layout mode: Rendered Markdown viewer` and least one note uses it, the setting must also contain `Viewer`. 55 | 56 | 1. Add the appropriate tags to the notes. If not already done. 57 | 58 | - When the selected note is changed, the editor layout is switched. 59 | 60 | - If none of the selected note's tags matches a specified layout tag, the default layout from the option `Default editor layout` is used. 61 | 62 | - If nothing is selected as default editor layout, the currently active editor layout will be kept. 63 | 64 | - If more than one tag is specified for a note, the first matching one is used. 65 | 66 | ## Commands 67 | 68 | This plugin does not provide any commands. 69 | 70 | ## User options 71 | 72 | This plugin adds provides user options which can be changed via `Tools > Options > Persistent Layout` (Windows App). 73 | 74 | ## Feedback 75 | 76 | - :question: Need help? 77 | - Ask a question on the [Joplin Forum](https://discourse.joplinapp.org/t/persist-editor-layout-plugin/14411) 78 | - :bulb: An idea to improve or enhance the plugin? 79 | - Start a new discussion on the [Forum](https://discourse.joplinapp.org/t/persist-editor-layout-plugin/14411) or upvote [popular feature requests](https://github.com/benji300/joplin-persistent-layout/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement+sort%3Areactions-%2B1-desc+) 80 | - :bug: Found a bug? 81 | - Check the [Forum](https://discourse.joplinapp.org/t/persist-editor-layout-plugin/14411) if anyone else already reported the same issue. Otherwise report it by yourself. 82 | 83 | ## Support 84 | 85 | You like this plugin as much as I do and it improves your daily work with Joplin? 86 | 87 | Then I would be very happy if you buy me a :beer: or :coffee: via [PayPal](https://www.paypal.com/donate?hosted_button_id=6FHDGK3PTNU22) :wink: 88 | 89 | ## Contributing 90 | 91 | Contributions to this plugin are most welcome. Feel free to open a pull request or an issue. 92 | Make sure to use conventional [commit messages](https://github.com/pvdlg/conventional-commit-types) if you're creating a pull request. 93 | 94 | ## Development 95 | 96 | The npm package of the plugin can be found [here](https://www.npmjs.com/package/joplin-plugin-persistent-editor-layout). 97 | 98 | ### Building the plugin 99 | 100 | If you want to build the plugin by your own simply run `npm run dist`. 101 | 102 | ### Updating the plugin framework 103 | 104 | To update the plugin framework, run `npm run update`. 105 | 106 | ## Changes 107 | 108 | See [CHANGELOG](./CHANGELOG.md) for details. 109 | 110 | ## License 111 | 112 | Copyright (c) 2021 Benjamin Seifert 113 | 114 | MIT License. See [LICENSE](./LICENSE) for more information. 115 | -------------------------------------------------------------------------------- /api/Global.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import Joplin from './Joplin'; 3 | /** 4 | * @ignore 5 | */ 6 | /** 7 | * @ignore 8 | */ 9 | export default class Global { 10 | private joplin_; 11 | constructor(implementation: any, plugin: Plugin, store: any); 12 | get joplin(): Joplin; 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 | import JoplinClipboard from './JoplinClipboard'; 12 | import JoplinWindow from './JoplinWindow'; 13 | /** 14 | * This is the main entry point to the Joplin API. You can access various services using the provided accessors. 15 | * 16 | * **This is a beta API** 17 | * 18 | * 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: 19 | * 20 | * - Maintain backward compatibility; 21 | * - When possible, deprecate features instead of removing them; 22 | * - Document breaking changes in the changelog; 23 | * 24 | * 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. 25 | * 26 | * Eventually, the plugin API will be versioned to make this process smoother. 27 | */ 28 | export default class Joplin { 29 | private data_; 30 | private plugins_; 31 | private workspace_; 32 | private filters_; 33 | private commands_; 34 | private views_; 35 | private interop_; 36 | private settings_; 37 | private contentScripts_; 38 | private clipboard_; 39 | private window_; 40 | constructor(implementation: any, plugin: Plugin, store: any); 41 | get data(): JoplinData; 42 | get clipboard(): JoplinClipboard; 43 | get window(): JoplinWindow; 44 | get plugins(): JoplinPlugins; 45 | get workspace(): JoplinWorkspace; 46 | get contentScripts(): JoplinContentScripts; 47 | /** 48 | * @ignore 49 | * 50 | * Not sure if it's the best way to hook into the app 51 | * so for now disable filters. 52 | */ 53 | get filters(): JoplinFilters; 54 | get commands(): JoplinCommands; 55 | get views(): JoplinViews; 56 | get interop(): JoplinInterop; 57 | get settings(): JoplinSettings; 58 | /** 59 | * It is not possible to bundle native packages with a plugin, because they 60 | * need to work cross-platforms. Instead access to certain useful native 61 | * packages is provided using this function. 62 | * 63 | * Currently these packages are available: 64 | * 65 | * - [sqlite3](https://www.npmjs.com/package/sqlite3) 66 | * - [fs-extra](https://www.npmjs.com/package/fs-extra) 67 | * 68 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/nativeModule) 69 | */ 70 | require(_path: string): any; 71 | } 72 | -------------------------------------------------------------------------------- /api/JoplinClipboard.d.ts: -------------------------------------------------------------------------------- 1 | export default class JoplinClipboard { 2 | private electronClipboard_; 3 | private electronNativeImage_; 4 | constructor(electronClipboard: any, electronNativeImage: any); 5 | readText(): Promise; 6 | writeText(text: string): Promise; 7 | readHtml(): Promise; 8 | writeHtml(html: string): Promise; 9 | /** 10 | * Returns the image in [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) format. 11 | */ 12 | readImage(): Promise; 13 | /** 14 | * Takes an image in [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) format. 15 | */ 16 | writeImage(dataUrl: string): Promise; 17 | /** 18 | * Returns the list available formats (mime types). 19 | * 20 | * For example [ 'text/plain', 'text/html' ] 21 | */ 22 | availableFormats(): Promise; 23 | } 24 | -------------------------------------------------------------------------------- /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 | * ## Executing editor commands 24 | * 25 | * There might be a situation where you want to invoke editor commands 26 | * without using a {@link JoplinContentScripts | contentScript}. For this 27 | * reason Joplin provides the built in `editor.execCommand` command. 28 | * 29 | * `editor.execCommand` should work with any core command in both the 30 | * [CodeMirror](https://codemirror.net/doc/manual.html#execCommand) and 31 | * [TinyMCE](https://www.tiny.cloud/docs/api/tinymce/tinymce.editorcommands/#execcommand) editors, 32 | * as well as most functions calls directly on a CodeMirror editor object (extensions). 33 | * 34 | * * [CodeMirror commands](https://codemirror.net/doc/manual.html#commands) 35 | * * [TinyMCE core editor commands](https://www.tiny.cloud/docs/advanced/editor-command-identifiers/#coreeditorcommands) 36 | * 37 | * `editor.execCommand` supports adding arguments for the commands. 38 | * 39 | * ```typescript 40 | * await joplin.commands.execute('editor.execCommand', { 41 | * name: 'madeUpCommand', // CodeMirror and TinyMCE 42 | * args: [], // CodeMirror and TinyMCE 43 | * ui: false, // TinyMCE only 44 | * value: '', // TinyMCE only 45 | * }); 46 | * ``` 47 | * 48 | * [View the example using the CodeMirror editor](https://github.com/laurent22/joplin/blob/dev/packages/app-cli/tests/support/plugins/codemirror_content_script/src/index.ts) 49 | * 50 | */ 51 | export default class JoplinCommands { 52 | /** 53 | * desktop Executes the given 54 | * command. 55 | * 56 | * The command can take any number of arguments, and the supported 57 | * arguments will vary based on the command. For custom commands, this 58 | * is the `args` passed to the `execute()` function. For built-in 59 | * commands, you can find the supported arguments by checking the links 60 | * above. 61 | * 62 | * ```typescript 63 | * // Create a new note in the current notebook: 64 | * await joplin.commands.execute('newNote'); 65 | * 66 | * // Create a new sub-notebook under the provided notebook 67 | * // Note: internally, notebooks are called "folders". 68 | * await joplin.commands.execute('newFolder', "SOME_FOLDER_ID"); 69 | * ``` 70 | */ 71 | execute(commandName: string, ...args: any[]): Promise; 72 | /** 73 | * desktop Registers a new command. 74 | * 75 | * ```typescript 76 | * // Register a new commmand called "testCommand1" 77 | * 78 | * await joplin.commands.register({ 79 | * name: 'testCommand1', 80 | * label: 'My Test Command 1', 81 | * iconName: 'fas fa-music', 82 | * execute: () => { 83 | * alert('Testing plugin command 1'); 84 | * }, 85 | * }); 86 | * ``` 87 | */ 88 | register(command: Command): Promise; 89 | } 90 | -------------------------------------------------------------------------------- /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 | * Gets the plugin own data directory path. Use this to store any 28 | * plugin-related data. Unlike [[installationDir]], any data stored here 29 | * will be persisted. 30 | */ 31 | dataDir(): Promise; 32 | /** 33 | * Gets the plugin installation directory. This can be used to access any 34 | * asset that was packaged with the plugin. This directory should be 35 | * considered read-only because any data you store here might be deleted or 36 | * re-created at any time. To store new persistent data, use [[dataDir]]. 37 | */ 38 | installationDir(): Promise; 39 | /** 40 | * @deprecated Use joplin.require() 41 | */ 42 | require(_path: string): any; 43 | } 44 | -------------------------------------------------------------------------------- /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 new settings. 26 | * Note that registering a setting item is dynamic and will be gone next time Joplin starts. 27 | * What it means is that you need to register the setting every time the plugin starts (for example in the onStart event). 28 | * 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 29 | * reason the plugin fails to start at some point. 30 | */ 31 | registerSettings(settings: Record): Promise; 32 | /** 33 | * @deprecated Use joplin.settings.registerSettings() 34 | * 35 | * Registers a new setting. 36 | */ 37 | registerSetting(key: string, settingItem: SettingItem): Promise; 38 | /** 39 | * Registers a new setting section. Like for registerSetting, it is dynamic and needs to be done every time the plugin starts. 40 | */ 41 | registerSection(name: string, section: SettingSection): Promise; 42 | /** 43 | * Gets a setting value (only applies to setting you registered from your plugin) 44 | */ 45 | value(key: string): Promise; 46 | /** 47 | * Sets a setting value (only applies to setting you registered from your plugin) 48 | */ 49 | setValue(key: string, value: any): Promise; 50 | /** 51 | * Gets a global setting value, including app-specific settings and those set by other plugins. 52 | * 53 | * The list of available settings is not documented yet, but can be found by looking at the source code: 54 | * 55 | * https://github.com/laurent22/joplin/blob/dev/packages/lib/models/Setting.ts#L142 56 | */ 57 | globalValue(key: string): Promise; 58 | /** 59 | * Called when one or multiple settings of your plugin have been changed. 60 | * - For performance reasons, this event is triggered with a delay. 61 | * - You will only get events for your own plugin settings. 62 | */ 63 | onChange(handler: ChangeHandler): Promise; 64 | } 65 | -------------------------------------------------------------------------------- /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 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 | * Toggle on whether to fit the dialog size to the content or not. 64 | * When set to false, the dialog stretches to fill the application 65 | * window. 66 | * @default true 67 | */ 68 | setFitToContent(handle: ViewHandle, status: boolean): Promise; 69 | } 70 | -------------------------------------------------------------------------------- /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/JoplinWindow.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | export interface Implementation { 3 | injectCustomStyles(elementId: string, cssFilePath: string): Promise; 4 | } 5 | export default class JoplinWindow { 6 | private plugin_; 7 | private store_; 8 | private implementation_; 9 | constructor(implementation: Implementation, plugin: Plugin, store: any); 10 | /** 11 | * Loads a chrome CSS file. It will apply to the window UI elements, except 12 | * for the note viewer. It is the same as the "Custom stylesheet for 13 | * Joplin-wide app styles" setting. See the [Load CSS Demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/load_css) 14 | * for an example. 15 | */ 16 | loadChromeCssFile(filePath: string): Promise; 17 | /** 18 | * Loads a note CSS file. It will apply to the note viewer, as well as any 19 | * exported or printed note. It is the same as the "Custom stylesheet for 20 | * rendered Markdown" setting. See the [Load CSS Demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/load_css) 21 | * for an example. 22 | */ 23 | loadNoteCssFile(filePath: string): Promise; 24 | } 25 | -------------------------------------------------------------------------------- /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 the current 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 31 | * affects 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 34 | * Code). It's a simple boolean expression that evaluates to `true` or 35 | * `false`. It supports the following operators: 36 | * 37 | * Operator | Symbol | Example 38 | * -- | -- | -- 39 | * Equality | == | "editorType == markdown" 40 | * Inequality | != | "currentScreen != config" 41 | * Or | \|\| | "noteIsTodo \|\| noteTodoCompleted" 42 | * And | && | "oneNoteSelected && !inConflictFolder" 43 | * 44 | * Joplin, unlike VSCode, also supports parenthesis, which allows creating 45 | * more complex expressions such as `cond1 || (cond2 && cond3)`. Only one 46 | * level of parenthesis is possible (nested ones aren't supported). 47 | * 48 | * Currently the supported context variables aren't documented, but you can 49 | * find the list below: 50 | * 51 | * - [Global When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts) 52 | * - [Desktop app When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/app-desktop/services/commands/stateToWhenClauseContext.ts) 53 | * 54 | * Note: Commands are enabled by default unless you use this property. 55 | */ 56 | enabledCondition?: string; 57 | } 58 | 59 | // ================================================================= 60 | // Interop API types 61 | // ================================================================= 62 | 63 | export enum FileSystemItem { 64 | File = 'file', 65 | Directory = 'directory', 66 | } 67 | 68 | export enum ImportModuleOutputFormat { 69 | Markdown = 'md', 70 | Html = 'html', 71 | } 72 | 73 | /** 74 | * 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. 75 | * 76 | * 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. 77 | * 78 | * To get a better sense of what it will contain it can be useful to print it using `console.info(context)`. 79 | */ 80 | export interface ExportModule { 81 | /** 82 | * The format to be exported, eg "enex", "jex", "json", etc. 83 | */ 84 | format: string; 85 | 86 | /** 87 | * The description that will appear in the UI, for example in the menu item. 88 | */ 89 | description: string; 90 | 91 | /** 92 | * 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. 93 | */ 94 | target: FileSystemItem; 95 | 96 | /** 97 | * Only applies to single file exporters or importers 98 | * It tells whether the format can package multiple notes into one file. 99 | * For example JEX or ENEX can, but HTML cannot. 100 | */ 101 | isNoteArchive: boolean; 102 | 103 | /** 104 | * 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. 105 | */ 106 | fileExtensions?: string[]; 107 | 108 | /** 109 | * Called when the export process starts. 110 | */ 111 | onInit(context: ExportContext): Promise; 112 | 113 | /** 114 | * Called when an item needs to be processed. An "item" can be any Joplin object, such as a note, a folder, a notebook, etc. 115 | */ 116 | onProcessItem(context: ExportContext, itemType: number, item: any): Promise; 117 | 118 | /** 119 | * Called when a resource file needs to be exported. 120 | */ 121 | onProcessResource(context: ExportContext, resource: any, filePath: string): Promise; 122 | 123 | /** 124 | * Called when the export process is done. 125 | */ 126 | onClose(context: ExportContext): Promise; 127 | } 128 | 129 | export interface ImportModule { 130 | /** 131 | * The format to be exported, eg "enex", "jex", "json", etc. 132 | */ 133 | format: string; 134 | 135 | /** 136 | * The description that will appear in the UI, for example in the menu item. 137 | */ 138 | description: string; 139 | 140 | /** 141 | * Only applies to single file exporters or importers 142 | * It tells whether the format can package multiple notes into one file. 143 | * For example JEX or ENEX can, but HTML cannot. 144 | */ 145 | isNoteArchive: boolean; 146 | 147 | /** 148 | * The type of sources that are supported by the module. Tells whether the module can import files or directories or both. 149 | */ 150 | sources: FileSystemItem[]; 151 | 152 | /** 153 | * Tells the file extensions of the exported files. 154 | */ 155 | fileExtensions?: string[]; 156 | 157 | /** 158 | * Tells the type of notes that will be generated, either HTML or Markdown (default). 159 | */ 160 | outputFormat?: ImportModuleOutputFormat; 161 | 162 | /** 163 | * Called when the import process starts. There is only one event handler within which you should import the complete data. 164 | */ 165 | onExec(context: ImportContext): Promise; 166 | } 167 | 168 | export interface ExportOptions { 169 | format?: string; 170 | path?: string; 171 | sourceFolderIds?: string[]; 172 | sourceNoteIds?: string[]; 173 | // modulePath?: string; 174 | target?: FileSystemItem; 175 | } 176 | 177 | export interface ExportContext { 178 | destPath: string; 179 | options: ExportOptions; 180 | 181 | /** 182 | * 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. 183 | */ 184 | userData?: any; 185 | } 186 | 187 | export interface ImportContext { 188 | sourcePath: string; 189 | options: any; 190 | warnings: string[]; 191 | } 192 | 193 | // ================================================================= 194 | // Misc types 195 | // ================================================================= 196 | 197 | export interface Script { 198 | onStart?(event: any): Promise; 199 | } 200 | 201 | export interface Disposable { 202 | // dispose():void; 203 | } 204 | 205 | // ================================================================= 206 | // Menu types 207 | // ================================================================= 208 | 209 | export interface CreateMenuItemOptions { 210 | accelerator: string; 211 | } 212 | 213 | export enum MenuItemLocation { 214 | File = 'file', 215 | Edit = 'edit', 216 | View = 'view', 217 | Note = 'note', 218 | Tools = 'tools', 219 | Help = 'help', 220 | 221 | /** 222 | * @deprecated Do not use - same as NoteListContextMenu 223 | */ 224 | Context = 'context', 225 | 226 | // If adding an item here, don't forget to update isContextMenuItemLocation() 227 | 228 | /** 229 | * When a command is called from the note list context menu, the 230 | * command will receive the following arguments: 231 | * 232 | * - `noteIds:string[]`: IDs of the notes that were right-clicked on. 233 | */ 234 | NoteListContextMenu = 'noteListContextMenu', 235 | 236 | EditorContextMenu = 'editorContextMenu', 237 | 238 | /** 239 | * When a command is called from a folder context menu, the 240 | * command will receive the following arguments: 241 | * 242 | * - `folderId:string`: ID of the folder that was right-clicked on 243 | */ 244 | FolderContextMenu = 'folderContextMenu', 245 | 246 | /** 247 | * When a command is called from a tag context menu, the 248 | * command will receive the following arguments: 249 | * 250 | * - `tagId:string`: ID of the tag that was right-clicked on 251 | */ 252 | TagContextMenu = 'tagContextMenu', 253 | } 254 | 255 | export function isContextMenuItemLocation(location: MenuItemLocation): boolean { 256 | return [ 257 | MenuItemLocation.Context, 258 | MenuItemLocation.NoteListContextMenu, 259 | MenuItemLocation.EditorContextMenu, 260 | MenuItemLocation.FolderContextMenu, 261 | MenuItemLocation.TagContextMenu, 262 | ].includes(location); 263 | } 264 | 265 | export interface MenuItem { 266 | /** 267 | * Command that should be associated with the menu item. All menu item should 268 | * have a command associated with them unless they are a sub-menu. 269 | */ 270 | commandName?: string; 271 | 272 | /** 273 | * Accelerator associated with the menu item 274 | */ 275 | accelerator?: string; 276 | 277 | /** 278 | * Menu items that should appear below this menu item. Allows creating a menu tree. 279 | */ 280 | submenu?: MenuItem[]; 281 | 282 | /** 283 | * Menu item label. If not specified, the command label will be used instead. 284 | */ 285 | label?: string; 286 | } 287 | 288 | // ================================================================= 289 | // View API types 290 | // ================================================================= 291 | 292 | export interface ButtonSpec { 293 | id: ButtonId; 294 | title?: string; 295 | onClick?(): void; 296 | } 297 | 298 | export type ButtonId = string; 299 | 300 | export enum ToolbarButtonLocation { 301 | /** 302 | * This toolbar in the top right corner of the application. It applies to the note as a whole, including its metadata. 303 | */ 304 | NoteToolbar = 'noteToolbar', 305 | 306 | /** 307 | * This toolbar is right above the text editor. It applies to the note body only. 308 | */ 309 | EditorToolbar = 'editorToolbar', 310 | } 311 | 312 | export type ViewHandle = string; 313 | 314 | export interface EditorCommand { 315 | name: string; 316 | value?: any; 317 | } 318 | 319 | export interface DialogResult { 320 | id: ButtonId; 321 | formData?: any; 322 | } 323 | 324 | // ================================================================= 325 | // Settings types 326 | // ================================================================= 327 | 328 | export enum SettingItemType { 329 | Int = 1, 330 | String = 2, 331 | Bool = 3, 332 | Array = 4, 333 | Object = 5, 334 | Button = 6, 335 | } 336 | 337 | export enum AppType { 338 | Desktop = 'desktop', 339 | Mobile = 'mobile', 340 | Cli = 'cli', 341 | } 342 | 343 | export enum SettingStorage { 344 | Database = 1, 345 | File = 2, 346 | } 347 | 348 | // Redefine a simplified interface to mask internal details 349 | // and to remove function calls as they would have to be async. 350 | export interface SettingItem { 351 | value: any; 352 | type: SettingItemType; 353 | 354 | label: string; 355 | description?: string; 356 | 357 | /** 358 | * A public setting will appear in the Configuration screen and will be 359 | * modifiable by the user. A private setting however will not appear there, 360 | * and can only be changed programmatically. You may use this to store some 361 | * values that you do not want to directly expose. 362 | */ 363 | public: boolean; 364 | 365 | /** 366 | * You would usually set this to a section you would have created 367 | * specifically for the plugin. 368 | */ 369 | section?: string; 370 | 371 | /** 372 | * To create a setting with multiple options, set this property to `true`. 373 | * That setting will render as a dropdown list in the configuration screen. 374 | */ 375 | isEnum?: boolean; 376 | 377 | /** 378 | * This property is required when `isEnum` is `true`. In which case, it 379 | * should contain a map of value => label. 380 | */ 381 | options?: Record; 382 | 383 | /** 384 | * Reserved property. Not used at the moment. 385 | */ 386 | appTypes?: AppType[]; 387 | 388 | /** 389 | * Set this to `true` to store secure data, such as passwords. Any such 390 | * setting will be stored in the system keychain if one is available. 391 | */ 392 | secure?: boolean; 393 | 394 | /** 395 | * An advanced setting will be moved under the "Advanced" button in the 396 | * config screen. 397 | */ 398 | advanced?: boolean; 399 | 400 | /** 401 | * Set the min, max and step values if you want to restrict an int setting 402 | * to a particular range. 403 | */ 404 | minimum?: number; 405 | maximum?: number; 406 | step?: number; 407 | 408 | /** 409 | * Either store the setting in the database or in settings.json. Defaults to database. 410 | */ 411 | storage?: SettingStorage; 412 | } 413 | 414 | export interface SettingSection { 415 | label: string; 416 | iconName?: string; 417 | description?: string; 418 | name?: string; 419 | } 420 | 421 | // ================================================================= 422 | // Data API types 423 | // ================================================================= 424 | 425 | /** 426 | * An array of at least one element and at most three elements. 427 | * 428 | * - **[0]**: Resource name (eg. "notes", "folders", "tags", etc.) 429 | * - **[1]**: (Optional) Resource ID. 430 | * - **[2]**: (Optional) Resource link. 431 | */ 432 | export type Path = string[]; 433 | 434 | // ================================================================= 435 | // Content Script types 436 | // ================================================================= 437 | 438 | export type PostMessageHandler = (message: any)=> Promise; 439 | 440 | /** 441 | * When a content script is initialised, it receives a `context` object. 442 | */ 443 | export interface ContentScriptContext { 444 | /** 445 | * The plugin ID that registered this content script 446 | */ 447 | pluginId: string; 448 | 449 | /** 450 | * The content script ID, which may be necessary to post messages 451 | */ 452 | contentScriptId: string; 453 | 454 | /** 455 | * Can be used by CodeMirror content scripts to post a message to the plugin 456 | */ 457 | postMessage: PostMessageHandler; 458 | } 459 | 460 | export enum ContentScriptType { 461 | /** 462 | * Registers a new Markdown-It plugin, which should follow the template 463 | * below. 464 | * 465 | * ```javascript 466 | * module.exports = { 467 | * default: function(context) { 468 | * return { 469 | * plugin: function(markdownIt, options) { 470 | * // ... 471 | * }, 472 | * assets: { 473 | * // ... 474 | * }, 475 | * } 476 | * } 477 | * } 478 | * ``` 479 | * See [the 480 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/content_script) 481 | * for a simple Markdown-it plugin example. 482 | * 483 | * ## Exported members 484 | * 485 | * - The `context` argument is currently unused but could be used later on 486 | * to provide access to your own plugin so that the content script and 487 | * plugin can communicate. 488 | * 489 | * - The **required** `plugin` key is the actual Markdown-It plugin - check 490 | * the [official doc](https://github.com/markdown-it/markdown-it) for more 491 | * information. The `options` parameter is of type 492 | * [RuleOptions](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml.ts), 493 | * which contains a number of options, mostly useful for Joplin's internal 494 | * code. 495 | * 496 | * - Using the **optional** `assets` key you may specify assets such as JS 497 | * or CSS that should be loaded in the rendered HTML document. Check for 498 | * example the Joplin [Mermaid 499 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts) 500 | * to see how the data should be structured. 501 | * 502 | * ## Posting messages from the content script to your plugin 503 | * 504 | * The application provides the following function to allow executing 505 | * commands from the rendered HTML code: 506 | * 507 | * ```javascript 508 | * const response = await webviewApi.postMessage(contentScriptId, message); 509 | * ``` 510 | * 511 | * - `contentScriptId` is the ID you've defined when you registered the 512 | * content script. You can retrieve it from the 513 | * {@link ContentScriptContext | context}. 514 | * - `message` can be any basic JavaScript type (number, string, plain 515 | * object), but it cannot be a function or class instance. 516 | * 517 | * When you post a message, the plugin can send back a `response` thus 518 | * allowing two-way communication: 519 | * 520 | * ```javascript 521 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => { 522 | * // Process message 523 | * return response; // Can be any object, string or number 524 | * }); 525 | * ``` 526 | * 527 | * See {@link JoplinContentScripts.onMessage} for more details, as well as 528 | * the [postMessage 529 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages). 530 | * 531 | * ## Registering an existing Markdown-it plugin 532 | * 533 | * To include a regular Markdown-It plugin, that doesn't make use of any 534 | * Joplin-specific features, you would simply create a file such as this: 535 | * 536 | * ```javascript 537 | * module.exports = { 538 | * default: function(context) { 539 | * return { 540 | * plugin: require('markdown-it-toc-done-right'); 541 | * } 542 | * } 543 | * } 544 | * ``` 545 | */ 546 | MarkdownItPlugin = 'markdownItPlugin', 547 | 548 | /** 549 | * Registers a new CodeMirror plugin, which should follow the template 550 | * below. 551 | * 552 | * ```javascript 553 | * module.exports = { 554 | * default: function(context) { 555 | * return { 556 | * plugin: function(CodeMirror) { 557 | * // ... 558 | * }, 559 | * codeMirrorResources: [], 560 | * codeMirrorOptions: { 561 | * // ... 562 | * }, 563 | * assets: { 564 | * // ... 565 | * }, 566 | * } 567 | * } 568 | * } 569 | * ``` 570 | * 571 | * - The `context` argument is currently unused but could be used later on 572 | * to provide access to your own plugin so that the content script and 573 | * plugin can communicate. 574 | * 575 | * - The `plugin` key is your CodeMirror plugin. This is where you can 576 | * register new commands with CodeMirror or interact with the CodeMirror 577 | * instance as needed. 578 | * 579 | * - The `codeMirrorResources` key is an array of CodeMirror resources that 580 | * will be loaded and attached to the CodeMirror module. These are made up 581 | * of addons, keymaps, and modes. For example, for a plugin that want's to 582 | * enable clojure highlighting in code blocks. `codeMirrorResources` would 583 | * be set to `['mode/clojure/clojure']`. 584 | * 585 | * - The `codeMirrorOptions` key contains all the 586 | * [CodeMirror](https://codemirror.net/doc/manual.html#config) options 587 | * that will be set or changed by this plugin. New options can alse be 588 | * declared via 589 | * [`CodeMirror.defineOption`](https://codemirror.net/doc/manual.html#defineOption), 590 | * and then have their value set here. For example, a plugin that enables 591 | * line numbers would set `codeMirrorOptions` to `{'lineNumbers': true}`. 592 | * 593 | * - Using the **optional** `assets` key you may specify **only** CSS assets 594 | * that should be loaded in the rendered HTML document. Check for example 595 | * the Joplin [Mermaid 596 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts) 597 | * to see how the data should be structured. 598 | * 599 | * One of the `plugin`, `codeMirrorResources`, or `codeMirrorOptions` keys 600 | * must be provided for the plugin to be valid. Having multiple or all 601 | * provided is also okay. 602 | * 603 | * See also the [demo 604 | * plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/codemirror_content_script) 605 | * for an example of all these keys being used in one plugin. 606 | * 607 | * ## Posting messages from the content script to your plugin 608 | * 609 | * In order to post messages to the plugin, you can use the postMessage 610 | * function passed to the {@link ContentScriptContext | context}. 611 | * 612 | * ```javascript 613 | * const response = await context.postMessage('messageFromCodeMirrorContentScript'); 614 | * ``` 615 | * 616 | * When you post a message, the plugin can send back a `response` thus 617 | * allowing two-way communication: 618 | * 619 | * ```javascript 620 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => { 621 | * // Process message 622 | * return response; // Can be any object, string or number 623 | * }); 624 | * ``` 625 | * 626 | * See {@link JoplinContentScripts.onMessage} for more details, as well as 627 | * the [postMessage 628 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages). 629 | * 630 | */ 631 | CodeMirrorPlugin = 'codeMirrorPlugin', 632 | } 633 | -------------------------------------------------------------------------------- /assets/tags-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benji300/joplin-persistent-layout/89705479ff3459e365ab47327d0d2af02d9d5044/assets/tags-config.png -------------------------------------------------------------------------------- /joplin-persistent-layout.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ], 7 | "settings": { 8 | "editor.detectIndentation": false, 9 | "editor.insertSpaces": true, 10 | "editor.tabSize": 2, 11 | "files.exclude": { 12 | "**/dist": true, 13 | "**/node_modules": true, 14 | ".*": true, 15 | "*workspace": true 16 | } 17 | }, 18 | "tasks": { 19 | "version": "2.0.0", 20 | "presentation": { 21 | "clear": true, 22 | "panel": "shared" 23 | }, 24 | "problemMatcher": [], 25 | "windows": { 26 | "options": { 27 | "cwd": "${workspaceFolder}" 28 | } 29 | }, 30 | "tasks": [ 31 | { 32 | "label": "$(cloud-download) Install npm dependencies", 33 | "command": "npm install", 34 | "group": "build", 35 | "type": "shell" 36 | }, 37 | { 38 | "label": "Build Plugin", 39 | "command": "npm run dist", 40 | "type": "shell" 41 | }, 42 | { 43 | "label": "$(tag) Release Plugin", 44 | "command": "npm run release", 45 | "group": "build", 46 | "type": "shell" 47 | }, 48 | { 49 | "label": "$(compare-changes) Compare with user profile (BCompare)", 50 | "command": "C:/Program Files/Beyond Compare 4/BCompare.exe", 51 | "group": "build", 52 | "args": [ 53 | "./.config/${input:profile}/plugins/${workspaceFolderBasename}", 54 | "${workspaceFolder}/dist" 55 | ], 56 | "isBackground": true 57 | }, 58 | { 59 | "label": "$(compare-changes) Compare active file with...", 60 | "type": "process", 61 | "command": "${command:workbench.files.action.compareFileWith}", 62 | "group": "build", 63 | "isBackground": true, 64 | "windows": { 65 | "options": { 66 | "cwd": "C:/Users/${env:username}" 67 | } 68 | }, 69 | "problemMatcher": [] 70 | }, 71 | { 72 | "label": "$(window) Open Joplin", 73 | "command": "C:/Program Files/Joplin/Joplin.exe", 74 | "group": "build", 75 | "isBackground": true 76 | }, 77 | { 78 | "label": "$(window) Open Joplin (dev)", 79 | "command": "C:/Program Files/Joplin/Joplin.exe", 80 | "group": "build", 81 | "dependsOn": [ 82 | "Build Plugin" 83 | ], 84 | "args": [ 85 | "--env", 86 | "dev" 87 | ], 88 | "isBackground": true 89 | }, 90 | { 91 | "label": "$(refresh) Reload Joplin", 92 | "command": "powershell", 93 | "group": "build", 94 | "dependsOn": [ 95 | "Build Plugin" 96 | ], 97 | "args": [ 98 | "Stop-Process -Name \"Joplin\";", 99 | "& 'C:/Program Files/Joplin/Joplin.exe'" 100 | ], 101 | "isBackground": true 102 | }, 103 | { 104 | "label": "$(refresh) Reload Joplin (dev)", 105 | "command": "powershell", 106 | "group": { 107 | "isDefault": true, 108 | "kind": "build" 109 | }, 110 | "dependsOn": [ 111 | "Build Plugin" 112 | ], 113 | "args": [ 114 | "Stop-Process -Name \"Joplin\";", 115 | "& 'C:/Program Files/Joplin/Joplin.exe' --env dev" 116 | ], 117 | "isBackground": true 118 | }, 119 | { 120 | "label": "$(folder-opened) Open user profile directory", 121 | "command": "powershell", 122 | "group": "build", 123 | "args": [ 124 | "Invoke-Item ./.config/${input:profile}" 125 | ], 126 | "isBackground": true, 127 | "windows": { 128 | "options": { 129 | "cwd": "C:/Users/${env:username}" 130 | } 131 | } 132 | } 133 | ], 134 | "inputs": [ 135 | { 136 | "id": "profile", 137 | "description": "Select user profile directory", 138 | "type": "pickString", 139 | "default": "default", 140 | "options": [ 141 | "joplin-desktop", 142 | "joplindev-desktop" 143 | ] 144 | } 145 | ] 146 | }, 147 | "extensions": { 148 | "recommendations": [ 149 | "ms-vscode.vscode-typescript-next" 150 | ] 151 | } 152 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joplin-plugin-persistent-editor-layout", 3 | "version": "2.2.0", 4 | "description": "Save the editor layout (editor/split view/viewer/rich text) for each note separately with custom tags.", 5 | "author": "Benji300", 6 | "homepage": "https://github.com/benji300/joplin-persistent-layout", 7 | "bugs": { 8 | "url": "https://github.com/benji300/joplin-persistent-layout/issues" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/benji300/joplin-persistent-layout.git" 13 | }, 14 | "scripts": { 15 | "dist": "webpack --joplin-plugin-config buildMain && webpack --joplin-plugin-config buildExtraScripts && webpack --joplin-plugin-config createArchive", 16 | "prepare": "npm run dist", 17 | "update": "npm install -g generator-joplin && yo joplin --update" 18 | }, 19 | "license": "MIT", 20 | "keywords": [ 21 | "joplin-plugin" 22 | ], 23 | "devDependencies": { 24 | "@types/node": "^14.14.37", 25 | "chalk": "^4.1.0", 26 | "copy-webpack-plugin": "^6.1.0", 27 | "fs-extra": "^9.0.1", 28 | "glob": "^7.1.6", 29 | "on-build-webpack": "^0.1.0", 30 | "tar": "^6.1.7", 31 | "ts-loader": "^7.0.5", 32 | "typescript": "^3.9.9", 33 | "webpack": "^4.43.0", 34 | "webpack-cli": "^3.3.11", 35 | "yargs": "^16.2.0" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /plugin.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "extraScripts": [] 3 | } -------------------------------------------------------------------------------- /src/Layout.ts: -------------------------------------------------------------------------------- 1 | interface ILayoutDesc { 2 | valid: boolean 3 | codeView: boolean, 4 | panes: string[] 5 | } 6 | 7 | const LayoutDesc: ILayoutDesc[] = [ 8 | { valid: false, codeView: true, panes: [""] }, // none 9 | { valid: true, codeView: true, panes: ["editor"] }, // editor 10 | { valid: true, codeView: true, panes: ["editor", "viewer"] }, // split view 11 | { valid: true, codeView: true, panes: ["viewer"] }, // viewer 12 | { valid: true, codeView: false, panes: [""] }, // rich text (WYSIWYG) 13 | { valid: true, codeView: false, panes: [""] }, // previous 14 | ]; 15 | 16 | export enum LayoutType { 17 | None = 0, 18 | Editor = 1, 19 | Split = 2, 20 | Viewer = 3, 21 | Richtext = 4, // WYSIWYG 22 | Previous = 5 23 | } 24 | 25 | export class Layout { 26 | private _type: LayoutType = LayoutType.None; 27 | 28 | private constructor(type: LayoutType) { 29 | this._type = type; 30 | } 31 | 32 | get type(): LayoutType { 33 | return this._type; 34 | } 35 | 36 | static create(type: LayoutType): Layout { 37 | return new Layout(type); 38 | } 39 | 40 | static matchesVisiblePanes(type: LayoutType, visiblePanes: any[]): boolean { 41 | // noteVisiblePanes = ["editor","viewer"] 42 | return (LayoutDesc[type].panes.sort().toString() == visiblePanes.sort().toString()); 43 | } 44 | 45 | static getLayoutType(codeView: boolean, visiblePanes: any[]): LayoutType { 46 | if (codeView) { 47 | if (Layout.matchesVisiblePanes(LayoutType.Editor, visiblePanes)) { 48 | return LayoutType.Editor; 49 | } else if (Layout.matchesVisiblePanes(LayoutType.Split, visiblePanes)) { 50 | return LayoutType.Split; 51 | } else if (Layout.matchesVisiblePanes(LayoutType.Viewer, visiblePanes)) { 52 | return LayoutType.Viewer; 53 | } else { 54 | return LayoutType.None; 55 | } 56 | } else { 57 | return LayoutType.Richtext; 58 | } 59 | } 60 | 61 | set(layout: LayoutType) { 62 | this._type = layout; 63 | } 64 | 65 | isValid(): boolean { 66 | return LayoutDesc[this._type].valid; 67 | } 68 | 69 | isCodeView(): boolean { 70 | return LayoutDesc[this._type].codeView; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/data.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import { Path } from 'api/types'; 3 | 4 | /** 5 | * Helper class for data accesses. 6 | */ 7 | export class DA { 8 | 9 | private static async getAll(path: Path, query: any): Promise { 10 | query.page = 1; 11 | let response = await joplin.data.get(path, query); 12 | // console.log(`response: ${JSON.stringify(response)}`); 13 | let result = !!response.items ? response.items : []; 14 | while (!!response.has_more) { 15 | // console.log(`has_more`); 16 | query.page += 1; 17 | response = await joplin.data.get(path, query); 18 | result.concat(response.items) 19 | } 20 | // console.log(`result: ${JSON.stringify(result)}`); 21 | return result; 22 | } 23 | 24 | /** 25 | * Gets all folders sorted by their title. 26 | * By default it includes the fields: id, title, parent_id 27 | */ 28 | static async getFolders(extraFields?: string[]): Promise { 29 | try { 30 | const fields: string[] = ['id', 'title', 'parent_id']; 31 | if (extraFields) fields.push(...extraFields); 32 | return await DA.getAll(['folders'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }); 33 | } catch (e) { 34 | return []; 35 | } 36 | } 37 | 38 | /** 39 | * Gets all folders sorted by their title and filtered by the handled predicate. 40 | * By default it includes the fields: id, title, parent_id 41 | */ 42 | static async getFoldersFiltered(predicate: (value: any, index: number, array: any[]) => unknown, extraFields?: string[]): Promise { 43 | try { 44 | const fields: string[] = ['id', 'title', 'parent_id']; 45 | if (extraFields) fields.push(...extraFields); 46 | const folders: any[] = await DA.getAll(['folders'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }) 47 | return folders.filter(predicate); 48 | } catch (e) { 49 | return []; 50 | } 51 | } 52 | 53 | /** 54 | * Gets all subfolders of the handled folder sorted by their title. 55 | * By default it includes the fields: id, title, parent_id 56 | */ 57 | static async getFoldersOfFolder(folderId: string, extraFields?: string[]): Promise { 58 | return await DA.getFoldersFiltered(x => x.parent_id === folderId, extraFields); 59 | } 60 | 61 | /** 62 | * Gets the folder with the handle ID or null. 63 | * By default it includes the fields: id, title 64 | */ 65 | static async getFolder(id: string, extraFields?: string[]): Promise { 66 | try { 67 | const fields: string[] = ['id', 'title', 'parent_id']; 68 | if (extraFields) fields.push(...extraFields); 69 | return await joplin.data.get(['folders', id], { fields: fields }); 70 | } catch (e) { 71 | return null; 72 | } 73 | } 74 | 75 | /** 76 | * Gets all notes sorted by their title. 77 | * By default it includes the fields: id, title, is_todo 78 | */ 79 | static async getNotes(extraFields?: string[]): Promise { 80 | try { 81 | const fields: string[] = ['id', 'title', 'is_todo']; 82 | if (extraFields) fields.push(...extraFields); 83 | return await DA.getAll(['notes'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }); 84 | } catch (e) { 85 | return []; 86 | } 87 | } 88 | 89 | /** 90 | * Gets all notes sorted by their title and filtered by the handled predicate. 91 | * By default it includes the fields: id, title, is_todo 92 | */ 93 | static async getNotesFiltered(predicate: (value: any, index: number, array: any[]) => unknown, extraFields?: string[]): Promise { 94 | try { 95 | const fields: string[] = ['id', 'title', 'is_todo']; 96 | if (extraFields) fields.push(...extraFields); 97 | const notes: any[] = await DA.getAll(['notes'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }); 98 | return notes.filter(predicate); 99 | } catch (e) { 100 | return []; 101 | } 102 | } 103 | 104 | /** 105 | * Gets all notes of the handled folder sorted by their title. 106 | * By default it includes the fields: id, title, is_todo 107 | */ 108 | static async getNotesOfFolder(folderId: string, extraFields?: string[]): Promise { 109 | try { 110 | const fields: string[] = ['id', 'title', 'is_todo']; 111 | if (extraFields) fields.push(...extraFields); 112 | return await DA.getAll(['folders', folderId, 'notes'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }); 113 | } catch (e) { 114 | return []; 115 | } 116 | } 117 | 118 | /** 119 | * Gets all notes of the handled folder sorted by their title. 120 | * By default it includes the fields: id, title, is_todo 121 | */ 122 | static async getNotesOfTag(tagId: string, extraFields?: string[]): Promise { 123 | try { 124 | const fields: string[] = ['id', 'title', 'is_todo']; 125 | if (extraFields) fields.push(...extraFields); 126 | return await DA.getAll(['tags', tagId, 'notes'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }); 127 | } catch (e) { 128 | return []; 129 | } 130 | } 131 | 132 | /** 133 | * Gets the note with the handle ID or null. 134 | * By default it includes the fields: id, title, is_todo 135 | */ 136 | static async getNote(id: string, extraFields?: string[]): Promise { 137 | try { 138 | const fields: string[] = ['id', 'title', 'is_todo']; 139 | if (extraFields) fields.push(...extraFields); 140 | return await joplin.data.get(['notes', id], { fields: fields }); 141 | } catch (e) { 142 | return null; 143 | } 144 | } 145 | 146 | /** 147 | * Gets All tags sortedsorted by their title. 148 | * By default it includes the fields: id, title 149 | */ 150 | static async getTags(extraFields?: string[]): Promise { 151 | try { 152 | const fields: string[] = ['id', 'title']; 153 | if (extraFields) fields.push(...extraFields); 154 | return await DA.getAll(['tags'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }); 155 | } catch (e) { 156 | return []; 157 | } 158 | } 159 | 160 | /** 161 | * Gets all tags of the handled note sorted by their title. 162 | * By default it includes the fields: id, title 163 | */ 164 | static async getTagsOfNote(noteId: string, extraFields?: string[]): Promise { 165 | try { 166 | const fields: string[] = ['id', 'title']; 167 | if (extraFields) fields.push(...extraFields); 168 | return await DA.getAll(['notes', noteId, 'tags'], { fields: fields, order_by: 'title', order_dir: 'ASC', page: 1 }); 169 | } catch (e) { 170 | return []; 171 | } 172 | } 173 | 174 | /** 175 | * Gets the tag with the handle ID or null. 176 | * By default it includes the fields: id, title 177 | */ 178 | static async getTag(id: string, extraFields?: string[]): Promise { 179 | try { 180 | const fields: string[] = ['id', 'title']; 181 | if (extraFields) fields.push(...extraFields); 182 | return await joplin.data.get(['tags', id], { fields: fields }); 183 | } catch (e) { 184 | return null; 185 | } 186 | } 187 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import { ChangeEvent } from 'api/JoplinSettings'; 3 | import { Settings } from './settings'; 4 | import { DA } from './data'; 5 | import { Layout, LayoutType } from './Layout'; 6 | 7 | let previousSelectedNoteId: string = ''; 8 | let previousLayoutType: LayoutType = LayoutType.Editor; 9 | let lastNoteId: string = ''; 10 | 11 | joplin.plugins.register({ 12 | onStart: async function () { 13 | const SETTINGS = joplin.settings; 14 | const WORKSPACE = joplin.workspace; 15 | // settings 16 | const settings: Settings = new Settings(); 17 | await settings.register(); 18 | 19 | //#region HELPERS 20 | 21 | function checkMatchingTags(noteTags: any[], layoutTags: string[]): boolean { 22 | return (noteTags.findIndex(tag => layoutTags.includes(tag.title.toLocaleLowerCase())) >= 0); 23 | } 24 | 25 | async function toggleVisiblePanes(layout: Layout) { 26 | // console.debug(`Toggle layout: ${JSON.stringify(layout)}`); 27 | const codeView: boolean = await settings.editorCodeView; 28 | 29 | // toggle markdown/rich text editor 30 | if (layout.isCodeView() != codeView) { 31 | // console.debug(`toggleEditors`); 32 | await joplin.commands.execute('toggleEditors'); 33 | } 34 | 35 | // toggle panes for markdown editor 36 | if (layout.isCodeView()) { 37 | for (let i: number = 0; i < 3; i++) { 38 | const visiblePanes: any[] = await settings.noteVisiblePanes; 39 | if (Layout.matchesVisiblePanes(layout.type, visiblePanes)) { 40 | break; 41 | } 42 | // console.debug(`toggleVisiblePanes`); 43 | await joplin.commands.execute('toggleVisiblePanes'); 44 | } 45 | } 46 | } 47 | 48 | //#endregion 49 | 50 | //#region COMMANDS 51 | 52 | //#endregion 53 | 54 | //#region EVENTS 55 | 56 | WORKSPACE.onNoteSelectionChange(async () => { 57 | try { 58 | const selectedNote: any = await WORKSPACE.selectedNote(); 59 | 60 | if (selectedNote) { 61 | console.debug(`selected note: ${selectedNote.title}`); 62 | 63 | // to prevent redundant callback activations 64 | if (selectedNote.id === previousSelectedNoteId) return; 65 | previousSelectedNoteId = selectedNote.id; 66 | const noteTags: any[] = await DA.getTagsOfNote(selectedNote.id); 67 | let layout: Layout = Layout.create(settings.defaultLayout); 68 | 69 | if (checkMatchingTags(noteTags, settings.editorTags)) { // editor 70 | layout.set(LayoutType.Editor); 71 | } else if (checkMatchingTags(noteTags, settings.splitTags)) { // split view 72 | layout.set(LayoutType.Split); 73 | } else if (checkMatchingTags(noteTags, settings.viewerTags)) { // viewer 74 | layout.set(LayoutType.Viewer); 75 | } else if (checkMatchingTags(noteTags, settings.richtextTags)) { // rich text 76 | layout.set(LayoutType.Richtext); 77 | } else { // no layout tags 78 | 79 | // set to previously stored layout if enabled by settings 80 | if (layout.type == LayoutType.Previous) { 81 | if (previousLayoutType != LayoutType.None) { 82 | layout.set(previousLayoutType); 83 | // console.debug(`set layout type to previous: ${previousLayoutType}`); 84 | } 85 | } 86 | } 87 | 88 | // store layout from previous note w/o layout tags 89 | if (lastNoteId) { 90 | const lastNoteTags: any[] = await DA.getTagsOfNote(lastNoteId); 91 | if (!checkMatchingTags(lastNoteTags, settings.allLayoutTags)) { 92 | const codeView: boolean = await settings.editorCodeView; 93 | const visiblePanes: any[] = await settings.noteVisiblePanes; 94 | previousLayoutType = Layout.getLayoutType(codeView, visiblePanes); 95 | // console.debug(`store layout type: ${previousLayoutType}`); 96 | } 97 | } 98 | 99 | // toggle panes 100 | if (layout.isValid()) { 101 | await toggleVisiblePanes(layout); 102 | } 103 | 104 | // store selected note id as last 105 | lastNoteId = selectedNote.id; 106 | } else { 107 | previousSelectedNoteId = ''; 108 | } 109 | } catch (error) { 110 | console.error(`onNoteSelectionChange: ${error}`); 111 | } 112 | }); 113 | 114 | // let onChangeCnt = 0; 115 | SETTINGS.onChange(async (event: ChangeEvent) => { 116 | // console.debug(`onChange() hits: ${onChangeCnt++}`); 117 | await settings.read(event); 118 | }); 119 | 120 | //#endregion 121 | } 122 | }); 123 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 1, 3 | "id": "joplin.plugin.benji.persistentLayout", 4 | "app_min_version": "1.8.2", 5 | "version": "2.2.0", 6 | "name": "Persistent Editor Layout", 7 | "description": "Save the editor layout (editor/split view/viewer/rich text) for each note separately with custom tags.", 8 | "author": "Benji300", 9 | "homepage_url": "https://github.com/benji300/joplin-persistent-layout", 10 | "repository_url": "https://github.com/benji300/joplin-persistent-layout", 11 | "keywords": [ 12 | "notes", 13 | "editor", 14 | "split", 15 | "viewer", 16 | "view", 17 | "save", 18 | "store" 19 | ] 20 | } -------------------------------------------------------------------------------- /src/settings.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import { SettingItemType } from 'api/types'; 3 | import { ChangeEvent } from 'api/JoplinSettings'; 4 | import { LayoutType } from './Layout'; 5 | 6 | /** 7 | * Advanced style setting default values. 8 | * Used when setting is set to 'default'. 9 | */ 10 | export enum SettingDefaults { 11 | Empty = '0', 12 | Default = 'default', 13 | Editor = 'layout:editor', 14 | Split = 'layout:split', 15 | Viewer = 'layout:viewer', 16 | Richtext = 'layout:richtext' 17 | } 18 | 19 | /** 20 | * Definitions of plugin settings. 21 | */ 22 | export class Settings { 23 | // private settings 24 | // none 25 | // general settings 26 | private _defaultLayout: LayoutType = LayoutType.None; 27 | private _editorTags: string = SettingDefaults.Editor; 28 | private _splitTags: string = SettingDefaults.Split; 29 | private _viewerTags: string = SettingDefaults.Viewer; 30 | private _richtextTags: string = SettingDefaults.Richtext; 31 | // advanced settings 32 | // none 33 | // internals 34 | private _defaultRegExp: RegExp = new RegExp(SettingDefaults.Default, 'i'); 35 | private _whiteSpaceRegExp: RegExp = new RegExp(/\s/, 'gi'); 36 | 37 | constructor() { 38 | } 39 | 40 | private asArray(tags: string): string[] { 41 | return tags.trim().replace(this._whiteSpaceRegExp, '').toLocaleLowerCase().split(','); 42 | } 43 | 44 | //#region GETTER 45 | 46 | get defaultLayout(): LayoutType { 47 | return this._defaultLayout; 48 | } 49 | 50 | get allLayoutTags(): string[] { 51 | let arr: string[] = [...this.editorTags, ...this.splitTags, ...this.viewerTags, ...this.richtextTags]; 52 | return arr; 53 | } 54 | 55 | get editorTags(): string[] { 56 | return this.asArray(this._editorTags); 57 | } 58 | 59 | get splitTags(): string[] { 60 | return this.asArray(this._splitTags); 61 | } 62 | 63 | get viewerTags(): string[] { 64 | return this.asArray(this._viewerTags); 65 | } 66 | 67 | get richtextTags(): string[] { 68 | return this.asArray(this._richtextTags); 69 | } 70 | 71 | //#endregion 72 | 73 | //#region GLOBAL VALUES 74 | 75 | get editorCodeView(): Promise { 76 | return joplin.settings.globalValue('editor.codeView'); 77 | } 78 | 79 | get noteVisiblePanes(): Promise { 80 | return joplin.settings.globalValue('noteVisiblePanes'); 81 | } 82 | 83 | //#endregion 84 | 85 | /** 86 | * Register settings section with all options and intially read them at the end. 87 | */ 88 | async register() { 89 | 90 | // register settings in own section 91 | await joplin.settings.registerSection('persistent.layout.settings', { 92 | label: 'Persistent Layout', 93 | iconName: 'fas fa-columns' 94 | }); 95 | await joplin.settings.registerSettings({ 96 | // private settings 97 | // none 98 | // general settings 99 | defaultLayout: { 100 | value: LayoutType.None, 101 | type: SettingItemType.Int, 102 | section: 'persistent.layout.settings', 103 | isEnum: true, 104 | public: true, 105 | label: 'Default editor layout', 106 | description: 'Default editor layout which is used for all notes that have no layout tags specified. ' + 107 | 'If "None" (empty) is selected, the current active layout is kept. ' + 108 | 'If "Previous" is selected, the last layout which was active on the last selcted note without layout tags is restored.', 109 | options: { 110 | '0': ' ', 111 | '1': 'Editor', 112 | '2': 'Split View', 113 | '3': 'Viewer', 114 | '4': 'Rich Text', 115 | '5': 'Previous' 116 | }, 117 | }, 118 | editorTags: { 119 | value: this._editorTags, 120 | type: SettingItemType.String, 121 | section: 'persistent.layout.settings', 122 | public: true, 123 | label: 'Tags for editor layout mode: Markdown editor', 124 | description: 'Specify as comma-separated list.' 125 | }, 126 | splitTags: { 127 | value: this._splitTags, 128 | type: SettingItemType.String, 129 | section: 'persistent.layout.settings', 130 | public: true, 131 | label: 'Tags for editor layout mode: Split view', 132 | description: 'Specify as comma-separated list.' 133 | }, 134 | viewerTags: { 135 | value: this._viewerTags, 136 | type: SettingItemType.String, 137 | section: 'persistent.layout.settings', 138 | public: true, 139 | label: 'Tags for editor layout mode: Rendered Markdown viewer', 140 | description: 'Specify as comma-separated list.' 141 | }, 142 | richtextTags: { 143 | value: this._richtextTags, 144 | type: SettingItemType.String, 145 | section: 'persistent.layout.settings', 146 | public: true, 147 | label: 'Tags for editor layout mode: Rich text (WYSIWYG)', 148 | description: 'Specify as comma-separated list.' 149 | }, 150 | // advanced settings 151 | // none 152 | }); 153 | 154 | // initially read settings 155 | await this.read(); 156 | } 157 | 158 | private async getOrDefault(event: ChangeEvent, localVar: any, setting: string, defaultValue?: string): Promise { 159 | const read: boolean = (!event || event.keys.includes(setting)); 160 | if (read) { 161 | const value: string = await joplin.settings.value(setting); 162 | if (defaultValue && value.match(this._defaultRegExp)) { 163 | return defaultValue; 164 | } else { 165 | return value; 166 | } 167 | } 168 | return localVar; 169 | } 170 | 171 | /** 172 | * Update settings. Either all or only changed ones. 173 | */ 174 | async read(event?: ChangeEvent) { 175 | this._defaultLayout = await this.getOrDefault(event, this._defaultLayout, 'defaultLayout'); 176 | this._editorTags = await this.getOrDefault(event, this._editorTags, 'editorTags'); 177 | this._splitTags = await this.getOrDefault(event, this._splitTags, 'splitTags'); 178 | this._viewerTags = await this.getOrDefault(event, this._viewerTags, 'viewerTags'); 179 | this._richtextTags = await this.getOrDefault(event, this._richtextTags, 'richtextTags'); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /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 | // JSON files can also be required from scripts so we include this. 139 | // https://github.com/joplin/plugin-bibtex/pull/2 140 | extensions: ['.tsx', '.ts', '.js', '.json'], 141 | }, 142 | output: { 143 | filename: 'index.js', 144 | path: distDir, 145 | }, 146 | plugins: [ 147 | new CopyPlugin({ 148 | patterns: [ 149 | { 150 | from: '**/*', 151 | context: path.resolve(__dirname, 'src'), 152 | to: path.resolve(__dirname, 'dist'), 153 | globOptions: { 154 | ignore: [ 155 | // All TypeScript files are compiled to JS and 156 | // already copied into /dist so we don't copy them. 157 | '**/*.ts', 158 | '**/*.tsx', 159 | ], 160 | }, 161 | }, 162 | ], 163 | }), 164 | ], 165 | }); 166 | 167 | const extraScriptConfig = Object.assign({}, baseConfig, { 168 | resolve: { 169 | alias: { 170 | api: path.resolve(__dirname, 'api'), 171 | }, 172 | extensions: ['.tsx', '.ts', '.js', '.json'], 173 | }, 174 | }); 175 | 176 | const createArchiveConfig = { 177 | stats: 'errors-only', 178 | entry: './dist/index.js', 179 | output: { 180 | filename: 'index.js', 181 | path: publishDir, 182 | }, 183 | plugins: [new WebpackOnBuildPlugin(onBuildCompleted)], 184 | }; 185 | 186 | function resolveExtraScriptPath(name) { 187 | const relativePath = `./src/${name}`; 188 | 189 | const fullPath = path.resolve(`${rootDir}/${relativePath}`); 190 | if (!fs.pathExistsSync(fullPath)) throw new Error(`Could not find extra script: "${name}" at "${fullPath}"`); 191 | 192 | const s = name.split('.'); 193 | s.pop(); 194 | const nameNoExt = s.join('.'); 195 | 196 | return { 197 | entry: relativePath, 198 | output: { 199 | filename: `${nameNoExt}.js`, 200 | path: distDir, 201 | library: 'default', 202 | libraryTarget: 'commonjs', 203 | libraryExport: 'default', 204 | }, 205 | }; 206 | } 207 | 208 | function buildExtraScriptConfigs(userConfig) { 209 | if (!userConfig.extraScripts.length) return []; 210 | 211 | const output = []; 212 | 213 | for (const scriptName of userConfig.extraScripts) { 214 | const scriptPaths = resolveExtraScriptPath(scriptName); 215 | output.push(Object.assign({}, extraScriptConfig, { 216 | entry: scriptPaths.entry, 217 | output: scriptPaths.output, 218 | })); 219 | } 220 | 221 | return output; 222 | } 223 | 224 | function main(processArgv) { 225 | const yargs = require('yargs/yargs'); 226 | const argv = yargs(processArgv).argv; 227 | 228 | const configName = argv['joplin-plugin-config']; 229 | if (!configName) throw new Error('A config file must be specified via the --joplin-plugin-config flag'); 230 | 231 | // Webpack configurations run in parallel, while we need them to run in 232 | // sequence, and to do that it seems the only way is to run webpack multiple 233 | // times, with different config each time. 234 | 235 | const configs = { 236 | // Builds the main src/index.ts and copy the extra content from /src to 237 | // /dist including scripts, CSS and any other asset. 238 | buildMain: [pluginConfig], 239 | 240 | // Builds the extra scripts as defined in plugin.config.json. When doing 241 | // so, some JavaScript files that were copied in the previous might be 242 | // overwritten here by the compiled version. This is by design. The 243 | // result is that JS files that don't need compilation, are simply 244 | // copied to /dist, while those that do need it are correctly compiled. 245 | buildExtraScripts: buildExtraScriptConfigs(userConfig), 246 | 247 | // Ths config is for creating the .jpl, which is done via the plugin, so 248 | // it doesn't actually need an entry and output, however webpack won't 249 | // run without this. So we give it an entry that we know is going to 250 | // exist and output in the publish dir. Then the plugin will delete this 251 | // temporary file before packaging the plugin. 252 | createArchive: [createArchiveConfig], 253 | }; 254 | 255 | // If we are running the first config step, we clean up and create the build 256 | // directories. 257 | if (configName === 'buildMain') { 258 | fs.removeSync(distDir); 259 | fs.removeSync(publishDir); 260 | fs.mkdirpSync(publishDir); 261 | } 262 | 263 | return configs[configName]; 264 | } 265 | 266 | let exportedConfigs = []; 267 | 268 | try { 269 | exportedConfigs = main(process.argv); 270 | } catch (error) { 271 | console.error(chalk.red(error.message)); 272 | process.exit(1); 273 | } 274 | 275 | if (!exportedConfigs.length) { 276 | // Nothing to do - for example where there are no external scripts to 277 | // compile. 278 | process.exit(0); 279 | } 280 | 281 | module.exports = exportedConfigs; 282 | --------------------------------------------------------------------------------