├── .gitignore ├── .npmignore ├── GENERATOR_DOC.md ├── 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 ├── package.json ├── plugin.config.json ├── screenshot ├── dailynote.png ├── history.png └── tab-panels.png ├── src ├── aggregateSearch │ ├── index.ts │ └── test.tsx ├── codemirror │ ├── autoCompletion │ │ ├── index.ts │ │ └── quickCommands.ts │ ├── commands │ │ ├── commands.ts │ │ └── index.ts │ ├── noteRefCompletion │ │ ├── index.ts │ │ └── noteRefCompletion.ts │ └── paperCiteCompletion │ │ ├── index.ts │ │ └── paperCiteCompletion.ts ├── common.ts ├── dailyNote │ ├── htmlGenerator.tsx │ ├── index.ts │ ├── panelHtml.ts │ ├── settings.ts │ └── utils.ts ├── groups │ └── index.ts ├── history │ ├── history.ts │ ├── index.ts │ ├── panel.ts │ └── settings.ts ├── index.ts ├── inlineTodo │ ├── builder.ts │ ├── common.ts │ ├── index.ts │ ├── mark_todo.ts │ ├── panelHtml.ts │ ├── settings.ts │ ├── todoEngine.ts │ ├── todoRender │ │ ├── conferenceStyleRender.ts │ │ ├── index.ts │ │ └── todoRender.css │ ├── types.ts │ └── utils.ts ├── locale.ts ├── manifest.json ├── outline │ ├── index.ts │ ├── mdHeaders.ts │ ├── panelHtml.ts │ └── settings.ts ├── readcube │ ├── common.ts │ ├── driver │ │ ├── codemirror │ │ │ ├── autoCitation │ │ │ │ ├── index.ts │ │ │ │ └── insertCitation.ts │ │ │ └── paperBlockRender │ │ │ │ ├── index.ts │ │ │ │ └── paperLineWidget.css │ │ ├── markdownItRenderer │ │ │ └── paperFence │ │ │ │ ├── index.ts │ │ │ │ ├── paperFence.css │ │ │ │ └── paperRender.js │ │ └── style │ │ │ ├── index.ts │ │ │ └── paperStyle.css │ ├── index.ts │ ├── lib │ │ ├── PaperSvcFactory.ts │ │ ├── base │ │ │ ├── paperDB.ts │ │ │ ├── paperExtend.ts │ │ │ ├── paperNotify.ts │ │ │ ├── paperSvc.ts │ │ │ └── paperType.ts │ │ ├── papers │ │ │ ├── papersUtils.ts │ │ │ ├── papersWS.ts │ │ │ └── readcubePaperSvc.ts │ │ └── zotero │ │ │ ├── zoteroPaperSvc.ts │ │ │ └── zoteroWS.ts │ ├── panelHtml.ts │ ├── readcube.ts │ ├── settings.ts │ ├── ui │ │ └── citation-popup │ │ │ ├── index.ts │ │ │ ├── lib │ │ │ ├── autoComplete.min.css │ │ │ ├── autoComplete.min.js │ │ │ └── he.min.js │ │ │ ├── view.css │ │ │ ├── view.html │ │ │ └── view.js │ └── utils │ │ ├── CMBlockMarkerHelperV2.ts │ │ ├── click-and-clear.ts │ │ ├── cm-utils.ts │ │ ├── paperCardGenerator.ts │ │ └── reg.ts ├── relatedNotes │ ├── engine.ts │ ├── index.ts │ ├── panelHtml.ts │ ├── settings.ts │ └── types.ts ├── scripts │ ├── dailyNote │ │ ├── dailyNote.css │ │ ├── dailyNote.js │ │ └── dialog.css │ ├── history │ │ ├── history.css │ │ └── history.js │ ├── inlineTodo │ │ ├── inlineTodo.css │ │ └── inlineTodo.js │ ├── outline │ │ ├── webview.css │ │ └── webview.js │ ├── readcube │ │ ├── popup.css │ │ ├── readcube.css │ │ └── readcube.js │ ├── relatedNotes │ │ ├── relatedNotes.css │ │ └── relatedNotes.js │ ├── sidebars │ │ ├── bootstrap.bundle.min.js │ │ ├── bootstrap.min.css │ │ ├── custom.css │ │ └── sidebars.js │ └── writingMarker │ │ ├── writingMarker.css │ │ └── writingMarker.js ├── settings.ts ├── sidebars │ └── sidebarPage.ts ├── utils │ ├── noteUpdateNotify.ts │ ├── noteUtils.ts │ └── stringUtils.ts └── writingMarker │ ├── common.ts │ ├── htmlGenerator.tsx │ ├── index.ts │ ├── panelHtml.ts │ └── utils.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 | -------------------------------------------------------------------------------- /GENERATOR_DOC.md: -------------------------------------------------------------------------------- 1 | # generator-joplin 2 | 3 | Scaffolds out a new Joplin plugin 4 | 5 | ## Installation 6 | 7 | First, install [Yeoman](http://yeoman.io) and generator-joplin using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)). 8 | 9 | ```bash 10 | npm install -g yo 11 | npm install -g generator-joplin 12 | ``` 13 | 14 | Then generate your new project: 15 | 16 | ```bash 17 | yo joplin 18 | ``` 19 | 20 | ## Development 21 | 22 | To test the generator for development purposes, follow the instructions there: https://yeoman.io/authoring/#running-the-generator 23 | This is a template to create a new Joplin plugin. 24 | 25 | ## Structure 26 | 27 | The main two files you will want to look at are: 28 | 29 | - `/src/index.ts`, which contains the entry point for the plugin source code. 30 | - `/src/manifest.json`, which is the plugin manifest. It contains information such as the plugin a name, version, etc. 31 | 32 | The file `/plugin.config.json` could also be useful if you intend to use [external scripts](#external-script-files), such as content scripts or webview scripts. 33 | 34 | ## Building the plugin 35 | 36 | The plugin is built using Webpack, which creates the compiled code in `/dist`. A JPL archive will also be created at the root, which can use to distribute the plugin. 37 | 38 | To build the plugin, simply run `npm run dist`. 39 | 40 | The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript. 41 | 42 | ## Publishing the plugin 43 | 44 | To publish the plugin, add it to npmjs.com by running `npm publish`. Later on, a script will pick up your plugin and add it automatically to the Joplin plugin repository as long as the package satisfies these conditions: 45 | 46 | - In `package.json`, the name starts with "joplin-plugin-". For example, "joplin-plugin-toc". 47 | - In `package.json`, the keywords include "joplin-plugin". 48 | - In the `publish/` directory, there should be a .jpl and .json file (which are built by `npm run dist`) 49 | 50 | In general all this is done automatically by the plugin generator, which will set the name and keywords of package.json, and will put the right files in the "publish" directory. But if something doesn't work and your plugin doesn't appear in the repository, double-check the above conditions. 51 | 52 | ## Updating the plugin framework 53 | 54 | To update the plugin framework, run `npm run update`. 55 | 56 | In general this command tries to do the right thing - in particular it's going to merge the changes in package.json and .gitignore instead of overwriting. It will also leave "/src" as well as README.md untouched. 57 | 58 | The file that may cause problem is "webpack.config.js" because it's going to be overwritten. For that reason, if you want to change it, consider creating a separate JavaScript file and include it in webpack.config.js. That way, when you update, you only have to restore the line that include your file. 59 | 60 | ## External script files 61 | 62 | By default, the compiler (webpack) is going to compile `src/index.ts` only (as well as any file it imports), and any other file will simply be copied to the plugin package. In some cases this is sufficient, however if you have [content scripts](https://joplinapp.org/api/references/plugin_api/classes/joplincontentscripts.html) or [webview scripts](https://joplinapp.org/api/references/plugin_api/classes/joplinviewspanels.html#addscript) you might want to compile them too, in particular in these two cases: 63 | 64 | - The script is a TypeScript file - in which case it has to be compiled to JavaScript. 65 | 66 | - The script requires modules you've added to package.json. In that case, the script, whether JS or TS, must be compiled so that the dependencies are bundled with the JPL file. 67 | 68 | To get such an external script file to compile, you need to add it to the `extraScripts` array in `plugin.config.json`. The path you add should be relative to /src. For example, if you have a file in "/src/webviews/index.ts", the path should be set to "webviews/index.ts". Once compiled, the file will always be named with a .js extension. So you will get "webviews/index.js" in the plugin package, and that's the path you should use to reference the file. 69 | 70 | ## License 71 | 72 | MIT © Laurent Cozic 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Joplin Plugin Bundle 2 | 3 | Plugins in one panel. Some of the plugins come from other repo, and I modified them to show all the plugin panels in the same panel under different tabs. 4 | 5 | > **Why?** : Save my screen space by aggregating those plugins into one panel 6 | 7 | > **How?** : Copy & Paste code from existing plugins, and modify them at the code level. I cannot figure out a non-intrusive way to gather them together in one panel. 8 | 9 | Current plugins: 10 | 11 | * Outline (v1.3.1): https://github.com/cqroot/joplin-outline 12 | * Inline Todo (v1.4.0): https://github.com/CalebJohn/joplin-inline-todo 13 | * Four different categories: Today, Scheduled, Inbox, and Filter 14 | * Click the todo items to open corresponding notes 15 | * Show task priority in different colors 16 | * Syntax: 17 | * @Project 18 | * +tag 19 | * //date 20 | * !1 !2 !3 !4: Four level task priority. 1 > 2 > 3 > 4. Default is 4. 21 | * Daily Note: Idea from https://github.com/liamcain/obsidian-calendar-plugin 22 | * Show whether there is a note for each day in month calendar 23 | * Click on any day to create a note or open the existing note 24 | * History Panel (v1.0.): https://github.com/alondmnt/joplin-plugin-history-panel 25 | 26 | Under development: 27 | 28 | * Note Link System (v0.8.0): https://github.com/ylc395/joplin-plugin-note-link-system 29 | * Writing Marker [Planned]: Help to mark text with a label and show them in the sidebar ordered by marker categories: 30 | * Recheck: text needs to be rechecked 31 | * Rewrite: text needs to be rewritten 32 | * ... (It depends on what I need to finish my papers) 33 | * Aggregated Search [Planned]: Allow search multiple resources and present the results in one panel. 34 | > I treat Joplin as my top-level knowledge base while there exist many other tools behind Joplin. Joplin is not a good choice for document management, so I need to search other tools. 35 | * Joplin Notes 36 | * ReadCube Papers: https://www.papersapp.com/ 37 | * ArchiveBox: https://github.com/ArchiveBox/ArchiveBox 38 | * ... ? 39 | 40 | ![Imgur](https://i.imgur.com/yfcsNDb.gif) 41 | 42 | ![Imgur](https://i.imgur.com/h7fP8iq.gif) 43 | 44 | 45 | 46 | ## Building the plugin 47 | 48 | The plugin is built using Webpack, which creates the compiled code in `/dist`. A JPL archive will also be created at the root, which can use to distribute the plugin. 49 | 50 | To build the plugin, simply run `npm run dist`. 51 | 52 | The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript. 53 | 54 | ## Updating the plugin framework 55 | 56 | To update the plugin framework, run `npm run update`. 57 | 58 | In general this command tries to do the right thing - in particular it's going to merge the changes in package.json and .gitignore instead of overwriting. It will also leave "/src" as well as README.md untouched. 59 | 60 | The file that may cause problem is "webpack.config.js" because it's going to be overwritten. For that reason, if you want to change it, consider creating a separate JavaScript file and include it in webpack.config.js. That way, when you update, you only have to restore the line that include your file. 61 | -------------------------------------------------------------------------------- /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 | * The API is now relatively stable and in general maintaining backward compatibility is a top priority, so you shouldn't except much breakages. 17 | * 18 | * If a breaking change ever becomes needed, best effort will be done to: 19 | * 20 | * - Deprecate features instead of removing them, so as to give you time to fix the issue; 21 | * - Document breaking changes in the changelog; 22 | * 23 | * 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. 24 | */ 25 | export default class Joplin { 26 | private data_; 27 | private plugins_; 28 | private workspace_; 29 | private filters_; 30 | private commands_; 31 | private views_; 32 | private interop_; 33 | private settings_; 34 | private contentScripts_; 35 | private clipboard_; 36 | private window_; 37 | constructor(implementation: any, plugin: Plugin, store: any); 38 | get data(): JoplinData; 39 | get clipboard(): JoplinClipboard; 40 | get window(): JoplinWindow; 41 | get plugins(): JoplinPlugins; 42 | get workspace(): JoplinWorkspace; 43 | get contentScripts(): JoplinContentScripts; 44 | /** 45 | * @ignore 46 | * 47 | * Not sure if it's the best way to hook into the app 48 | * so for now disable filters. 49 | */ 50 | get filters(): JoplinFilters; 51 | get commands(): JoplinCommands; 52 | get views(): JoplinViews; 53 | get interop(): JoplinInterop; 54 | get settings(): JoplinSettings; 55 | /** 56 | * It is not possible to bundle native packages with a plugin, because they 57 | * need to work cross-platforms. Instead access to certain useful native 58 | * packages is provided using this function. 59 | * 60 | * Currently these packages are available: 61 | * 62 | * - [sqlite3](https://www.npmjs.com/package/sqlite3) 63 | * - [fs-extra](https://www.npmjs.com/package/fs-extra) 64 | * 65 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/nativeModule) 66 | */ 67 | require(_path: string): any; 68 | } 69 | -------------------------------------------------------------------------------- /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/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 { ModelType } from '../../../BaseModel'; 2 | import { Path } from './types'; 3 | /** 4 | * This module provides access to the Joplin data API: https://joplinapp.org/api/references/rest_api/ 5 | * This is the main way to retrieve data, such as notes, notebooks, tags, etc. 6 | * or to update them or delete them. 7 | * 8 | * This is also what you would use to search notes, via the `search` endpoint. 9 | * 10 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/simple) 11 | * 12 | * 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. 13 | * And each method takes these parameters: 14 | * 15 | * * `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. 16 | * * `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. 17 | * * `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. 18 | * * `files`: (Optional) Used to create new resources and associate them with files. 19 | * 20 | * 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. 21 | * 22 | * For example: 23 | * 24 | * ```typescript 25 | * // Get a note ID, title and body 26 | * const noteId = 'some_note_id'; 27 | * const note = await joplin.data.get(['notes', noteId], { fields: ['id', 'title', 'body'] }); 28 | * 29 | * // Get all folders 30 | * const folders = await joplin.data.get(['folders']); 31 | * 32 | * // Set the note body 33 | * await joplin.data.put(['notes', noteId], null, { body: "New note body" }); 34 | * 35 | * // Create a new note under one of the folders 36 | * await joplin.data.post(['notes'], null, { body: "my new note", title: "some title", parent_id: folders[0].id }); 37 | * ``` 38 | */ 39 | export default class JoplinData { 40 | private api_; 41 | private pathSegmentRegex_; 42 | private serializeApiBody; 43 | private pathToString; 44 | get(path: Path, query?: any): Promise; 45 | post(path: Path, query?: any, body?: any, files?: any[]): Promise; 46 | put(path: Path, query?: any, body?: any, files?: any[]): Promise; 47 | delete(path: Path, query?: any): Promise; 48 | itemType(itemId: string): Promise; 49 | resourcePath(resourceId: string): Promise; 50 | } 51 | -------------------------------------------------------------------------------- /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 is set to 90vw and 80vh 65 | * @default true 66 | */ 67 | setFitToContent(handle: ViewHandle, status: boolean): Promise; 68 | } 69 | -------------------------------------------------------------------------------- /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 | * Sends a message to the webview. 51 | * 52 | * The webview must have registered a message handler prior, otherwise the message is ignored. Use; 53 | * 54 | * ```javascript 55 | * webviewApi.onMessage((message) => { ... }); 56 | * ``` 57 | * 58 | * - `message` can be any JavaScript object, string or number 59 | * 60 | * The view API may have only one onMessage handler defined. 61 | * This method is fire and forget so no response is returned. 62 | * 63 | * It is particularly useful when the webview needs to react to events emitted by the plugin or the joplin api. 64 | */ 65 | postMessage(handle: ViewHandle, message: any): void; 66 | /** 67 | * Shows the panel 68 | */ 69 | show(handle: ViewHandle, show?: boolean): Promise; 70 | /** 71 | * Hides the panel 72 | */ 73 | hide(handle: ViewHandle): Promise; 74 | /** 75 | * Tells whether the panel is visible or not 76 | */ 77 | visible(handle: ViewHandle): Promise; 78 | } 79 | -------------------------------------------------------------------------------- /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, MenuItem } from './types'; 3 | export interface EditContextMenuFilterObject { 4 | items: MenuItem[]; 5 | } 6 | declare type FilterHandler = (object: T) => Promise; 7 | declare enum ItemChangeEventType { 8 | Create = 1, 9 | Update = 2, 10 | Delete = 3 11 | } 12 | interface ItemChangeEvent { 13 | id: string; 14 | event: ItemChangeEventType; 15 | } 16 | interface SyncStartEvent { 17 | withErrors: boolean; 18 | } 19 | interface ResourceChangeEvent { 20 | id: string; 21 | } 22 | declare type ItemChangeHandler = (event: ItemChangeEvent) => void; 23 | declare type SyncStartHandler = (event: SyncStartEvent) => void; 24 | declare type ResourceChangeHandler = (event: ResourceChangeEvent) => void; 25 | /** 26 | * The workspace service provides access to all the parts of Joplin that 27 | * are being worked on - i.e. the currently selected notes or notebooks as 28 | * well as various related events, such as when a new note is selected, or 29 | * when the note content changes. 30 | * 31 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins) 32 | */ 33 | export default class JoplinWorkspace { 34 | private store; 35 | constructor(store: any); 36 | /** 37 | * Called when a new note or notes are selected. 38 | */ 39 | onNoteSelectionChange(callback: Function): Promise; 40 | /** 41 | * Called when the content of a note changes. 42 | * @deprecated Use `onNoteChange()` instead, which is reliably triggered whenever the note content, or any note property changes. 43 | */ 44 | onNoteContentChange(callback: Function): Promise; 45 | /** 46 | * Called when the content of the current note changes. 47 | */ 48 | onNoteChange(handler: ItemChangeHandler): Promise; 49 | /** 50 | * Called when a resource is changed. Currently this handled will not be 51 | * called when a resource is added or deleted. 52 | */ 53 | onResourceChange(handler: ResourceChangeHandler): Promise; 54 | /** 55 | * Called when an alarm associated with a to-do is triggered. 56 | */ 57 | onNoteAlarmTrigger(handler: Function): Promise; 58 | /** 59 | * Called when the synchronisation process is starting. 60 | */ 61 | onSyncStart(handler: SyncStartHandler): Promise; 62 | /** 63 | * Called when the synchronisation process has finished. 64 | */ 65 | onSyncComplete(callback: Function): Promise; 66 | /** 67 | * Called just before the editor context menu is about to open. Allows 68 | * adding items to it. 69 | */ 70 | filterEditorContextMenu(handler: FilterHandler): void; 71 | /** 72 | * Gets the currently selected note 73 | */ 74 | selectedNote(): Promise; 75 | /** 76 | * Gets the currently selected folder. In some cases, for example during 77 | * search or when viewing a tag, no folder is actually selected in the user 78 | * interface. In that case, that function would return the last selected 79 | * folder. 80 | */ 81 | selectedFolder(): Promise; 82 | /** 83 | * Gets the IDs of the selected notes (can be zero, one, or many). Use the data API to retrieve information about these notes. 84 | */ 85 | selectedNoteIds(): Promise; 86 | } 87 | export {}; 88 | -------------------------------------------------------------------------------- /api/index.ts: -------------------------------------------------------------------------------- 1 | import type Joplin from './Joplin'; 2 | 3 | declare const joplin: Joplin; 4 | 5 | export default joplin; 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joplin-plugin-bundle", 3 | "version": "0.5.5", 4 | "scripts": { 5 | "dist": "webpack --joplin-plugin-config buildMain && webpack --joplin-plugin-config buildExtraScripts && webpack --joplin-plugin-config createArchive", 6 | "prepare": "npm run dist", 7 | "update": "npm install -g generator-joplin && yo joplin --update" 8 | }, 9 | "license": "MIT", 10 | "keywords": [ 11 | "joplin-plugin" 12 | ], 13 | "files": [ 14 | "publish" 15 | ], 16 | "devDependencies": { 17 | "@types/codemirror": "^5.60.5", 18 | "@types/node": "^14.0.14", 19 | "chalk": "^4.1.0", 20 | "copy-webpack-plugin": "^6.1.0", 21 | "fs-extra": "^9.0.1", 22 | "glob": "^7.1.6", 23 | "on-build-webpack": "^0.1.0", 24 | "tar": "^6.0.5", 25 | "ts-loader": "^7.0.5", 26 | "ts-node": "^10.9.1", 27 | "typescript": "^3.9.3", 28 | "webpack": "^4.43.0", 29 | "webpack-cli": "^3.3.11", 30 | "yargs": "^16.2.0" 31 | }, 32 | "dependencies": { 33 | "@fortawesome/fontawesome-free": "^5.15.1", 34 | "chrono-node": "^2.4.1", 35 | "dateformat": "^5.0.3", 36 | "html-entities": "^2.3.3", 37 | "markdown-it": "^13.0.1", 38 | "markdown-it-mark": "^3.0.1", 39 | "moment": "^2.29.4", 40 | "net": "^1.0.2", 41 | "node-fetch": "^2.6.1", 42 | "react": "^18.2.0", 43 | "react-dom": "^18.2.0", 44 | "reconnecting-websocket": "^4.4.0", 45 | "string-to-color": "^2.2.2", 46 | "tls": "^0.0.1", 47 | "ts-debounce": "^4.0.0", 48 | "uslug": "git+https://github.com/laurent22/uslug.git#emoji-support", 49 | "words-count": "^2.0.2", 50 | "ws": "^8.6.0", 51 | "zotero-api-client": "^0.40.0" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /plugin.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "extraScripts": [ 3 | "./codemirror/commands/index.ts", 4 | "./codemirror/autoCompletion/index.ts", 5 | "./codemirror/noteRefCompletion/index.ts", 6 | "./codemirror/paperCiteCompletion/index.ts", 7 | "./aggregateSearch/test.tsx", 8 | "./writingMarker/htmlGenerator.tsx", 9 | "./dailyNote/htmlGenerator.tsx", 10 | "./readcube/driver/markdownItRenderer/paperFence/index.ts", 11 | "./readcube/driver/codemirror/autoCitation/index.ts", 12 | "./readcube/driver/codemirror/paperBlockRender/index.ts", 13 | "./inlineTodo/todoRender/index.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /screenshot/dailynote.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeptemberHX/joplin-plugin-bundle/b379ff4cb6066e7326eb6c39e99f219639395cff/screenshot/dailynote.png -------------------------------------------------------------------------------- /screenshot/history.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeptemberHX/joplin-plugin-bundle/b379ff4cb6066e7326eb6c39e99f219639395cff/screenshot/history.png -------------------------------------------------------------------------------- /screenshot/tab-panels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeptemberHX/joplin-plugin-bundle/b379ff4cb6066e7326eb6c39e99f219639395cff/screenshot/tab-panels.png -------------------------------------------------------------------------------- /src/aggregateSearch/index.ts: -------------------------------------------------------------------------------- 1 | import { SidebarPlugin } from "../sidebars/sidebarPage"; 2 | import {underDevelopment} from "./test"; 3 | 4 | class AggregateSearchPlugin extends SidebarPlugin { 5 | 6 | constructor() { 7 | super(); 8 | 9 | this.id = "aggregateSearchPlugin"; 10 | this.name = "Aggregate Search"; 11 | this.icon = "fas fa-search"; 12 | this.styles = [ 13 | ]; 14 | this.scripts = [ 15 | ]; 16 | } 17 | } 18 | 19 | const aggregateSearchPlugin = new AggregateSearchPlugin(); 20 | export default aggregateSearchPlugin; 21 | -------------------------------------------------------------------------------- /src/aggregateSearch/test.tsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import {renderToStaticMarkup} from 'react-dom/server' 3 | 4 | export function underDevelopment() { 5 | return renderToStaticMarkup( 6 |
7 |
Under development...
8 |
9 | ); 10 | } 11 | -------------------------------------------------------------------------------- /src/codemirror/autoCompletion/index.ts: -------------------------------------------------------------------------------- 1 | import QuickCommands from "./quickCommands"; 2 | 3 | module.exports = { 4 | default: function(_context) { 5 | return { 6 | plugin: function (CodeMirror) { 7 | CodeMirror.defineOption("cm_auto_completion", [], async function(cm, val, old) { 8 | new QuickCommands(_context, cm, CodeMirror); 9 | }); 10 | }, 11 | codeMirrorOptions: { 12 | 'cm_auto_completion': true 13 | }, 14 | assets: function() { 15 | return [ ]; 16 | } 17 | } 18 | }, 19 | } 20 | -------------------------------------------------------------------------------- /src/codemirror/commands/commands.ts: -------------------------------------------------------------------------------- 1 | export default class CommandsBridge { 2 | constructor(private readonly editor) { 3 | } 4 | 5 | private readonly doc = this.editor.getDoc(); 6 | 7 | scrollToLine(line: number): void { 8 | // temporary fix: sometimes the first coordinate is incorrect, 9 | // resulting in a difference about +- 10 px, 10 | // call the scroll function twice fixes the problem. 11 | this.editor.scrollTo(null, this.editor.charCoords({ line: line, ch: 0 }, 'local').top); 12 | this.editor.scrollTo(null, this.editor.charCoords({ line: line, ch: 0 }, 'local').top); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/codemirror/commands/index.ts: -------------------------------------------------------------------------------- 1 | import CommandsBridge from "./commands"; 2 | import {debounce} from "ts-debounce"; 3 | import wordsCount from 'words-count'; 4 | import {MsgType} from "../../common"; 5 | 6 | module.exports = { 7 | default: function(_context) { 8 | return { 9 | plugin: function (CodeMirror) { 10 | CodeMirror.defineOption("sidebar_cm_commands", [], async function(cm, val, old) { 11 | const commandBridge = new CommandsBridge(cm); 12 | CodeMirror.defineExtension('sidebar_cm_scrollToLine', commandBridge.scrollToLine.bind(commandBridge)); 13 | }); 14 | 15 | CodeMirror.defineOption("cursorChangeNotification", [], async function(cm, val, old) { 16 | const changeDebounce = debounce(async function() { 17 | let selectedWordCount = 0; 18 | let selectedCharCount = 0; 19 | for (const selected of cm.getDoc().getSelections()) { 20 | selectedWordCount += wordsCount(selected); 21 | selectedCharCount += selected.length; 22 | } 23 | 24 | return await _context.postMessage({ 25 | type: MsgType.CURSOR_CHANGE, 26 | totalLineCount: cm.getDoc().lineCount(), 27 | currentLineNumber: cm.getDoc().getCursor().line + 1, 28 | totalWordCount: wordsCount(cm.getDoc().getValue()), 29 | selectedWordCount: selectedWordCount, 30 | totalCharCount: cm.getDoc().getValue().length, 31 | selectedCharCount: selectedCharCount 32 | }); 33 | }, 100); 34 | cm.on('cursorActivity', changeDebounce); 35 | }); 36 | 37 | CodeMirror.defineExtension('scrollToLine', function scrollToLine(lineno) { 38 | // temporary fix: sometimes the first coordinate is incorrect, 39 | // resulting in a difference about +- 10 px, 40 | // call the scroll function twice fixes the problem. 41 | this.scrollTo(null, this.charCoords({ line: lineno, ch: 0 }, 'local').top); 42 | this.scrollTo(null, this.charCoords({ line: lineno, ch: 0 }, 'local').top); 43 | }); 44 | 45 | CodeMirror.defineOption("markdownHeaderChange", [], async function(cm, val, old) { 46 | const headerChangeDebounce = debounce(async function() { 47 | var rect = cm.getWrapperElement().getBoundingClientRect(); 48 | return await _context.postMessage({ 49 | type: MsgType.SCROLL_CHANGE, 50 | from: cm.lineAtHeight(rect.top, "window"), 51 | to: cm.lineAtHeight(rect.bottom, "window") 52 | }); 53 | }, 10); 54 | cm.on('scroll', headerChangeDebounce); 55 | cm.on('change', function (cm, changeObjs) { 56 | if (changeObjs.origin === 'setValue') { 57 | headerChangeDebounce(); 58 | } 59 | }); 60 | }); 61 | }, 62 | codeMirrorOptions: { 63 | 'sidebar_cm_commands': true, 64 | 'cursorChangeNotification': true, 65 | 'markdownHeaderChange': true 66 | }, 67 | assets: function() { 68 | return [ ]; 69 | } 70 | } 71 | }, 72 | } 73 | -------------------------------------------------------------------------------- /src/codemirror/noteRefCompletion/index.ts: -------------------------------------------------------------------------------- 1 | import NoteRefCompletion from "./noteRefCompletion"; 2 | 3 | module.exports = { 4 | default: function(_context) { 5 | return { 6 | plugin: function (CodeMirror) { 7 | CodeMirror.defineOption("cm_note_ref_completion", [], async function(cm, val, old) { 8 | new NoteRefCompletion(_context, cm, CodeMirror); 9 | }); 10 | }, 11 | codeMirrorOptions: { 12 | 'cm_note_ref_completion': true 13 | }, 14 | assets: function() { 15 | return [ ]; 16 | } 17 | } 18 | }, 19 | } 20 | -------------------------------------------------------------------------------- /src/codemirror/noteRefCompletion/noteRefCompletion.ts: -------------------------------------------------------------------------------- 1 | // implemented according to https://github.com/ylc395/joplin-plugin-note-link-system/blob/main/src/driver/codeMirror/QuickLinker.ts 2 | 3 | import {Editor, Position} from "codemirror"; 4 | import CodeMirror from "codemirror"; 5 | 6 | const TRIGGER_SYMBOL = '@ref'; 7 | const HINT_ITEM_CLASS = 'quick-commands-hint'; 8 | const HINT_ITEM_PATH_CLASS = 'quick-commands-hint-path'; 9 | 10 | // @see https://codemirror.net/doc/manual.html#addon_show-hint 11 | export interface Hint { 12 | text: string; 13 | displayText?: string; 14 | className?: string; 15 | description?: string; 16 | render?: (container: Element, completion: Completion, hint: Hint) => void; 17 | // hint?: (cm: typeof CodeMirror, completion: Completion, hint: Hint) => void; 18 | inline: boolean; 19 | } 20 | 21 | interface Completion { 22 | from: Position; 23 | to: Position; 24 | list: Hint[]; 25 | selectedHint?: number; 26 | } 27 | 28 | export type ExtendedEditor = { 29 | showHint(options: { 30 | completeSingle: boolean; 31 | closeCharacters: RegExp; 32 | closeOnUnfocus: boolean; 33 | hint: (cm: Editor) => Completion | undefined | Promise; 34 | }): void; 35 | }; 36 | 37 | export default class NoteRefCompletion { 38 | constructor(private readonly context, private readonly editor: ExtendedEditor & Editor, private readonly cm: typeof CodeMirror) { 39 | this.editor.on('cursorActivity', this.triggerHints.bind(this)); 40 | setTimeout(this.init.bind(this), 100); 41 | } 42 | 43 | private async init() { 44 | 45 | } 46 | 47 | private readonly doc = this.editor.getDoc(); 48 | private symbolRange?: { from: Position; to: Position }; 49 | 50 | private triggerHints() { 51 | const pos = this.doc.getCursor(); 52 | const symbolRange = [{ line: pos.line, ch: pos.ch - TRIGGER_SYMBOL.length }, pos] as const; 53 | const chars = this.doc.getRange(...symbolRange); 54 | 55 | if ((chars === TRIGGER_SYMBOL) 56 | && !/\S/.test(this.doc.getRange(pos, {line: pos.line, ch: pos.ch + 1}))) { 57 | this.symbolRange = { from: symbolRange[0], to: symbolRange[1] }; 58 | this.editor.showHint({ 59 | closeCharacters: /[()\[\]{};:>,/ ]/, 60 | closeOnUnfocus: true, 61 | completeSingle: false, 62 | hint: this.getCommandCompletion.bind(this, chars), 63 | }); 64 | } 65 | } 66 | 67 | private async getCommandCompletion(symbols: string) : Promise { 68 | if (!this.symbolRange) { 69 | throw new Error('no symbolRange'); 70 | } 71 | 72 | const { line, ch } = this.symbolRange.to; 73 | const { line: cursorLine, ch: cursorCh } = this.doc.getCursor(); 74 | 75 | if (cursorLine < line || cursorCh < ch) { 76 | return; 77 | } 78 | 79 | const keyword = this.doc.getRange({ line, ch }, { line: cursorLine, ch: cursorCh }); 80 | const { from: completionFrom } = this.symbolRange; 81 | const completionTo = { line, ch: ch + keyword.length }; 82 | const completion: Completion = { 83 | from: completionFrom, 84 | to: completionTo, 85 | list: await this.getCommandHints( 86 | symbols, 87 | keyword, 88 | this.doc.getRange({line: cursorLine, ch: 0}, {line: cursorLine, ch: cursorCh - 1}) // string before '/' 89 | ), 90 | }; 91 | return completion; 92 | } 93 | 94 | private async getCommandHints(symbols: string, keyword: string, indent: string) : Promise { 95 | let hints = []; 96 | 97 | let results = await this.context.postMessage({ 98 | type: 'cm_note_ref_completion' 99 | }); 100 | 101 | // add indent when there exists 'tab' before or add a new line for non-inline hints 102 | for (let noteItem of results) { 103 | // filter the hints by keyword 104 | if (noteItem.title.includes(keyword)) { 105 | hints.push({ 106 | text: `[${noteItem.title}](:/${noteItem.id})`, 107 | displayText: noteItem.title, 108 | className: HINT_ITEM_CLASS, 109 | render(container) { 110 | container.innerHTML = noteItem.title; 111 | }, 112 | updateTime: noteItem.updated_time 113 | }) 114 | } 115 | } 116 | 117 | return hints.sort((h1, h2) => { 118 | if (h1.updateTime > h2.updateTime) { 119 | return -1; 120 | } else if (h1.updateTime < h2.updateTime) { 121 | return 1; 122 | } else { 123 | return 0; 124 | } 125 | }); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/codemirror/paperCiteCompletion/index.ts: -------------------------------------------------------------------------------- 1 | import NoteRefCompletion from "./paperCiteCompletion"; 2 | 3 | module.exports = { 4 | default: function(_context) { 5 | return { 6 | plugin: function (CodeMirror) { 7 | CodeMirror.defineOption("cm_paper_cite_completion", [], async function(cm, val, old) { 8 | new NoteRefCompletion(_context, cm, CodeMirror); 9 | }); 10 | }, 11 | codeMirrorOptions: { 12 | 'cm_paper_cite_completion': true 13 | }, 14 | assets: function() { 15 | return [ ]; 16 | } 17 | } 18 | }, 19 | } 20 | -------------------------------------------------------------------------------- /src/codemirror/paperCiteCompletion/paperCiteCompletion.ts: -------------------------------------------------------------------------------- 1 | // implemented according to https://github.com/ylc395/joplin-plugin-note-link-system/blob/main/src/driver/codeMirror/QuickLinker.ts 2 | 3 | import {Editor, Position} from "codemirror"; 4 | import CodeMirror from "codemirror"; 5 | 6 | const TRIGGER_SYMBOL = '@cite'; 7 | const HINT_ITEM_CLASS = 'quick-commands-hint'; 8 | const HINT_ITEM_PATH_CLASS = 'quick-commands-hint-path'; 9 | 10 | // @see https://codemirror.net/doc/manual.html#addon_show-hint 11 | export interface Hint { 12 | text: string; 13 | displayText?: string; 14 | className?: string; 15 | description?: string; 16 | render?: (container: Element, completion: Completion, hint: Hint) => void; 17 | // hint?: (cm: typeof CodeMirror, completion: Completion, hint: Hint) => void; 18 | inline: boolean; 19 | } 20 | 21 | interface Completion { 22 | from: Position; 23 | to: Position; 24 | list: Hint[]; 25 | selectedHint?: number; 26 | } 27 | 28 | export type ExtendedEditor = { 29 | showHint(options: { 30 | completeSingle: boolean; 31 | closeCharacters: RegExp; 32 | closeOnUnfocus: boolean; 33 | hint: (cm: Editor) => Completion | undefined | Promise; 34 | }): void; 35 | }; 36 | 37 | export default class PaperCiteCompletion { 38 | constructor(private readonly context, private readonly editor: ExtendedEditor & Editor, private readonly cm: typeof CodeMirror) { 39 | this.editor.on('cursorActivity', this.triggerHints.bind(this)); 40 | setTimeout(this.init.bind(this), 100); 41 | } 42 | 43 | private async init() { 44 | 45 | } 46 | 47 | private readonly doc = this.editor.getDoc(); 48 | private symbolRange?: { from: Position; to: Position }; 49 | 50 | private triggerHints() { 51 | const pos = this.doc.getCursor(); 52 | const symbolRange = [{ line: pos.line, ch: pos.ch - TRIGGER_SYMBOL.length }, pos] as const; 53 | const chars = this.doc.getRange(...symbolRange); 54 | 55 | if ((chars === TRIGGER_SYMBOL) 56 | && !/\S/.test(this.doc.getRange(pos, {line: pos.line, ch: pos.ch + 1}))) { 57 | this.symbolRange = { from: symbolRange[0], to: symbolRange[1] }; 58 | this.editor.showHint({ 59 | closeCharacters: /[()\[\]{};:>,/ ]/, 60 | closeOnUnfocus: true, 61 | completeSingle: false, 62 | hint: this.getCommandCompletion.bind(this, chars), 63 | }); 64 | } 65 | } 66 | 67 | private async getCommandCompletion(symbols: string) : Promise { 68 | if (!this.symbolRange) { 69 | throw new Error('no symbolRange'); 70 | } 71 | 72 | const { line, ch } = this.symbolRange.to; 73 | const { line: cursorLine, ch: cursorCh } = this.doc.getCursor(); 74 | 75 | if (cursorLine < line || cursorCh < ch) { 76 | return; 77 | } 78 | 79 | const keyword = this.doc.getRange({ line, ch }, { line: cursorLine, ch: cursorCh }); 80 | const { from: completionFrom } = this.symbolRange; 81 | const completionTo = { line, ch: ch + keyword.length }; 82 | const completion: Completion = { 83 | from: completionFrom, 84 | to: completionTo, 85 | list: await this.getCommandHints( 86 | symbols, 87 | keyword, 88 | this.doc.getRange({line: cursorLine, ch: 0}, {line: cursorLine, ch: cursorCh - 1}) // string before '/' 89 | ), 90 | }; 91 | return completion; 92 | } 93 | 94 | private async getCommandHints(symbols: string, keyword: string, indent: string) : Promise { 95 | let hints = []; 96 | 97 | let results = await this.context.postMessage({ 98 | type: 'cm_paper_cite_completion' 99 | }); 100 | 101 | // add indent when there exists 'tab' before or add a new line for non-inline hints 102 | for (let paperItem of results) { 103 | // filter the hints by keyword 104 | if (paperItem.title.includes(keyword)) { 105 | hints.push({ 106 | text: `[${paperItem.title}](${paperItem.url})`, 107 | displayText: paperItem.title, 108 | className: HINT_ITEM_CLASS, 109 | render(container) { 110 | container.innerHTML = paperItem.title; 111 | } 112 | }) 113 | } 114 | } 115 | 116 | return hints.sort((h1, h2) => { 117 | if (h1.title > h2.title) { 118 | return 1; 119 | } else if (h1.title < h2.title) { 120 | return -1; 121 | } else { 122 | return 0; 123 | } 124 | }); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/common.ts: -------------------------------------------------------------------------------- 1 | export const ENABLE_OUTLINE = 'bundle_enable_outline'; 2 | export const OUTLINE_DEFAULT_OPEN_DIRS = 'bundle_outline_default_open_dirs'; 3 | export const ENABLE_TODO = 'bundle_enable_todo'; 4 | export const TODO_DEFAULT_OPEN_DIRS = 'bundle_todo_default_open_dirs'; 5 | export const ENABLE_DAILY_NOTE = 'bundle_enable_daily_note'; 6 | export const DAILY_NOTE_DEFAULT_OPEN_DIRS = 'bundle_daily_note_default_open_dirs'; 7 | export const ENABLE_WRITING_MARKER = 'bundle_enable_writing_marker'; 8 | export const WRITING_MARKER_DEFAULT_OPEN_DIRS = 'bundle_writing_marker_default_open_dirs'; 9 | export const ENABLE_HISTORY = 'bundle_enable_history'; 10 | export const HISTORY_DEFAULT_OPEN_DIRS = 'bundle_history_default_open_dirs'; 11 | export const ENABLE_READCUBE_PAPERS = 'bundle_enable_readcube_papers'; 12 | export const PAPERS_DEFAULT_OPEN_DIRS = 'bundle_papers_default_open_dirs'; 13 | export const ENABLE_RELATED_NOTES = 'bundle_enable_related_notes'; 14 | export const RELATED_NOTES_DEFAULT_OPEN_DIRS = 'bundle_related_notes_default_open_dirs'; 15 | export const LAST_NOTE_UPDATE_DATE = 'bundle_last_note_update_date'; 16 | export const ENABLE_CHAR_COUNT = 'bundle_status_enable_char_count'; 17 | export const ENABLE_GROUPS = 'bundle_enable_groups'; 18 | 19 | 20 | export const PAPERS_PLUGIN_ID = 'papers'; 21 | export const DAILY_NOTE_PLUGIN_ID = 'dailyNote'; 22 | export const HISTORY_PLUGIN_ID = 'history-panel'; 23 | export const TODO_PLUGIN_ID = 'inline-todo'; 24 | export const OUTLINE_PLUGIN_ID = 'outline'; 25 | export const RELATED_NOTE_PLUGIN_ID = 'relatedNotesPlugin'; 26 | export const WRITING_MARKER_PLUGIN_ID = 'writingMarker'; 27 | export const GROUPS_PLUGIN_ID = 'groups'; 28 | 29 | export enum MsgType { 30 | SCROLL_CHANGE, 31 | CURSOR_CHANGE, 32 | } 33 | 34 | 35 | export class SideBarConfig { 36 | outline: boolean; 37 | outlineDefaultOpenDirs: string[]; 38 | inlineTodo: boolean; 39 | inlineTodoDefaultOpenDirs: string[]; 40 | dailyNote: boolean; 41 | dailyNoteDefaultOpenDirs: string[]; 42 | writingMarker: boolean; 43 | writingMarkerDefaultOpenDirs: string[]; 44 | history: boolean; 45 | historyDefaultOpenDirs: string[]; 46 | readcube: boolean; 47 | papersDefaultDirs: string[]; 48 | relatedNotes: boolean; 49 | relatedNotesDefaultDirs: string[]; 50 | charCount: boolean; 51 | groups: boolean; 52 | } 53 | -------------------------------------------------------------------------------- /src/dailyNote/htmlGenerator.tsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import {renderToString} from 'react-dom/server' 3 | import {DailyNoteConfig} from "./settings"; 4 | 5 | 6 | export function cellInnerHtml(monthClass: string, hasNote: boolean, isToday: boolean, date, finishedTaskCount?: number, config?: DailyNoteConfig, wordCount?: number) { 7 | return renderToString(generateCell(monthClass, hasNote, isToday, date, finishedTaskCount, config, wordCount)); 8 | } 9 | 10 | 11 | function generateCell(monthClass: string, hasNote: boolean, isToday: boolean, date, finishedTaskCount?: number, config?: DailyNoteConfig, wordCount?: number) { 12 | let wordCountLevel = wordCount ? Math.ceil(wordCount / (config && config.wordStep > 0 ? config.wordStep : 100)) : 0; 13 | if (wordCountLevel >= 20) { 14 | wordCountLevel = 20; 15 | } 16 | 17 | function generateWordCountPoint(level) { 18 | const result = []; 19 | for (let i = 1; i * 5 <= level; ++i) { 20 | result.push( 21 | 22 | ); 23 | } 24 | 25 | for (let i = 1; i <= level % 5; ++i) { 26 | result.push( 27 | 28 | ); 29 | } 30 | return result; 31 | } 32 | 33 | return
34 |
35 | {date.date()} 36 |
37 |
38 | {generateWordCountPoint(wordCountLevel)} 39 |
40 |
41 | } 42 | 43 | function generateClass(hasNote, isToday, finishedTaskCount) { 44 | return `day ${hasNote ? 'hasNote' : 'noNote'} ${isToday ? 'curr-day' : ''} ${finishedTaskCount && finishedTaskCount >= 10 ? 'level-10' : 'level-' + finishedTaskCount}`; 45 | } 46 | 47 | function generateStyle(finishedTaskCount, config: DailyNoteConfig) { 48 | const style = {}; 49 | if (finishedTaskCount && config.enableHeatmap) { 50 | style['background-color'] = `rgba(${config.heatmapColor}, 0.${Math.ceil(finishedTaskCount / (config.step > 0 ? config.step : 1))})`; 51 | } 52 | return style; 53 | } 54 | -------------------------------------------------------------------------------- /src/dailyNote/index.ts: -------------------------------------------------------------------------------- 1 | import {SidebarPlugin, Sidebars} from "../sidebars/sidebarPage"; 2 | import {createCalendar} from "./panelHtml"; 3 | import {createDailyNoteByDate, getDailyNoteByDate} from "./utils"; 4 | import joplin from "../../api"; 5 | import {debounce} from "ts-debounce"; 6 | import * as moment from "moment"; 7 | import {DailyNoteConfig, getConfig, settings} from "./settings"; 8 | import {DAILY_NOTE_PLUGIN_ID} from "../common"; 9 | 10 | class DailyNotePlugin extends SidebarPlugin { 11 | 12 | sidebar: Sidebars; 13 | createDialog; 14 | year: number; 15 | month: number; 16 | config: DailyNoteConfig; 17 | 18 | constructor() { 19 | super(); 20 | 21 | this.id = DAILY_NOTE_PLUGIN_ID; 22 | this.name = "Daily Note"; 23 | this.icon = "fas fa-calendar-alt"; 24 | this.styles = [ 25 | './scripts/dailyNote/dailyNote.css', 26 | ]; 27 | this.scripts = [ 28 | './scripts/dailyNote/dailyNote.js', 29 | ]; 30 | this.year = moment().year(); 31 | this.month = moment().month(); 32 | } 33 | 34 | public async init(sidebar: Sidebars) { 35 | await settings.register(); 36 | this.config = await getConfig(); 37 | 38 | this.sidebar = sidebar; 39 | await this.sidebar.updateHtml(this.id, await createCalendar(this.year, this.month, this.config)); 40 | 41 | this.createDialog = await joplin.views.dialogs.create('DailyNoteCreateDialog'); 42 | const updateDebounce = debounce(async () => await this.sidebar.updateHtml(this.id, await createCalendar(this.year, this.month, this.config)), 100); 43 | await joplin.workspace.onSyncComplete(async () => await updateDebounce()); 44 | await joplin.workspace.onNoteSelectionChange(async () => await updateDebounce()); 45 | await joplin.workspace.onNoteChange(async () => updateDebounce()); 46 | await joplin.settings.onChange(async () => { 47 | this.config = await getConfig(); 48 | await updateDebounce(); 49 | }); 50 | } 51 | 52 | async panelMsgProcess(msg: any): Promise { 53 | switch (msg.name) { 54 | case 'sidebar_dailynote_day_clicked': 55 | const splits = msg.id.split('-'); 56 | if (splits.length === 3) { 57 | const noteDate = msg.id; 58 | 59 | const noteId = await getDailyNoteByDate(noteDate); 60 | if (!noteId) { 61 | await joplin.views.dialogs.setHtml(this.createDialog, `

Note for ${noteDate} do not exist.

Would you like to create one?

`); 62 | await joplin.views.dialogs.addScript(this.createDialog, './scripts/dailyNote/dialog.css'); 63 | const dialogResult = await joplin.views.dialogs.open(this.createDialog); 64 | if (dialogResult.id === 'ok') { 65 | const createNoteId = await createDailyNoteByDate(noteDate, this.config.todoNote); 66 | await joplin.commands.execute('openItem', `:/${createNoteId}`); 67 | } 68 | } else { 69 | await joplin.commands.execute('openItem', `:/${noteId}`); 70 | } 71 | return true; 72 | } 73 | break; 74 | case 'sidebar_dailynote_show_calendar_for': 75 | await this.sidebar.updateHtml(this.id, await createCalendar(msg.id.year, msg.id.month, this.config)); 76 | this.year = msg.id.year; 77 | this.month = msg.id.month; 78 | return true; 79 | default: 80 | break; 81 | } 82 | return false; 83 | } 84 | } 85 | 86 | const dailyNotePlugin = new DailyNotePlugin(); 87 | export default dailyNotePlugin; 88 | -------------------------------------------------------------------------------- /src/dailyNote/panelHtml.ts: -------------------------------------------------------------------------------- 1 | import * as moment from "moment"; 2 | import {getDailyNoteIdsByMonth} from "./utils"; 3 | import {DailyNoteConfig} from "./settings"; 4 | import {cellInnerHtml} from "./htmlGenerator"; 5 | 6 | function createCell(monthClass: string, hasNote: boolean, isToday: boolean, date, finishedTaskCount?: number, config?: DailyNoteConfig, wordCount?: number) { 7 | return ` 8 | ${cellInnerHtml(monthClass, hasNote, isToday, date, finishedTaskCount, config, wordCount)} 9 | `; 10 | } 11 | 12 | function createCalendarTable(year, month, noteDaysInfo, config: DailyNoteConfig) { 13 | const currMonth = moment({year: year, month: month}); 14 | const lastMonth = moment({year: year, month: month}).add(-1, 'day'); 15 | const nextMonth = moment({year: year, month: month}).add(1, 'month'); 16 | let offset = config.mondayAsFirst ? 1 : 0; 17 | 18 | let table = ` 19 |
20 | 21 | 22 | 23 |
24 | 25 | 26 | `; 27 | if (offset === 0) { 28 | table += ` 29 | 30 | 31 | 32 | 33 | 34 | 35 | `; 36 | } else { 37 | table += ` 38 | 39 | 40 | 41 | 42 | 43 | 44 | `; 45 | } 46 | table += `` 47 | 48 | while (lastMonth.weekday() >= 1 + offset && lastMonth.weekday() <= 5 + offset) { 49 | lastMonth.add(-1, 'day'); 50 | } 51 | if (lastMonth.weekday() === 0 + offset) { 52 | table += ` 53 | `; 54 | while (lastMonth < currMonth) { 55 | table += createCell('prev-month', false, false, lastMonth); 56 | lastMonth.add(1, 'day'); 57 | } 58 | while (currMonth.weekday() !== 0 + offset) { 59 | const hasNote = currMonth.format('DD') in noteDaysInfo; 60 | const noteInfo = noteDaysInfo[currMonth.format('DD')]; 61 | table += createCell('curr-month', hasNote, 62 | currMonth.date() === moment().date() && currMonth.year() === moment().year() && currMonth.month() === moment().month(), 63 | currMonth, hasNote ? noteInfo.finishedTaskCount : null, config, noteInfo ? noteInfo.wordCount : null); 64 | currMonth.add(1, 'day'); 65 | } 66 | table += ` 67 | `; 68 | } 69 | 70 | while (currMonth < nextMonth) { 71 | table += ` 72 | `; 73 | for (let i = 0; i < 7; i++) { 74 | if (currMonth < nextMonth) { 75 | const hasNote = currMonth.format('DD') in noteDaysInfo; 76 | const noteInfo = noteDaysInfo[currMonth.format('DD')]; 77 | table += createCell('curr-month', hasNote, 78 | currMonth.date() === moment().date() && currMonth.year() === moment().year() && currMonth.month() === moment().month(), 79 | currMonth, hasNote ? noteInfo.finishedTaskCount : null, config, noteInfo ? noteInfo.wordCount : null); 80 | } else { 81 | table += createCell('next-month', false, 82 | currMonth.date() === moment().date() && currMonth.year() === moment().year() && currMonth.month() === moment().month(), 83 | currMonth); 84 | } 85 | currMonth.add(1, 'day'); 86 | } 87 | table += ` 88 | `; 89 | } 90 | table += ''; 91 | table += '
SuMoTuWeThFrSaMoTuWeThFrSaSu
'; 92 | return table; 93 | } 94 | 95 | export async function createCalendar(year, month, config: DailyNoteConfig) { 96 | const yearStr = `${year}`; 97 | let monthStr = `${month + 1}`; 98 | if (monthStr.length === 1) { 99 | monthStr = `0${monthStr}`; 100 | } 101 | const t = await getDailyNoteIdsByMonth(yearStr, monthStr); 102 | return createCalendarTable(year, month, t, config); 103 | } 104 | -------------------------------------------------------------------------------- /src/dailyNote/settings.ts: -------------------------------------------------------------------------------- 1 | import joplin from "../../api"; 2 | import {SettingItemType} from "../../api/types"; 3 | 4 | export const DAILY_NOTE_TEMPLATE = 'bundle_daily_note_template'; 5 | export const DAILY_NOTE_ROOT_DIR_NAME = 'bundle_daily_note_root_dir_name'; 6 | export const DAILY_NOTE_ENABLE_HEATMAP = 'bundle_daily_note_enable_heatmap'; 7 | export const DAILY_NOTE_HEATMAP_LEVEL_STEP = 'bundle_daily_note_heatmap_level_step'; 8 | export const DAILY_NOTE_HEATMAP_COLOR = 'bundle_daily_note_heatmap_color'; 9 | export const DAILY_NOTE_WORD_COUNT_STEP = 'bundle_daily_note_word_count_step'; 10 | export const DAILY_NOTE_USE_TODO_NOTE = 'bundle_daily_note_use_todo_note'; 11 | export const DAILY_NOTE_MONDAY_FIRST_WEEKDAY = 'bundle_daily_note_monday_first_weekday'; 12 | 13 | 14 | export class DailyNoteConfig { 15 | rootDirName: string; 16 | noteTemplate: string; 17 | enableHeatmap: boolean; 18 | heatmapColor: string; 19 | step: number; 20 | wordStep: number; 21 | todoNote: boolean; 22 | mondayAsFirst: boolean; 23 | } 24 | 25 | 26 | export async function getConfig() { 27 | const config = new DailyNoteConfig(); 28 | config.rootDirName = await joplin.settings.value(DAILY_NOTE_ROOT_DIR_NAME); 29 | config.noteTemplate = await joplin.settings.value(DAILY_NOTE_TEMPLATE); 30 | config.enableHeatmap = await joplin.settings.value(DAILY_NOTE_ENABLE_HEATMAP); 31 | config.heatmapColor = await joplin.settings.value(DAILY_NOTE_HEATMAP_COLOR); 32 | config.step = await joplin.settings.value(DAILY_NOTE_HEATMAP_LEVEL_STEP); 33 | config.wordStep = await joplin.settings.value(DAILY_NOTE_WORD_COUNT_STEP); 34 | config.todoNote = await joplin.settings.value(DAILY_NOTE_USE_TODO_NOTE); 35 | config.mondayAsFirst = await joplin.settings.value(DAILY_NOTE_MONDAY_FIRST_WEEKDAY); 36 | return config; 37 | } 38 | 39 | 40 | export namespace settings { 41 | const SECTION = 'DailyNoteSettings'; 42 | 43 | export async function register() { 44 | await joplin.settings.registerSection(SECTION, { 45 | label: "Bundle Daily Note", 46 | iconName: "fas fa-calendar-alt", 47 | }); 48 | 49 | let PLUGIN_SETTINGS = {}; 50 | 51 | PLUGIN_SETTINGS[DAILY_NOTE_ROOT_DIR_NAME] = { 52 | value: 'Daily Note', 53 | public: true, 54 | section: SECTION, 55 | type: SettingItemType.String, 56 | label: 'Daily Note Root Directory Name/ID', 57 | description: "Where to save all your daily notes. Set it to the directory ID if you want to use a specific directory as the root. Right click on the folder -> Copy external link -> Paste it in any editor and you will find the folder id (32 characters). If an invalid id is provided, 'Daily Note' will be used instead.", 58 | }; 59 | 60 | PLUGIN_SETTINGS[DAILY_NOTE_TEMPLATE] = { 61 | value: '', 62 | public: true, 63 | section: SECTION, 64 | type: SettingItemType.String, 65 | label: 'Daily Note Template', 66 | description: "Template when you create a new daily note. Use '\\n' for new line", 67 | }; 68 | 69 | PLUGIN_SETTINGS[DAILY_NOTE_MONDAY_FIRST_WEEKDAY] = { 70 | value: false, 71 | public: true, 72 | section: SECTION, 73 | type: SettingItemType.Bool, 74 | label: 'Use Monday as the first day of each week instead of Sunday' 75 | }; 76 | 77 | PLUGIN_SETTINGS[DAILY_NOTE_USE_TODO_NOTE] = { 78 | value: false, 79 | public: true, 80 | section: SECTION, 81 | type: SettingItemType.Bool, 82 | label: 'Create new notes in todo note type' 83 | }; 84 | 85 | PLUGIN_SETTINGS[DAILY_NOTE_WORD_COUNT_STEP] = { 86 | value: 100, 87 | public: true, 88 | section: SECTION, 89 | type: SettingItemType.Int, 90 | label: 'Daily Note Word Count Level Step', 91 | description: "There are 20 levels of word count, level = ceil(word count / level step). One green point = 1 level, one red point = 5 level", 92 | }; 93 | 94 | PLUGIN_SETTINGS[DAILY_NOTE_ENABLE_HEATMAP] = { 95 | value: true, 96 | public: true, 97 | section: SECTION, 98 | type: SettingItemType.Bool, 99 | label: 'Daily Note HeatMap', 100 | description: "Show heatmap for daily notes by counting the finished tasks in each daily note", 101 | }; 102 | 103 | PLUGIN_SETTINGS[DAILY_NOTE_HEATMAP_LEVEL_STEP] = { 104 | value: 1, 105 | public: true, 106 | section: SECTION, 107 | type: SettingItemType.Int, 108 | label: 'Daily Note HeatMap Level Step', 109 | description: "There are 10 levels of heatmap, level = ceil(# of finished tasks / level step)", 110 | }; 111 | 112 | PLUGIN_SETTINGS[DAILY_NOTE_HEATMAP_COLOR] = { 113 | value: '242, 75, 125', 114 | public: true, 115 | section: SECTION, 116 | type: SettingItemType.String, 117 | label: 'Daily Note HeatMap Color', 118 | description: "RGB color value for the heatmap", 119 | }; 120 | 121 | await joplin.settings.registerSettings(PLUGIN_SETTINGS); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/groups/index.ts: -------------------------------------------------------------------------------- 1 | import {SidebarPlugin, Sidebars} from "../sidebars/sidebarPage"; 2 | import {GROUPS_PLUGIN_ID} from "../common"; 3 | 4 | class GroupsPlugin extends SidebarPlugin { 5 | sidebar: Sidebars; 6 | 7 | constructor() { 8 | super(); 9 | 10 | this.id = GROUPS_PLUGIN_ID; 11 | this.name = "Groups"; 12 | this.icon = "fas fa-th-large"; 13 | this.styles = [ 14 | ]; 15 | this.scripts = [ 16 | ]; 17 | } 18 | } 19 | 20 | const groupsPlugin = new GroupsPlugin(); 21 | export default groupsPlugin; 22 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import {SidebarPlugin, Sidebars} from "./sidebars/sidebarPage"; 3 | import outlinePlugin from "./outline"; 4 | import todolistPlugin from "./inlineTodo"; 5 | import dailyNotePlugin from "./dailyNote"; 6 | import writingMarkerPlugin from "./writingMarker"; 7 | import historyPlugin from "./history"; 8 | import {ContentScriptType} from "../api/types"; 9 | import { 10 | ENABLE_CHAR_COUNT, 11 | ENABLE_DAILY_NOTE, 12 | ENABLE_HISTORY, 13 | ENABLE_OUTLINE, 14 | ENABLE_READCUBE_PAPERS, 15 | ENABLE_RELATED_NOTES, 16 | ENABLE_TODO, 17 | ENABLE_WRITING_MARKER, 18 | PAPERS_DEFAULT_OPEN_DIRS, 19 | SideBarConfig, 20 | RELATED_NOTES_DEFAULT_OPEN_DIRS, 21 | HISTORY_DEFAULT_OPEN_DIRS, 22 | WRITING_MARKER_DEFAULT_OPEN_DIRS, 23 | DAILY_NOTE_DEFAULT_OPEN_DIRS, TODO_DEFAULT_OPEN_DIRS, OUTLINE_DEFAULT_OPEN_DIRS, ENABLE_GROUPS 24 | } from "./common"; 25 | import {settings} from "./settings"; 26 | import readCubePlugin from "./readcube"; 27 | import relatedNotesPlugin from "./relatedNotes"; 28 | import noteUpdateNotify from "./utils/noteUpdateNotify"; 29 | import groupsPlugin from "./groups"; 30 | 31 | joplin.plugins.register({ 32 | onStart: async function() { 33 | await settings.register(); 34 | 35 | await noteUpdateNotify.init(); 36 | 37 | await joplin.contentScripts.register( 38 | ContentScriptType.CodeMirrorPlugin, 39 | 'sidebar_cm_commands', 40 | './codemirror/commands/index.js' 41 | ); 42 | 43 | const sidebar = new Sidebars(); 44 | 45 | let plugins: SidebarPlugin[] = []; 46 | 47 | const pluginConfig = await getConfig(); 48 | if (pluginConfig.outline) { 49 | plugins.push(outlinePlugin); 50 | } 51 | 52 | if (pluginConfig.inlineTodo) { 53 | plugins.push(todolistPlugin); 54 | } 55 | 56 | if (pluginConfig.dailyNote) { 57 | plugins.push(dailyNotePlugin); 58 | } 59 | 60 | if (pluginConfig.writingMarker) { 61 | plugins.push(writingMarkerPlugin); 62 | } 63 | 64 | if (pluginConfig.history) { 65 | plugins.push(historyPlugin); 66 | } 67 | 68 | if (pluginConfig.readcube) { 69 | plugins.push(readCubePlugin); 70 | } 71 | 72 | if (pluginConfig.relatedNotes) { 73 | plugins.push(relatedNotesPlugin); 74 | } 75 | 76 | if (pluginConfig.groups) { 77 | plugins.push(groupsPlugin); 78 | } 79 | 80 | await sidebar.init(plugins); 81 | }, 82 | }); 83 | 84 | export async function getConfig(): Promise { 85 | const config = new SideBarConfig(); 86 | config.outline = await joplin.settings.value(ENABLE_OUTLINE); 87 | config.outlineDefaultOpenDirs = await getFolderSetting(OUTLINE_DEFAULT_OPEN_DIRS); 88 | 89 | config.inlineTodo = await joplin.settings.value(ENABLE_TODO); 90 | config.inlineTodoDefaultOpenDirs = await getFolderSetting(TODO_DEFAULT_OPEN_DIRS); 91 | 92 | config.dailyNote = await joplin.settings.value(ENABLE_DAILY_NOTE); 93 | config.dailyNoteDefaultOpenDirs = await getFolderSetting(DAILY_NOTE_DEFAULT_OPEN_DIRS); 94 | 95 | config.writingMarker = await joplin.settings.value(ENABLE_WRITING_MARKER); 96 | config.writingMarkerDefaultOpenDirs = await getFolderSetting(WRITING_MARKER_DEFAULT_OPEN_DIRS); 97 | 98 | config.history = await joplin.settings.value(ENABLE_HISTORY); 99 | config.historyDefaultOpenDirs = await getFolderSetting(HISTORY_DEFAULT_OPEN_DIRS); 100 | 101 | config.readcube = await joplin.settings.value(ENABLE_READCUBE_PAPERS); 102 | config.papersDefaultDirs = await getFolderSetting(PAPERS_DEFAULT_OPEN_DIRS); 103 | 104 | config.relatedNotes = await joplin.settings.value(ENABLE_RELATED_NOTES); 105 | config.relatedNotesDefaultDirs = await getFolderSetting(RELATED_NOTES_DEFAULT_OPEN_DIRS) 106 | 107 | config.groups = await joplin.settings.value(ENABLE_GROUPS); 108 | 109 | config.charCount = await joplin.settings.value(ENABLE_CHAR_COUNT); 110 | return config; 111 | } 112 | 113 | async function getFolderSetting(configName: string) { 114 | const folderNames = await joplin.settings.value(configName); 115 | const results = []; 116 | for (const noteFolder of folderNames.split('|')) { 117 | if (noteFolder.length > 0) { 118 | results.push(noteFolder); 119 | } 120 | } 121 | return results; 122 | } 123 | -------------------------------------------------------------------------------- /src/inlineTodo/builder.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import { Note, Settings, Todo, Summary } from './types'; 3 | import * as chrono from 'chrono-node'; 4 | 5 | const dateStrReg = /^\d{4}-\d{2}-\d{2}$/; 6 | 7 | export class SummaryBuilder { 8 | _summary: Summary = {}; 9 | // Maps folder ids to folder name 10 | // Record 11 | _folders: Record = {}; 12 | // Don't overwrite the summary note unless all notes have been checked 13 | _initialized: boolean = false; 14 | // The plugin settings 15 | _settings: Settings; 16 | 17 | constructor (s: Settings) { 18 | this._settings = s; 19 | } 20 | 21 | async search_in_note(note: Note): Promise { 22 | // Conflict notes are duplicates usually 23 | if (note.is_conflict) { return; } 24 | let matches = []; 25 | // This introduces a small risk of a race condition 26 | // (If this is waiting, the note.body could become stale, but this function would 27 | // continue anyways and update the summary with stale data) 28 | // I don't think this will be an issue in practice, and if it does crop up 29 | // there won't be any data loss 30 | let folder = await this.get_parent_title(note.parent_id); 31 | let match; 32 | let index = 0; 33 | let lineNumber = 0; 34 | const todo_type = this._settings.todo_type; 35 | todo_type.regex.lastIndex = 0; 36 | for (const line of note.body.split('\n')) { 37 | while ((match = todo_type.regex.exec(line)) !== null) { 38 | // For todoitems in daily notes, we consider the note date as the default task date 39 | let matchedDate = todo_type.date(match); 40 | if (this.settings.note_title_date && matchedDate.length === 0 && dateStrReg.test(note.title)) { 41 | matchedDate = note.title; 42 | } 43 | 44 | const dateStrSplit = matchedDate.split('~'); 45 | let fromDate, toDate; 46 | fromDate = chrono.parseDate(dateStrSplit[0]); 47 | if (dateStrSplit.length >= 2) { 48 | toDate = chrono.parseDate(dateStrSplit[1]); 49 | if (toDate < fromDate) { 50 | toDate = null; 51 | } 52 | } 53 | 54 | matches.push({ 55 | note: note.id, 56 | note_title: note.title, 57 | parent_id: note.parent_id, 58 | parent_title: folder, 59 | msg: todo_type.msg(match), 60 | assignee: todo_type.assignee(match), 61 | date: matchedDate, 62 | fromDate: fromDate, 63 | toDate: toDate, 64 | tags: todo_type.tags(match), 65 | index: index, 66 | priority: todo_type.priority(match), 67 | line: lineNumber 68 | }); 69 | index += 1; 70 | } 71 | lineNumber += 1; 72 | } 73 | 74 | if (matches.length > 0 || this._summary[note.id]?.length > 0) { 75 | // Check if the matches actually changed 76 | const dirty = JSON.stringify(this._summary[note.id]) != JSON.stringify(matches); 77 | 78 | this._summary[note.id] = matches; 79 | 80 | return dirty; 81 | } 82 | 83 | return false; 84 | } 85 | 86 | // This function scans all notes, but it's rate limited to it from crushing Joplin 87 | async search_in_all() { 88 | this._summary = {}; 89 | let page = 0; 90 | let r; 91 | do { 92 | page += 1; 93 | // I don't know how the basic search is implemented, it could be that it runs a regex 94 | // query on each note under the hood. If that is the case and this behaviour crushed 95 | // some slow clients, I should consider reverting this back to searching all notes 96 | // (with the rate limiter) 97 | r = await joplin.data.get(['search'], { query: this._settings.todo_type.query, fields: ['id', 'body', 'title', 'parent_id', 'is_conflict'], page: page }); 98 | if (r.items) { 99 | for (let note of r.items) { 100 | await this.search_in_note(note); 101 | } 102 | } 103 | } while(r.has_more); 104 | 105 | this._initialized = true; 106 | } 107 | 108 | async update_from_note(note: Note, note_title_date?: boolean) { 109 | if (note.id in this._summary) { 110 | delete this._summary[note.id]; 111 | } 112 | await this.search_in_note(note); 113 | } 114 | 115 | // Reads a parent title from cache, or uses the joplin api to get a title based on id 116 | async get_parent_title(id: string): Promise { 117 | if (!(id in this._folders)) { 118 | let f = await joplin.data.get(['folders', id], { fields: ['title'] }); 119 | this._folders[id] = f.title; 120 | } 121 | 122 | return this._folders[id]; 123 | } 124 | 125 | get summary(): Summary { 126 | return this._summary; 127 | } 128 | 129 | get settings(): Settings { 130 | return this._settings; 131 | } 132 | set settings(s: Settings) { 133 | this._settings = s; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/inlineTodo/common.ts: -------------------------------------------------------------------------------- 1 | // To add a new regex simple define one below 2 | // The title is what will appear in the settings menu 3 | // The regex is what will identify a todo line 4 | // The query is what will identify a note with a todo in it (Joplin search syntax) 5 | // The assignee is a function that extracts the assignee from the todo 6 | // The date is a function that extracts the date from the todo 7 | // The tags is a function that extracts the tags from the todo 8 | // The msg is a function that extracts the message from the todo 9 | export const regexes = { 10 | list: { 11 | title: 'Confluence Style', 12 | regex: /^\s*- \[ \]\s.*(?<=\s)(?:(@[^\s]+)|(\/\/[^\s]+)|(\+[^\s]+)|(![1234](?=\s))|())(?:[^\n]*)?/gm, 13 | query: '/"- [ ]"', 14 | assignee: (todo: string[]) => { 15 | const result = todo[0].match(/(?<=\s@)([^\s]+)/); 16 | return result ? result[0] : ''; 17 | }, 18 | date: (todo: string[]) => { 19 | const result = todo[0].match(/(?<=\s\/\/)([^\s]+)/); 20 | return result ? result[0] : ''; 21 | }, 22 | tags: (todo: string[]) => { 23 | // the /g is important to get multiple results instead of a single match 24 | const result = todo[0].match(/(?<=\s\+)[^\s]+/g); 25 | return result ? result : []; 26 | }, 27 | msg: (todo: string[]) => { 28 | let result = todo[0].split(/\s@[^\s]+/).join(''); 29 | result = result.split(/\s\/\/[^\s]+/).join(''); 30 | result = result.split(/\s\+[^\s]+/).join(''); 31 | result = result.split(/- \[ \]/).join(''); 32 | result = result.split(/(?<=\s)![1234]/).join(''); 33 | 34 | return result.trim(); 35 | }, 36 | priority: (todo: string[]) => { 37 | const result = todo[0].match(/(?<=\s!)([1234])/g); 38 | return result ? Number(result[0]) : 4; 39 | }, 40 | toggle: { open: '- [ ]', closed: '- [x]' }, 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/inlineTodo/mark_todo.ts: -------------------------------------------------------------------------------- 1 | import joplin from "api"; 2 | import {Settings, Todo} from "./types"; 3 | 4 | 5 | export async function set_origin_todo(todo: Todo, settings: Settings): Promise { 6 | const origin = await joplin.data.get(['notes', todo.note], { fields: ['body'] }); 7 | let lines = origin.body.split('\n'); 8 | const parser = settings.todo_type; 9 | 10 | let match: RegExpExecArray; 11 | for (let i = 0; i < lines.length; i++) { 12 | parser.regex.lastIndex = 0; 13 | match = parser.regex.exec(lines[i] + '\n'); 14 | if (match === null) { continue; } 15 | 16 | if (!((parser.msg(match) == todo.msg) && 17 | (parser.assignee(match) == todo.assignee) && 18 | (JSON.stringify(parser.tags(match)) == JSON.stringify(todo.tags)))) { 19 | continue; 20 | } 21 | 22 | lines[i] = lines[i].replace(parser.toggle.open, parser.toggle.closed); 23 | 24 | // edit origin note 25 | await joplin.data.put(['notes', todo.note], null, { body: lines.join('\n') }); 26 | 27 | return true; 28 | } 29 | 30 | return false 31 | } 32 | -------------------------------------------------------------------------------- /src/inlineTodo/settings.ts: -------------------------------------------------------------------------------- 1 | import joplin from "../../api"; 2 | import {SettingItemType} from "../../api/types"; 3 | 4 | export const INLINE_TODO_NOTE_TITLE_AS_DATE = 'bundle_inline_todo_note_title_as_date'; 5 | export const INLINE_TODO_ITEM_DESCRIPTION = 'bundle_inline_todo_item_description'; 6 | export const INLINE_TODO_AUTO_COMPLETION = 'bundle_inline_todo_auto_completion'; 7 | export const INLINE_TODO_FILTER_TAG = 'bundle_inline_todo_filter_tag'; 8 | 9 | export namespace settings { 10 | const SECTION = 'BundleInlineTodoSettings'; 11 | 12 | export async function register() { 13 | await joplin.settings.registerSection(SECTION, { 14 | label: "Bundle Inline Todo", 15 | iconName: "fas fa-check", 16 | }); 17 | 18 | let PLUGIN_SETTINGS = {}; 19 | 20 | PLUGIN_SETTINGS[INLINE_TODO_NOTE_TITLE_AS_DATE] = { 21 | value: false, 22 | public: true, 23 | section: SECTION, 24 | type: SettingItemType.Bool, 25 | label: 'Use note title as default task date', 26 | description: "When the note title means a date, then use it as the default task data for all the tasks in the note", 27 | }; 28 | 29 | PLUGIN_SETTINGS[INLINE_TODO_ITEM_DESCRIPTION] = { 30 | value: true, 31 | public: true, 32 | section: SECTION, 33 | type: SettingItemType.Bool, 34 | label: 'Show task description', 35 | description: "Show the text following tasks with one more indent as task description", 36 | }; 37 | 38 | PLUGIN_SETTINGS[INLINE_TODO_AUTO_COMPLETION] = { 39 | value: true, 40 | public: true, 41 | section: SECTION, 42 | type: SettingItemType.Bool, 43 | label: 'Show hints for todo tags and project. Triggered by "+" and "@". Requires restart' 44 | }; 45 | 46 | PLUGIN_SETTINGS[INLINE_TODO_FILTER_TAG] = { 47 | value: '', 48 | public: true, 49 | section: SECTION, 50 | type: SettingItemType.String, 51 | label: 'Note tags that you want to avoid in todo item scanning. tag1|tag2|tag3|...' 52 | }; 53 | 54 | await joplin.settings.registerSettings(PLUGIN_SETTINGS); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/inlineTodo/todoRender/index.ts: -------------------------------------------------------------------------------- 1 | import {conferenceStyleRender} from "./conferenceStyleRender"; 2 | 3 | export default function (context) { 4 | return { 5 | plugin: function (markdownIt, _options) { 6 | const pluginId = context.pluginId; 7 | 8 | conferenceStyleRender(markdownIt, _options); 9 | }, 10 | assets: function() { 11 | return [ 12 | { name: 'todoRender.css' } 13 | ]; 14 | }, 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/inlineTodo/todoRender/todoRender.css: -------------------------------------------------------------------------------- 1 | span.inline-todo { 2 | font-size: 90%; 3 | padding: 2px 3px; 4 | color: white; 5 | text-align: center; 6 | opacity: 0.75; 7 | } 8 | 9 | 10 | span.inline-todo-assignee { 11 | background-color: dodgerblue; 12 | border-radius: 4px; 13 | } 14 | 15 | span.inline-todo-date { 16 | background-color: orange; 17 | border-radius: 4px; 18 | } 19 | 20 | span.inline-todo-priority-1 { 21 | background: #e33e2f; 22 | } 23 | 24 | span.inline-todo-priority-2 { 25 | background: #f8d15f; 26 | } 27 | 28 | span.inline-todo-priority-3 { 29 | background: #549644; 30 | } 31 | 32 | span.inline-todo-priority-4 { 33 | background: #ececec; 34 | color: black; 35 | } 36 | 37 | span.inline-todo-date::before { 38 | content: '🕰 '; 39 | } 40 | 41 | .tag { 42 | position: relative; 43 | top: 0; 44 | z-index: 1; 45 | text-align: center; 46 | color: white; 47 | } 48 | 49 | .tag::before, 50 | .tag::after { 51 | content: ''; 52 | position: absolute; 53 | top: 0; 54 | transform: skew(-12deg); 55 | } 56 | 57 | .tag::after { 58 | right: 0; 59 | bottom: 0; 60 | z-index: -1; 61 | border-radius: 5px; 62 | background: red; 63 | } 64 | 65 | .tag-left::after { 66 | left: 0; 67 | } 68 | 69 | .tag-left::before { 70 | left: -10px; 71 | } 72 | 73 | .tag-right::after { 74 | background: #52C41B; 75 | left: 0; 76 | } 77 | -------------------------------------------------------------------------------- /src/inlineTodo/types.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface Note { 3 | id: string; 4 | body: string; 5 | title: string; 6 | parent_id: string; 7 | is_conflict: boolean; 8 | } 9 | 10 | export interface Todo { 11 | note: string; 12 | note_title: string; 13 | parent_id: string; 14 | parent_title: string; 15 | msg: string; 16 | assignee: string; 17 | date: string; 18 | tags: string[]; 19 | index: number; 20 | priority: number; 21 | description: string[]; 22 | indent: number; 23 | 24 | fromDate: Date; 25 | toDate: Date; 26 | line: number; 27 | } 28 | 29 | interface Toggle { 30 | open: string; 31 | closed: string; 32 | } 33 | 34 | interface RegexEntry { 35 | title: string; 36 | regex: RegExp; 37 | query: string; 38 | msg: (s: string[]) => string; 39 | assignee: (s: string[]) => string; 40 | date: (s: string[]) => string; 41 | tags: (s: string[]) => string[]; 42 | priority: (s: string[]) => number; 43 | toggle: Toggle; 44 | } 45 | 46 | export interface Settings { 47 | summary_id?: string; 48 | scan_period_s: number; 49 | scan_period_c: number; 50 | todo_type: RegexEntry; 51 | summary_type: string; 52 | force_sync: boolean; 53 | note_title_date: boolean; 54 | showDescription: boolean; 55 | 56 | filterTags: string[]; 57 | 58 | auto_completion: boolean; 59 | } 60 | 61 | export interface TitleEntry { 62 | title: string; 63 | } 64 | 65 | // Record; 66 | export type Summary = Record; 67 | 68 | -------------------------------------------------------------------------------- /src/inlineTodo/utils.ts: -------------------------------------------------------------------------------- 1 | import {Todo} from "./types"; 2 | import * as chrono from 'chrono-node'; 3 | 4 | export function filterItemsBySearchStr(items: Todo[], searchStr: string) { 5 | const conditions = searchStr.split(' '); 6 | const results = []; 7 | for (const item of items) { 8 | let passed = true; 9 | for (const cond of conditions) { 10 | if (cond.length === 0) { 11 | continue; 12 | } 13 | if (cond.startsWith('@')) { 14 | if (cond.length > 1 && (!item.assignee || (item.assignee && item.assignee.toLowerCase() !== cond.substr(1).toLowerCase()))) { 15 | passed = false; 16 | break; 17 | } else if (cond.length === 1 && item.assignee && item.assignee.length > 0) { 18 | passed = false; 19 | break; 20 | } 21 | } else if (cond.startsWith('+')) { 22 | if (cond.length > 1) { 23 | if (!item.tags) { 24 | passed = false; 25 | break; 26 | } else { 27 | let tagFound = false; 28 | for (const tag of item.tags) { 29 | const targetTag = cond.substr(1).toLowerCase(); 30 | if (tag.toLowerCase() === targetTag) { 31 | tagFound = true; 32 | break; 33 | } 34 | } 35 | 36 | if (!tagFound) { 37 | passed = false; 38 | break; 39 | } 40 | } 41 | } else if (cond.length === 1 && item.tags && item.tags.length > 0) { 42 | passed = false; 43 | break; 44 | } 45 | } else if (cond.startsWith('//')) { 46 | if (cond.length > 2) { 47 | const searchDate = chrono.parseDate(cond.substr(2)); 48 | console.log(searchDate, item.fromDate, item.toDate); 49 | if (searchDate && (!item.fromDate 50 | || (!item.toDate && daysDifference(item.fromDate, searchDate) !== 0) 51 | || (item.toDate && (daysDifference(item.fromDate, searchDate) < 0 || daysDifference(item.toDate, searchDate) > 0)))) { 52 | passed = false; 53 | break; 54 | } 55 | } else if (cond.length === 2 && item.fromDate) { 56 | passed = false; 57 | break; 58 | } 59 | } else if (cond.startsWith('!')) { 60 | if (cond.length > 1 && item.priority !== Number(cond.substr(1))) { 61 | passed = false; 62 | break; 63 | } 64 | } else { 65 | if (!item.msg.toLowerCase().includes(cond.toLowerCase())) { 66 | passed = false; 67 | break; 68 | } 69 | } 70 | } 71 | 72 | if (passed) { 73 | results.push(item); 74 | } 75 | } 76 | return results; 77 | } 78 | 79 | // https://stackoverflow.com/a/7763654/5513120 80 | export function daysDifference(d0, d1) { 81 | const diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12); 82 | return Math.round(diff / 8.64e7); 83 | } 84 | 85 | export function isTodayIncluded(fromDate, toDate) { 86 | return durationComparedToToday(fromDate, toDate) === 0; 87 | } 88 | 89 | /** 90 | * Return 0 if today is included; -1 if today is earlier, otherwise 1 is returned. 91 | */ 92 | export function durationComparedToToday(fromDate, toDate) { 93 | const today = new Date(); 94 | const fromDiff = daysDifference(fromDate, today); 95 | const toDiff = daysDifference(today, toDate); 96 | 97 | if (fromDiff >= 0 && toDiff >= 0) { 98 | return 0; 99 | } else if (fromDiff < 0) { 100 | return -1; 101 | } else { 102 | return 1; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/locale.ts: -------------------------------------------------------------------------------- 1 | export class MsgType { 2 | static ENABLE_OUTLINE_LABEL = 'ENABLE_OUTLINE_LABEL'; 3 | static ENABLE_OUTLINE_DESCRIPTION = 'ENABLE_OUTLINE_DESCRIPTION'; 4 | } 5 | 6 | 7 | export function localeString(msgType: string, locale: string): string { 8 | if (locale in LocaleMsg && msgType in LocaleMsg[locale]) { 9 | return LocaleMsg[locale][msgType]; 10 | } 11 | return LocaleMsg['default'][msgType]; 12 | } 13 | 14 | 15 | const LocaleMsg = { 16 | 'zh_CN': { 17 | ENABLE_OUTLINE_LABEL: '启用 Outline 菜单子插件', 18 | ENABLE_OUTLINE_DESCRIPTION: '原插件地址:https://github.com/cqroot/joplin-outline,需要重启。' 19 | }, 20 | 'default': { 21 | ENABLE_OUTLINE_LABEL: 'Enable Outline in bundle', 22 | ENABLE_OUTLINE_DESCRIPTION: 'Forked from https://github.com/cqroot/joplin-outline. Requires restart' 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 1, 3 | "id": "com.septemberhx.pluginBundle", 4 | "app_min_version": "2.8", 5 | "version": "0.5.5", 6 | "name": "Plugin Bundle", 7 | "description": "Table of Contents, Inline Todos, Daily Notes, and History aggregated in one panel with more eye-candy UI design.", 8 | "author": "SeptemberHX", 9 | "homepage_url": "https://github.com/SeptemberHX/joplin-plugin-bundle.git", 10 | "repository_url": "https://github.com/SeptemberHX/joplin-plugin-bundle.git", 11 | "keywords": [], 12 | "categories": [] 13 | } 14 | -------------------------------------------------------------------------------- /src/outline/index.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import { ContentScriptType } from 'api/types'; 3 | import { registerSettings, settingValue } from './settings'; 4 | import mdHeaders from './mdHeaders'; 5 | import panelHtml from './panelHtml'; 6 | import {SidebarPlugin, Sidebars} from "../sidebars/sidebarPage"; 7 | import {MsgType, OUTLINE_PLUGIN_ID} from "../common"; 8 | 9 | 10 | class OutlinePlugin extends SidebarPlugin { 11 | sidebars: Sidebars; 12 | currentHead: { 13 | text: string; 14 | lineno: number; 15 | }; 16 | 17 | constructor() { 18 | super(); 19 | 20 | this.id = OUTLINE_PLUGIN_ID; 21 | this.name = 'Outline'; 22 | this.icon = 'fas fa-list'; 23 | this.styles = [ 24 | './scripts/outline/webview.css' 25 | ]; 26 | this.scripts = [ 27 | './scripts/outline/webview.js' 28 | ]; 29 | } 30 | 31 | public async panelMsgProcess(message: any) { 32 | if (message.name === 'scrollToHeader') { 33 | const editorCodeView = await joplin.settings.globalValue('editor.codeView'); 34 | const noteVisiblePanes = await joplin.settings.globalValue('noteVisiblePanes'); 35 | if (editorCodeView && noteVisiblePanes.includes('editor')) { 36 | // scroll in raw markdown editor 37 | await joplin.commands.execute('editor.execCommand', { 38 | name: 'scrollToLine', 39 | args: [message.lineno], 40 | }); 41 | } else { 42 | // scroll in WYSIWYG editor or viewer 43 | await joplin.commands.execute('scrollToHash', message.hash); 44 | } 45 | return true; 46 | } else if (message.name === 'contextMenu') { 47 | const noteId = (await joplin.workspace.selectedNoteIds())[0]; 48 | const noteTitle = (await joplin.data.get(['notes', noteId], { fields: ['title'] })).title; 49 | const innerLink = `[${noteTitle}#${message.content}](:/${noteId}#${message.hash})`; 50 | 51 | const input = document.createElement('input'); 52 | input.setAttribute('value', innerLink); 53 | document.body.appendChild(input); 54 | input.select(); 55 | document.execCommand('copy'); 56 | document.body.removeChild(input); 57 | return true; 58 | } 59 | return false; 60 | } 61 | 62 | async cmMsgProcess(msg: any): Promise { 63 | switch (msg.type) { 64 | case MsgType.SCROLL_CHANGE: 65 | const note = await joplin.workspace.selectedNote(); 66 | if (note) { 67 | const headers = mdHeaders(note.body, msg.from, msg.to); 68 | if (headers.length > 0) { 69 | let i; 70 | for (i = headers.length - 1; i >= 0; i--) { 71 | if (headers[i].lineno < msg.from) { 72 | break; 73 | } 74 | } 75 | if (i < headers.length - 1) { 76 | i += 1; 77 | } 78 | const newHeader = headers[i]; 79 | 80 | if (!this.currentHead || (newHeader.text !== this.currentHead.text || newHeader.lineno !== this.currentHead.lineno)) { 81 | this.currentHead = newHeader; 82 | await this.updateTocView(); 83 | } 84 | } 85 | 86 | } 87 | return true; 88 | default: 89 | return false; 90 | } 91 | } 92 | 93 | public async init(sidebars: Sidebars) { 94 | this.sidebars = sidebars; 95 | await registerSettings(); 96 | 97 | await joplin.workspace.onNoteSelectionChange(() => { 98 | this.updateTocView(); 99 | }); 100 | await joplin.workspace.onNoteChange(() => { 101 | this.updateTocView(); 102 | }); 103 | await joplin.settings.onChange(() => { 104 | this.updateTocView(); 105 | }); 106 | 107 | await this.updateTocView(); 108 | } 109 | 110 | private async updateTocView() { 111 | const note = await joplin.workspace.selectedNote(); 112 | 113 | let headers; 114 | if (note) { 115 | headers = mdHeaders(note.body); 116 | } else { 117 | headers = []; 118 | } 119 | 120 | const htmlText = await panelHtml(headers, this.currentHead); 121 | await this.sidebars.updateHtml(this.id, htmlText); 122 | } 123 | } 124 | 125 | const outlinePlugin = new OutlinePlugin(); 126 | export default outlinePlugin; 127 | -------------------------------------------------------------------------------- /src/outline/mdHeaders.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-continue, no-useless-escape, no-constant-condition */ 2 | export default function mdHeaders(noteBody: string, from?: number, to?: number) { 3 | const headers = []; 4 | const lines = noteBody.split('\n').map((line, index) => ({ index, line })); 5 | let flagBlock = false; 6 | let flagComment = false; 7 | /* eslint-disable prefer-const */ 8 | for (let { index, line } of lines) { 9 | if (to && to < index) { break; } 10 | 11 | // check code block 12 | if (line.match(/(?:```)/)) { 13 | flagBlock = !flagBlock; 14 | continue; 15 | } 16 | // check comment block 17 | if (line.match(/(?:)/)) { 18 | flagComment = true; 19 | continue; 20 | } 21 | if (line.match(/(?:-->)/)) { 22 | flagComment = false; 23 | continue; 24 | } 25 | if (flagBlock || flagComment) continue; 26 | 27 | if (!line.match(/^ {0,3}#/)) continue; 28 | line = line.trim(); 29 | // remove closing '#'s 30 | line = line.replace(/\s+#*$/, ''); 31 | // remove HTML tags 32 | while (true) { 33 | let x = line.replace(/<[^\/][^>]*>([^<>]*?)<\/[^>]*>/, '$1'); 34 | if (x === line) break; 35 | line = x; 36 | } 37 | // remove math expressions 38 | while (true) { 39 | let x = line.replace(/\$.+?\$/, ''); 40 | if (x === line) break; 41 | line = x; 42 | } 43 | // remove Markdown links 44 | while (true) { 45 | let x = line.replace(/\[(.*?)\]\(.*?\)/, '$1'); 46 | if (x === line) break; 47 | line = x; 48 | } 49 | // remove nested Markdown '*'s and '_'s 50 | while (true) { 51 | let x = line.replace(/([_\*])(?!\s)((?:[^_\*]|[_\*]+(?=\s))+?)(? 6) continue; 58 | headers.push({ 59 | level: match[1].length, 60 | text: match[2] ?? '', 61 | lineno: index, 62 | }); 63 | } 64 | return headers; 65 | } 66 | -------------------------------------------------------------------------------- /src/outline/panelHtml.ts: -------------------------------------------------------------------------------- 1 | import {settingValue} from "./settings"; 2 | var md = require('markdown-it')() 3 | .use(require('markdown-it-mark')); 4 | 5 | const uslug = require('uslug'); 6 | 7 | // From https://stackoverflow.com/a/6234804/561309 8 | function escapeHtml(unsafe: string) { 9 | return unsafe 10 | .replace(/&/g, '&') 11 | .replace(//g, '>') 13 | .replace(/"/g, '"') 14 | .replace(/'/g, '''); 15 | } 16 | 17 | async function getHeaderPrefix(level: number) { 18 | /* eslint-disable no-return-await */ 19 | return await settingValue(`h${level}Prefix`); 20 | } 21 | 22 | export default async function panelHtml(headers: any[], currentHead) { 23 | // Settings 24 | const showNumber = await settingValue('showNumber'); 25 | const headerDepth = await settingValue('headerDepth'); 26 | const numberStyle = await settingValue('numberStyle'); 27 | const disableLinewrap = await settingValue('disableLinewrap'); 28 | 29 | let linewrapStyle = ''; 30 | if (disableLinewrap) { 31 | linewrapStyle += ` 32 | white-space: nowrap; 33 | text-overflow: ellipsis; 34 | overflow: hidden;`; 35 | } 36 | 37 | const slugs: any = {}; 38 | const itemHtml = []; 39 | const headerCount: number[] = [0, 0, 0, 0, 0, 0]; 40 | 41 | let headerN = 0; 42 | for (const header of headers) { 43 | // header depth 44 | /* eslint-disable no-continue */ 45 | if (header.level > headerDepth) { 46 | continue; 47 | } 48 | 49 | const isCurrentHeader = currentHead ? (header.text === currentHead.text && header.lineno === currentHead.lineno) : headerN === 0; 50 | 51 | // get slug 52 | const s = uslug(header.text); 53 | const num = slugs[s] ? slugs[s] : 1; 54 | const output = [s]; 55 | if (num > 1) output.push(num); 56 | slugs[s] = num + 1; 57 | const slug = output.join('-'); 58 | 59 | headerCount[header.level - 1] += 1; 60 | for (let i = header.level; i < 6; i += 1) { 61 | headerCount[i] = 0; 62 | } 63 | 64 | let numberPrefix = ''; 65 | if (showNumber) { 66 | for (let i = 0; i < header.level; i += 1) { 67 | numberPrefix += headerCount[i]; 68 | if (i !== header.level - 1) { 69 | numberPrefix += '.'; 70 | } 71 | } 72 | } 73 | 74 | /* eslint-disable no-await-in-loop */ 75 | itemHtml.push(` 76 | `); 81 | 82 | const prefix = await getHeaderPrefix(header.level); 83 | if (prefix && prefix.length > 0) { 84 | itemHtml.push(`${prefix}`); 85 | } 86 | 87 | itemHtml.push(` 88 | ${numberPrefix} 89 | ${md.renderInline(header.text)} 90 | `); 91 | 92 | headerN += 1; 93 | } 94 | 95 | if (itemHtml.length === 0) { 96 | itemHtml.push(` 97 |
98 | 99 |

No table of contents

100 |
101 | `); 102 | } 103 | 104 | return ` 105 |
106 |
107 | ${itemHtml.join('\n')} 108 |
109 |
`; 110 | } 111 | -------------------------------------------------------------------------------- /src/outline/settings.ts: -------------------------------------------------------------------------------- 1 | import { SettingItemType } from 'api/types'; 2 | import joplin from 'api'; 3 | 4 | export async function registerSettings() { 5 | await joplin.settings.registerSection('outline.settings', { 6 | label: 'Outline', 7 | iconName: 'fas fa-bars', 8 | }); 9 | 10 | await joplin.settings.registerSettings({ 11 | headerDepth: { 12 | type: SettingItemType.Int, 13 | value: 6, 14 | description: 'Header depth', 15 | section: 'outline.settings', 16 | public: true, 17 | label: 'Header Depth', 18 | }, 19 | disableLinewrap: { 20 | type: SettingItemType.Bool, 21 | value: false, 22 | description: 'Disable the linewrap', 23 | section: 'outline.settings', 24 | public: true, 25 | label: 'Disable Linewrap', 26 | }, 27 | showNumber: { 28 | type: SettingItemType.Bool, 29 | value: false, 30 | description: 'show numbered headers', 31 | section: 'outline.settings', 32 | public: true, 33 | label: 'Show Number', 34 | }, 35 | numberStyle: { 36 | type: SettingItemType.String, 37 | value: 'font-weight: normal; font-style: normal', 38 | description: 'font-weight: normal; font-style: normal', 39 | section: 'outline.settings', 40 | public: true, 41 | label: 'Number Style', 42 | advanced: true, 43 | }, 44 | h1Prefix: { 45 | type: SettingItemType.String, 46 | value: '', 47 | section: 'outline.settings', 48 | public: true, 49 | label: 'H1 Prefix', 50 | advanced: true, 51 | }, 52 | h2Prefix: { 53 | type: SettingItemType.String, 54 | value: '', 55 | section: 'outline.settings', 56 | public: true, 57 | label: 'H2 Prefix', 58 | advanced: true, 59 | }, 60 | h3Prefix: { 61 | type: SettingItemType.String, 62 | value: '', 63 | section: 'outline.settings', 64 | public: true, 65 | label: 'H3 Prefix', 66 | advanced: true, 67 | }, 68 | h4Prefix: { 69 | type: SettingItemType.String, 70 | value: '', 71 | section: 'outline.settings', 72 | public: true, 73 | label: 'H4 Prefix', 74 | advanced: true, 75 | }, 76 | h5Prefix: { 77 | type: SettingItemType.String, 78 | value: '', 79 | section: 'outline.settings', 80 | public: true, 81 | label: 'H5 Prefix', 82 | advanced: true, 83 | }, 84 | h6Prefix: { 85 | type: SettingItemType.String, 86 | value: '', 87 | section: 'outline.settings', 88 | public: true, 89 | label: 'H6 Prefix', 90 | advanced: true, 91 | }, 92 | }); 93 | } 94 | 95 | export function settingValue(key: string) { 96 | return joplin.settings.value(key); 97 | } 98 | -------------------------------------------------------------------------------- /src/readcube/common.ts: -------------------------------------------------------------------------------- 1 | export const PAPERS_COOKIE = 'PapersPluginCookie'; 2 | export const PAPERS_FOLDER_NAME = 'Papers'; 3 | export const CITATION_POPUP_ID = 'enhancement_citation_popup_id'; 4 | export const PAPERS_NOTEID_TO_PAPERID_TITLE = 'papers.db'; 5 | export const SOURCE_URL_PAPERS_PREFIX = 'papers_'; 6 | export const SOURCE_URL_DIDA_PREFIX = 'dida_'; 7 | export const ENABLE_CUSTOM_STYLE = 'PapersPluginEnableCustomStyle'; 8 | export const ENABLE_ENHANCED_BLOCKQUOTE = 'PapersPluginEnableEnhancedQuote'; 9 | export const ZOTERO_USER_ID = 'PapersZoteroUserId'; 10 | export const ZOTERO_USER_API_KEY = 'PapersZoteroUserApiKey'; 11 | export const PAPERS_SERVICE_PROVIDER = 'PapersServiceProvider'; 12 | export const PAPERS_CREATE_PAPER_NOTE_IN_CURRENT_FOLDER = 'PapersCreateNotePaperInCurrentFolder'; 13 | 14 | export enum PaperServiceType { 15 | READCUBE, 16 | ZOTERO, 17 | } 18 | 19 | 20 | export class PaperConfig { 21 | type: PaperServiceType; 22 | papersCookie: string; 23 | zoteroUserId: number; 24 | zoteroApiKey: string; 25 | paperNoteInCurrFolder: boolean; 26 | } 27 | 28 | 29 | export function extractInfo(data: string) { 30 | const splitResults = data.split(':'); 31 | let info = {}; 32 | for (const result of splitResults) { 33 | if (result.startsWith(SOURCE_URL_PAPERS_PREFIX)) { 34 | info[SOURCE_URL_PAPERS_PREFIX] = result.substr(SOURCE_URL_PAPERS_PREFIX.length); 35 | } else if (result.startsWith(SOURCE_URL_DIDA_PREFIX)) { 36 | info[SOURCE_URL_DIDA_PREFIX] = result.substr(SOURCE_URL_DIDA_PREFIX.length); 37 | } 38 | } 39 | return info; 40 | } 41 | 42 | export function updateInfo(raw, prefix, data) { 43 | let info = extractInfo(raw); 44 | info[prefix] = data; 45 | 46 | let newInfoStrs = []; 47 | for (let prefix in info) { 48 | newInfoStrs.push(`${prefix}${info[prefix]}`); 49 | } 50 | return newInfoStrs.join(':'); 51 | } 52 | -------------------------------------------------------------------------------- /src/readcube/driver/codemirror/autoCitation/index.ts: -------------------------------------------------------------------------------- 1 | import InsertCitation from "./insertCitation"; 2 | 3 | module.exports = { 4 | default: function(_context) { 5 | return { 6 | plugin: function (CodeMirror) { 7 | CodeMirror.defineOption("enhancement_autoCitation", [], async function(cm, val, old) { 8 | const commandBridge = new InsertCitation(cm); 9 | CodeMirror.defineExtension('enhancement_insertCitation', commandBridge.insertPaperCitations.bind(commandBridge)); 10 | CodeMirror.defineExtension('enhancement_insertAnnotation', commandBridge.insertAnnotationCitations.bind(commandBridge)); 11 | }); 12 | }, 13 | codeMirrorOptions: { 14 | 'enhancement_autoCitation': true, 15 | }, 16 | assets: function() { 17 | return [ ]; 18 | } 19 | } 20 | }, 21 | } 22 | -------------------------------------------------------------------------------- /src/readcube/driver/codemirror/autoCitation/insertCitation.ts: -------------------------------------------------------------------------------- 1 | import {colorMap} from "../../../utils/paperCardGenerator"; 2 | import {AnnotationItem} from "../../../lib/base/paperType"; 3 | 4 | export default class InsertCitation { 5 | constructor(private readonly editor) {} 6 | private readonly doc = this.editor.getDoc(); 7 | 8 | insertPaperCitations(options) { 9 | const itemCitations: string[] = options[0]; 10 | const itemRefNames: string[] = options[1]; 11 | const selections = this.doc.listSelections(); 12 | if (itemCitations.length == 0 || !selections || selections.length == 0) { 13 | return; 14 | } 15 | const currSelection = selections[0]; 16 | 17 | let appendRefsText = ''; 18 | let insertRefNames = []; 19 | let text = this.doc.getValue(); 20 | for (const index in itemCitations) { 21 | const refText = `[^${itemRefNames[index]}]: ${itemCitations[index]}`; 22 | if (text.indexOf(refText) < 0) { 23 | appendRefsText += refText + '\n'; 24 | } 25 | insertRefNames.push(`[^${itemRefNames[index]}]`); 26 | } 27 | 28 | if (appendRefsText.length > 0) { 29 | if (text[text.length - 1] != '\n') { 30 | text += '\n\n\n'; 31 | } 32 | text += appendRefsText; 33 | } 34 | 35 | const info = this.editor.getScrollInfo(); 36 | this.doc.setValue(text); 37 | 38 | const refNameStr = insertRefNames.join(''); 39 | this.doc.replaceRange(refNameStr, currSelection.to()); 40 | this.editor.scrollTo(info.left, info.top); 41 | this.editor.setCursor({line: currSelection.head.line, ch: currSelection.head.ch + refNameStr.length}); 42 | 43 | this.editor.focus(); 44 | } 45 | 46 | insertAnnotationCitations(options) { 47 | const annotations: AnnotationItem[] = options[0]; 48 | const enableEnhanced: boolean = options[1]; 49 | const annotationLinks: string = options[2]; 50 | const selections = this.doc.listSelections(); 51 | if (annotations.length == 0 || !selections || selections.length == 0) { 52 | return; 53 | } 54 | const currSelection = selections[0]; 55 | 56 | let insertedText = ""; 57 | let i = 0; 58 | for (const anno of annotations) { 59 | insertedText += '\n!!! note'; 60 | if (anno.text && anno.text.length > 0) { 61 | insertedText += ` [📜](${annotationLinks[i]}) ${anno.text.replace('\n', ' ')}`; 62 | if (enableEnhanced) { 63 | insertedText += ` [color=${anno.color_id < 0 ? anno.color : colorMap[anno.color_id]}][name=${anno.user_name}][date=${new Date(anno.modified).toLocaleString()}]`; 64 | } 65 | insertedText += '\n'; 66 | } else { 67 | insertedText += `\n[🎶](${annotationLinks[i]}) `; 68 | } 69 | 70 | if (anno.note && anno.note.length > 0) { 71 | insertedText += `${anno.note.replace('\n', ' ')}`; 72 | insertedText += '\n'; 73 | } 74 | i += 1; 75 | } 76 | insertedText += '!!!\n'; 77 | this.doc.replaceRange(insertedText, currSelection.to()); 78 | this.editor.setCursor({line: currSelection.head.line, ch: currSelection.head.ch + insertedText.length}); 79 | this.editor.focus(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/readcube/driver/codemirror/paperBlockRender/index.ts: -------------------------------------------------------------------------------- 1 | import {LineHandle} from "codemirror"; 2 | import {CMBlockMarkerHelperV2} from "../../../utils/CMBlockMarkerHelperV2"; 3 | import {debounce} from "ts-debounce"; 4 | import {buildPaperCard} from "../../../utils/paperCardGenerator"; 5 | import {findLineWidgetAtLine} from "../../../utils/cm-utils"; 6 | import {PAPER_ID_REG} from "../../../utils/reg"; 7 | 8 | const ENHANCEMENT_PAPER_BLOCK_SPAN_MARKER_CLASS = 'enhancement-paper-block-marker'; 9 | const ENHANCEMENT_PAPER_BLOCK_SPAN_MARKER_LINE_CLASS = 'enhancement-paper-block-marker-line'; 10 | 11 | 12 | module.exports = { 13 | default: function (_context) { 14 | return { 15 | plugin: function (CodeMirror) { 16 | CodeMirror.defineOption("readcubePaperRender", [], async function (cm, val, old) { 17 | // Block Katex Math Render 18 | const blockPaperHelper = new CMBlockMarkerHelperV2(cm, null, /^\s*```paper\s*$/, /^\s*```\s*$/, (beginMatch, endMatch, content: string, fromLine, toLine) => { 19 | let divElement = document.createElement("div"); 20 | 21 | const idMatch = PAPER_ID_REG.exec(content); 22 | if (idMatch) { 23 | _context.postMessage({type: 'queryPaper', content: idMatch[1]}).then((item) => { 24 | divElement.innerHTML = buildPaperCard(item, null); 25 | const lineWidget = findLineWidgetAtLine(cm, toLine, ENHANCEMENT_PAPER_BLOCK_SPAN_MARKER_CLASS + '-line-widget'); 26 | if (lineWidget) { 27 | setTimeout(() => { 28 | lineWidget.changed() 29 | }, 50); 30 | } 31 | }) 32 | } 33 | 34 | return divElement; 35 | }, () => { 36 | const span = document.createElement('span'); 37 | span.textContent = '===> Folded Papers Block <==='; 38 | span.style.cssText = 'color: lightgray; font-size: smaller; font-style: italic;'; 39 | return span; 40 | }, ENHANCEMENT_PAPER_BLOCK_SPAN_MARKER_CLASS, true, false, null, (content, e) => { 41 | const match = PAPER_ID_REG.exec(content); 42 | if (match) { 43 | _context.postMessage({ 44 | type: 'openPaper', 45 | content: match[1] 46 | }); 47 | } 48 | }); 49 | 50 | cm.on('renderLine', (editor, line: LineHandle, element: Element) => { 51 | if (element.getElementsByClassName(ENHANCEMENT_PAPER_BLOCK_SPAN_MARKER_CLASS).length > 0) { 52 | element.classList.add(ENHANCEMENT_PAPER_BLOCK_SPAN_MARKER_LINE_CLASS); 53 | } 54 | }) 55 | 56 | function process() { 57 | cm.startOperation(); 58 | blockPaperHelper.process(true); 59 | cm.endOperation(); 60 | } 61 | 62 | const debounceProcess = debounce(process, 100); 63 | cm.on('change', async function (cm, changeObjs) { 64 | if (changeObjs.origin === 'setValue') { 65 | process(); 66 | // this.unfoldAtCursor(); 67 | } else if (changeObjs.origin === 'undo' || changeObjs.origin === 'redo') { 68 | await debounceProcess(); 69 | } 70 | }); 71 | cm.on('cursorActivity', debounceProcess); 72 | cm.on('viewportChange', debounceProcess); 73 | }); 74 | }, 75 | codeMirrorOptions: { 76 | 'readcubePaperRender': true, 77 | }, 78 | assets: function () { 79 | return [ 80 | { name: 'paperLineWidget.css' } 81 | ] 82 | } 83 | } 84 | }, 85 | } 86 | -------------------------------------------------------------------------------- /src/readcube/driver/codemirror/paperBlockRender/paperLineWidget.css: -------------------------------------------------------------------------------- 1 | .enhancement-paper-block-marker-line { 2 | display: none; 3 | } 4 | 5 | .enhancement-paper-block-marker-line-widget .paper_tg { 6 | max-width: 1000px; 7 | margin: auto; 8 | border-collapse: collapse; 9 | border-spacing: 0; 10 | } 11 | 12 | .enhancement-paper-block-marker-line-widget .paper_tg td { 13 | border-color: black; 14 | border-style: solid; 15 | border-width: 1px; 16 | font-family: Times New Roman, serif !important; 17 | font-size: 14px; 18 | overflow: hidden; 19 | padding: 10px 5px; 20 | word-break: normal; 21 | } 22 | 23 | .enhancement-paper-block-marker-line-widget .paper_tg th { 24 | border-color: black; 25 | border-style: solid; 26 | border-width: 1px; 27 | font-size: 14px; 28 | font-weight: normal; 29 | overflow: hidden; 30 | word-break: normal; 31 | } 32 | 33 | .enhancement-paper-block-marker-line-widget .paper_tg th a, 34 | .enhancement-paper-block-marker-line-widget td i { 35 | font-family: Times New Roman, serif !important; 36 | } 37 | 38 | .enhancement-paper-block-marker-line-widget .paper_tg_title, 39 | .enhancement-paper-block-marker-line-widget .paper_tg_from, 40 | .enhancement-paper-block-marker-line-widget .paper_tg_tags, 41 | .enhancement-paper-block-marker-line-widget .paper_tg_stars, 42 | .enhancement-paper-block-marker-line-widget .paper_tg_authors, 43 | .enhancement-paper-block-marker-line-widget .paper_tg_from, 44 | .enhancement-paper-block-marker-line-widget .paper_tg_year { 45 | border-color: inherit; 46 | font-size: large; 47 | text-align: center; 48 | vertical-align: middle; 49 | } 50 | 51 | .enhancement-paper-block-marker-line-widget th.paper_tg_title { 52 | font-weight: bold !important; 53 | } 54 | 55 | .enhancement-paper-block-marker-line-widget th.paper_tg_abstract { 56 | border-color: inherit; 57 | text-align: left; 58 | vertical-align: top; 59 | } 60 | 61 | .enhancement-paper-block-marker-line-widget th.paper_tg_from { 62 | width: 50%; 63 | } 64 | 65 | .enhancement-paper-block-marker-line-widget .paper_tg_tags { 66 | width: 25%; 67 | } 68 | 69 | .enhancement-paper-block-marker-line-widget .noteBoxes 70 | { 71 | border: 1px solid; 72 | border-radius: 5px; 73 | padding: 10px; 74 | margin: 10px 0; 75 | width: 300px; 76 | } 77 | -------------------------------------------------------------------------------- /src/readcube/driver/markdownItRenderer/paperFence/index.ts: -------------------------------------------------------------------------------- 1 | import {PAPER_ID_REG} from "../../../utils/reg"; 2 | 3 | export default function (context) { 4 | return { 5 | plugin: function (markdownIt, _options) { 6 | const pluginId = context.pluginId; 7 | 8 | const defaultRender = markdownIt.renderer.rules.fence || function (tokens, idx, options, env, self) { 9 | return self.renderToken(tokens, idx, options, env, self); 10 | }; 11 | 12 | markdownIt.renderer.rules.fence = function (tokens, idx, options, env, self) { 13 | const token = tokens[idx]; 14 | console.log(token); 15 | if (token.info !== 'paper') return defaultRender(tokens, idx, options, env, self); 16 | 17 | const idMatch = PAPER_ID_REG.exec(token.content); 18 | if (idMatch) { 19 | return ` 20 |
${idMatch[1]}
21 | `; 22 | } else { 23 | return defaultRender(tokens, idx, options, env, self); 24 | } 25 | }; 26 | }, 27 | assets: function () { 28 | return [ 29 | {name: 'paperFence.css'}, 30 | {name: 'paperRender.js'} 31 | ]; 32 | }, 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/readcube/driver/markdownItRenderer/paperFence/paperFence.css: -------------------------------------------------------------------------------- 1 | /* for papers */ 2 | .paper_tg { 3 | max-width: 1000px; 4 | width: 90%; 5 | margin: auto; 6 | border-collapse: collapse; 7 | border-spacing: 0; 8 | } 9 | 10 | .paper_tg td { 11 | border-color: black; 12 | border-style: solid; 13 | border-width: 1px; 14 | font-family: Arial, sans-serif; 15 | font-size: 14px; 16 | overflow: hidden; 17 | padding: 10px 5px; 18 | word-break: normal; 19 | } 20 | 21 | .paper_tg th { 22 | border-color: black; 23 | border-style: solid; 24 | border-width: 1px; 25 | font-family: Arial, sans-serif; 26 | font-size: 14px; 27 | font-weight: normal; 28 | overflow: hidden; 29 | padding: 10px 5px; 30 | word-break: normal; 31 | } 32 | 33 | .paper_tg_title, .paper_tg_from, .paper_tg_tags, .paper_tg_stars, .paper_tg_authors, .paper_tg_from, .paper_tg_year { 34 | border-color: inherit; 35 | font-size: large; 36 | text-align: center; 37 | vertical-align: middle; 38 | } 39 | 40 | th.paper_tg_title { 41 | font-weight: bold !important; 42 | } 43 | 44 | th.paper_tg_abstract { 45 | border-color: inherit; 46 | text-align: left; 47 | vertical-align: top; 48 | } 49 | 50 | th.paper_tg_from { 51 | width: 50%; 52 | } 53 | 54 | .paper_tg_tags { 55 | width: 25%; 56 | } 57 | 58 | 59 | .noteBoxes 60 | { 61 | border: 1px solid; 62 | border-radius: 5px; 63 | padding: 10px; 64 | margin: 10px 0; 65 | width: 300px; 66 | } 67 | 68 | .type1 69 | { 70 | border-color: #E76F51; 71 | background-color: rgba(231, 111, 81, 0.1); 72 | } 73 | 74 | .type2 75 | { 76 | border-color: #2A9D8F; 77 | background-color: rgba(42, 157, 143, 0.1); 78 | } 79 | 80 | .type3 81 | { 82 | border-color: #0096C7; 83 | background-color: rgba(0, 150, 199, 0.1); 84 | } 85 | 86 | td.paper_tg_notes 87 | { 88 | border-color: #00B353; 89 | background-color: rgba(0, 179, 83, 0.1); 90 | } 91 | -------------------------------------------------------------------------------- /src/readcube/driver/markdownItRenderer/paperFence/paperRender.js: -------------------------------------------------------------------------------- 1 | function generateBodyForPaperFence(title, authors, from, tags, rating, abstract, collection_id, item_id, 2 | year, page, volume, notes) { 3 | let stars = '☆☆☆☆☆'; 4 | switch (rating) { 5 | case 1: 6 | stars = '★☆☆☆☆'; 7 | break; 8 | case 2: 9 | stars = '★★☆☆☆'; 10 | break; 11 | case 3: 12 | stars = '★★★☆☆'; 13 | break; 14 | case 4: 15 | stars = '★★★★☆'; 16 | break; 17 | case 5: 18 | stars = '★★★★★'; 19 | break; 20 | default: 21 | break; 22 | } 23 | 24 | return ` 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 |
${title}
${authors.join(', ')}
${from}${year}${tags.length > 0 ? tags : 'No tags'}${stars}
${abstract}
User Notes:
${notes}
48 | ` 49 | } 50 | 51 | document.addEventListener('joplin-noteDidUpdate', () => { 52 | loadPaperDetail(); 53 | }); 54 | 55 | const initIID_paper = setInterval(() => { 56 | clearInterval(initIID_paper); 57 | loadPaperDetail(); 58 | }, 100); 59 | 60 | function loadPaperDetail() { 61 | const paperRenderDivs = document.getElementsByClassName('paperRender'); 62 | for (const div of paperRenderDivs) { 63 | webviewApi.postMessage("enhancement_paper_fence_renderer", div.textContent).then(item => { 64 | if (item) { 65 | div.innerHTML = generateBodyForPaperFence(item.title, item.authors, item.journal, item.tags, item.rating, 66 | item.abstract, item.collection_id, item.id, item.year, item.page, item.volume, item.notes); 67 | } 68 | }); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/readcube/driver/style/index.ts: -------------------------------------------------------------------------------- 1 | export default function (context) { 2 | return { 3 | plugin: function (markdownIt, _options) { 4 | const pluginId = context.pluginId; 5 | }, 6 | assets: function() { 7 | return [ 8 | { name: 'paperStyle.css' } 9 | ]; 10 | }, 11 | } 12 | } -------------------------------------------------------------------------------- /src/readcube/driver/style/paperStyle.css: -------------------------------------------------------------------------------- 1 | :root { 2 | /* 基准字体 */ 3 | /* 备选:Times, "Times New Roman" */ 4 | --base-Latin-font: "Times New Roman", "Times New Roman 10"; 5 | --base-Chinese-font: "宋体-简", "华文宋体", "Noto Serif CJK SC"; 6 | --base-font-size: 11pt; 7 | --chapter-Chinese-font: "华文黑体"; 8 | --toc-font: ""; 9 | } 10 | 11 | body { 12 | counter-reset: h2N h3N h4N liist liiist katex; 13 | } 14 | 15 | 16 | /* blockquote */ 17 | blockquote { 18 | border-left: 4px solid #0087ed; 19 | border-radius: 2px; 20 | } 21 | 22 | mark { 23 | background-color: mediumseagreen; 24 | color: white; 25 | border-radius: 4px; 26 | padding: 2px; 27 | } 28 | 29 | ins { 30 | text-decoration-color: #fe0013; 31 | text-underline-offset: 2px; 32 | text-decoration-thickness: 2px; 33 | } 34 | 35 | img { 36 | max-width: 100%; 37 | height: auto; 38 | text-align: center; 39 | } 40 | 41 | .admonition { 42 | border-left: 4px solid #448aff; 43 | border-radius: 2px; 44 | } 45 | 46 | 47 | /* inline code */ 48 | .inline-code { 49 | border: none !important; 50 | font-family: "Menlo", "DejaVu Sans Mono", "Liberation Mono", "Consolas", "Ubuntu Mono", "Courier New", "andale mono", "lucida console", monospace !important; 51 | white-space: pre-wrap !important; 52 | word-wrap: normal !important; 53 | word-break: keep-all !important; 54 | padding: 2px 4px !important; 55 | color: #c0341d !important; 56 | background-color: #fbe5e1 !important; 57 | border-radius: 4px !important; 58 | } 59 | 60 | /* Node Link Favicon */ 61 | .note-link-external-website-icon > img { 62 | margin-top: auto !important; 63 | } 64 | 65 | .footnotes { 66 | counter-set: footnote-item-count; 67 | } 68 | 69 | li.footnote-item { 70 | counter-increment: footnote-item-count; 71 | } 72 | 73 | li.footnote-item::marker { 74 | content: '[' counter(footnote-item-count) ']. '; 75 | } 76 | 77 | span.resource-icon.fa-joplin { 78 | margin-right: 3px; 79 | margin-bottom: 1px; 80 | height: 14px; 81 | width: 12px; 82 | } 83 | 84 | /* h2 h3 h4 自动编号 */ 85 | 86 | h2 { 87 | counter-increment: h2N; 88 | counter-reset: h3N h4N; 89 | } 90 | 91 | h2::before { 92 | content: counter(h2N); 93 | margin-left: -0.5em; 94 | margin-right: 1em; 95 | } 96 | 97 | h3 { 98 | counter-increment: h3N; 99 | counter-reset: h4N; 100 | } 101 | 102 | h3::before { 103 | content: counter(h2N) "." counter(h3N); 104 | margin-left: -0.5em; 105 | margin-right: 1em; 106 | } 107 | 108 | h4 { 109 | counter-increment: h4N; 110 | } 111 | 112 | h4::before { 113 | content: counter(h2N) "." counter(h3N) "." counter(h4N); 114 | margin-left: -0.5em; 115 | margin-right: 1em; 116 | } 117 | 118 | p, blockquote, li, td { 119 | font-family: var(--toc-font), var(--base-Latin-font), var(--base-Chinese-font), serif !important; 120 | } 121 | 122 | h1, h2, h3, h4, h5, h6 { 123 | font-family: var(--base-Latin-font), var(--chapter-Chinese-font); 124 | } 125 | 126 | /* ============ 多级列表样式 ============ */ 127 | ol { 128 | /* 有序列表第一级:数字 */ 129 | list-style: decimal; 130 | } 131 | 132 | ol ol { 133 | counter-reset: liist; 134 | list-style: none; 135 | } 136 | 137 | ol ol li { 138 | counter-increment: liist; 139 | position: relative; 140 | } 141 | 142 | ol ol li::before { 143 | /* 有序列表第二级:括号加小写字母 */ 144 | content: "(" counter(liist, lower-alpha) ")."; 145 | left: -1.2em; 146 | margin-right: -0.6em; 147 | position: relative; 148 | } 149 | 150 | ol ol ol { 151 | counter-reset: liiist; 152 | list-style: none; 153 | margin: 0; 154 | } 155 | 156 | ol ol ol li { 157 | counter-increment: liiist; 158 | position: relative; 159 | } 160 | 161 | ol ol ol li::before { 162 | /* 有序列表第三级:小写罗马数字 */ 163 | content: counter(liiist, lower-roman) ".  "; 164 | align-self: flex-end; 165 | position: absolute; 166 | left: -2rem; 167 | width: 4.2rem; 168 | text-align: right; 169 | } 170 | 171 | #rendered-md ul, #rendered-md ol { 172 | margin-bottom: revert !important; 173 | } 174 | 175 | li { 176 | position: relative; 177 | } 178 | /* ============ 多级列表样式END ============ */ 179 | 180 | figcaption { 181 | font-family: var(--base-Latin-font), var(--base-Chinese-font), serif; 182 | } 183 | 184 | span.katex-display span.katex span.katex-html { 185 | counter-increment: katex; 186 | } 187 | 188 | span.katex-display span.katex span.katex-html::after { 189 | content: '(' counter(katex) ')'; 190 | right: 0; 191 | position: absolute; 192 | top: 50%; 193 | transform: translateY(-50%); 194 | } 195 | 196 | sup.footnote-ref { 197 | vertical-align: baseline; 198 | font-size: inherit; 199 | } 200 | 201 | div#rendered-md { 202 | max-width: 750pt; 203 | margin: auto; 204 | } 205 | -------------------------------------------------------------------------------- /src/readcube/lib/PaperSvcFactory.ts: -------------------------------------------------------------------------------- 1 | import {PaperSvc} from "./base/paperSvc"; 2 | import {PaperConfig, PaperServiceType} from "../common"; 3 | import {ReadcubePaperSvc} from "./papers/readcubePaperSvc"; 4 | import {AnnotationItem, PaperItem, PaperMetadata} from "./base/paperType"; 5 | import { PaperNotify } from "./base/paperNotify"; 6 | import {PapersWS} from "./papers/papersWS"; 7 | import {ZoteroPaperSvc} from "./zotero/zoteroPaperSvc"; 8 | import {ZoteroWS} from "./zotero/zoteroWS"; 9 | import {PaperExtend} from "./base/paperExtend"; 10 | import {debounce} from "ts-debounce"; 11 | 12 | class PaperSvcFactory extends PaperSvc { 13 | paperSvc: PaperSvc; 14 | paperNotify: PaperNotify; 15 | paperExtend: PaperExtend; 16 | debounceGetAllItems; 17 | 18 | async init(settings: PaperConfig) { 19 | console.log('Papers: Init paper service...'); 20 | switch (settings.type) { 21 | case PaperServiceType.READCUBE: 22 | this.paperSvc = new ReadcubePaperSvc(); 23 | this.paperNotify = new PapersWS(settings); 24 | break; 25 | case PaperServiceType.ZOTERO: 26 | this.paperSvc = new ZoteroPaperSvc(); 27 | this.paperNotify = new ZoteroWS(settings); 28 | break; 29 | default: 30 | break; 31 | } 32 | 33 | if (settings.papersCookie && settings.papersCookie.length > 0) { 34 | this.paperExtend = new PaperExtend(); 35 | this.paperExtend.init(settings); 36 | } 37 | 38 | await this.paperSvc.init(settings); 39 | 40 | this.debounceGetAllItems = debounce(this.paperSvc.getAllItems, 10000); 41 | } 42 | 43 | externalLink(paperItem: PaperItem): String { 44 | return this.paperSvc.externalLink(paperItem); 45 | } 46 | 47 | externalAnnotationLink(anno: AnnotationItem): String { 48 | return this.paperSvc.externalAnnotationLink(anno); 49 | } 50 | 51 | getSvc(): PaperSvc{ 52 | return this.paperSvc; 53 | } 54 | 55 | async onPaperChange(callback) { 56 | if (this.paperNotify) { 57 | this.paperNotify.onPaperChangeListeners.push(callback); 58 | } 59 | } 60 | 61 | async getAllItems(): Promise { 62 | console.log('Papers: Get all items...'); 63 | return await this.debounceGetAllItems(); 64 | } 65 | 66 | async getAnnotation(paperItem: PaperItem): Promise { 67 | return await this.paperSvc.getAnnotation(paperItem); 68 | } 69 | 70 | async getMetadata(doi: string): Promise { 71 | if (this.paperExtend) { 72 | return await this.paperExtend.getMetadata(doi); 73 | } 74 | return null; 75 | } 76 | 77 | async extractNotes(paperItem: PaperItem): Promise { 78 | return await this.paperSvc.extractNotes(paperItem); 79 | } 80 | } 81 | 82 | 83 | const paperSvc = new PaperSvcFactory(); 84 | export default paperSvc; 85 | -------------------------------------------------------------------------------- /src/readcube/lib/base/paperExtend.ts: -------------------------------------------------------------------------------- 1 | import {PaperFigure, PaperMetadata, PaperReference} from "./paperType"; 2 | import {PaperConfig} from "../../common"; 3 | import fetch from 'node-fetch'; 4 | 5 | export class PaperExtend { 6 | papersCookie: string; 7 | 8 | init(settings: PaperConfig) { 9 | this.papersCookie = settings.papersCookie; 10 | } 11 | 12 | async getMetadata(doi: string): Promise { 13 | const requestUrl = `https://services.readcube.com/reader/metadata?doi=${doi}`; 14 | const response = await fetch(requestUrl, { headers: { Cookie: this.papersCookie} }); 15 | if (response) { 16 | const resJson = await response.json(); 17 | if (resJson) { 18 | const metadata = new PaperMetadata(); 19 | metadata.references = []; 20 | if ('references' in resJson) { 21 | for (const ref of resJson['references']) { 22 | const paperRef = new PaperReference(); 23 | paperRef.title = 'title' in ref ? ref.title : ''; 24 | paperRef.ordinal = 'ordinal' in ref ? ref.ordinal : 1; 25 | paperRef.authors = 'authors' in ref ? ref.authors : []; 26 | paperRef.year = 'year' in ref ? ref.year : ''; 27 | paperRef.pagination = 'pagination' in ref ? ref.pagination : ''; 28 | paperRef.label = 'label' in ref ? ref.label : ''; 29 | paperRef.doi = 'doi' in ref ? ref.doi : ''; 30 | paperRef.article_url = 'article_url' in ref ? ref.article_url : ''; 31 | paperRef.reader_url = 'reader_url' in ref ? ref.reader_url : ''; 32 | paperRef.journal = 'journal' in ref ? ref.journal : ''; 33 | metadata.references.push(paperRef); 34 | } 35 | } 36 | 37 | metadata.figures = []; 38 | if ('figures' in resJson) { 39 | for (const figure of resJson['figures']) { 40 | const paperFigure = new PaperFigure(); 41 | paperFigure.url = 'url' in figure ? figure.url : ''; 42 | paperFigure.thumb = 'thumb' in figure ? figure.thumb : ''; 43 | paperFigure.download_url = 'download_url' in figure ? figure.download_url : ''; 44 | paperFigure.caption = 'caption' in figure ? figure.caption : ''; 45 | metadata.figures.push(paperFigure); 46 | } 47 | } 48 | return metadata; 49 | } 50 | } 51 | return null; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/readcube/lib/base/paperNotify.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Children should make sure the callbacks are called when note changes 3 | */ 4 | import {PaperConfig} from "../../common"; 5 | 6 | export abstract class PaperNotify { 7 | onPaperChangeListeners; 8 | settings: PaperConfig; 9 | 10 | protected constructor(config: PaperConfig) { 11 | this.settings = config; 12 | this.onPaperChangeListeners = []; 13 | } 14 | 15 | async onPaperChange(callback) { 16 | this.onPaperChangeListeners.push(callback); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/readcube/lib/base/paperSvc.ts: -------------------------------------------------------------------------------- 1 | import {AnnotationItem, PaperItem, PaperMetadata} from "./paperType"; 2 | import {PaperConfig} from "../../common"; 3 | 4 | export abstract class PaperSvc { 5 | /** 6 | * Return all papers 7 | */ 8 | async getAllItems(): Promise { 9 | return []; 10 | } 11 | 12 | /** 13 | * Return all annotations of given paper 14 | * @param paperItem 15 | */ 16 | async getAnnotation(paperItem: PaperItem): Promise { 17 | return []; 18 | } 19 | 20 | async init(settings: PaperConfig): Promise { } 21 | 22 | async extractNotes(paperItem: PaperItem): Promise { 23 | console.log("PaperSvc: Extracting notes"); 24 | return []; 25 | } 26 | 27 | externalLink(paperItem: PaperItem): String { 28 | return null; 29 | } 30 | 31 | externalAnnotationLink(anno: AnnotationItem): String { 32 | return null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/readcube/lib/base/paperType.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * API utils for Readcube PapersLib. All the apis are analyzed from the web application. 3 | */ 4 | 5 | 6 | export class PaperReference { 7 | title: string; 8 | ordinal: number; 9 | authors: string[]; 10 | year: string; 11 | pagination: string; 12 | label: string; 13 | doi: string; 14 | article_url: string; 15 | journal: string; 16 | reader_url: string; 17 | } 18 | 19 | export class PaperFigure { 20 | url: string; 21 | thumb: string; 22 | download_url: string; 23 | caption: string; 24 | } 25 | 26 | export class PaperMetadata { 27 | references: PaperReference[]; 28 | figures: PaperFigure[]; 29 | } 30 | 31 | export class PaperItem { 32 | title: string; 33 | journal: string; 34 | authors: string[]; 35 | tags: string[]; 36 | rating: number; 37 | abstract: string; 38 | collection_id: string; 39 | year: number; 40 | id: string; 41 | notes: string; 42 | annotations: []; 43 | issn: string; 44 | volume: string; 45 | url: string; 46 | pagination: string; 47 | journal_abbrev: string; 48 | doi: string; 49 | 50 | // zotero can have multiple notes for each paper 51 | zoteroNotes: string[]; 52 | } 53 | 54 | export type CollectionItem = { 55 | id: string; 56 | } 57 | export type AnnotationItem = { 58 | id: string; 59 | type: string; 60 | text: string; 61 | note: string; 62 | color_id: number; 63 | page: number; 64 | item_id: string; // collection_id:paper_id 65 | user_name: string; 66 | modified: string; 67 | color: string; // if color_id < 0, color is used instead 68 | } 69 | -------------------------------------------------------------------------------- /src/readcube/lib/zotero/zoteroWS.ts: -------------------------------------------------------------------------------- 1 | import {PaperNotify} from "../base/paperNotify"; 2 | import ReconnectingWebSocket from "reconnecting-websocket"; 3 | import {PaperConfig} from "../../common"; 4 | import paperSvc from "../PaperSvcFactory"; 5 | import {createRecord, deleteRecord, getRecord, removeInvalidSourceUrlByItemId, updateRecord} from "../base/paperDB"; 6 | import {ZoteroPaperSvc} from "./zoteroPaperSvc"; 7 | 8 | const options = { 9 | WebSocket: WebSocket, // custom WebSocket constructor 10 | connectionTimeout: 30000, 11 | maxReconnectInterval: 5000 12 | }; 13 | 14 | export class ZoteroWS extends PaperNotify { 15 | ws: ReconnectingWebSocket; 16 | papers: ZoteroPaperSvc; 17 | firstBoot = true; 18 | 19 | constructor(config: PaperConfig) { 20 | super(config); 21 | this.ws = new ReconnectingWebSocket('wss://stream.zotero.org', [], options); 22 | this.ws.onopen = this.onOpen.bind(this); 23 | this.ws.onmessage = this.onMessage.bind(this); 24 | this.ws.onclose = this.onClose.bind(this); 25 | this.ws.onerror = this.onError.bind(this); 26 | } 27 | 28 | /** 29 | * Not sure why we need to repeat the subscription. Just do the same as observed in the webapp. 30 | * @param collectionId 31 | */ 32 | sendSubscribe(): void { 33 | this.ws.send(`{ 34 | "action": "createSubscriptions", 35 | "subscriptions": [ 36 | { 37 | "apiKey": "${this.settings.zoteroApiKey}", 38 | "topics": [ 39 | "/users/${this.settings.zoteroUserId}" 40 | ] 41 | } 42 | ] 43 | }`); 44 | } 45 | 46 | async onOpen() { 47 | if (this.settings.zoteroApiKey.length === 0) { 48 | alert('Empty cookie for Papers. Please set it in the preferences.'); 49 | return; 50 | } 51 | 52 | this.papers = paperSvc.getSvc(); 53 | this.sendSubscribe(); 54 | } 55 | 56 | async onMessage(event: any) { 57 | const messages = JSON.parse(event.data); 58 | console.log('PapersWebSocket: Receive ', event.data); 59 | if (!['topicUpdated', 'topicAdded', 'topicRemoved'].includes(messages.event)) { 60 | return; 61 | } 62 | 63 | const oldItemIds = new Set(); 64 | for (const item of this.papers.cachedItems()) { 65 | oldItemIds.add(item.id); 66 | } 67 | 68 | this.papers.getAllItems().then(async (items) => { 69 | const newItemIds = new Set(); 70 | for (const item of items) { 71 | newItemIds.add(item.id); 72 | if (oldItemIds.has(item.id)) { 73 | await updateRecord(item.id, item); 74 | } else { 75 | await createRecord(item.id, item); 76 | } 77 | } 78 | 79 | for (const oldItemId of oldItemIds) { 80 | if (!newItemIds.has(oldItemId)) { 81 | await deleteRecord(oldItemId); 82 | await removeInvalidSourceUrlByItemId(oldItemId); 83 | } 84 | } 85 | 86 | // call the callback again because the paper list is changed 87 | for (const callback of this.onPaperChangeListeners) { 88 | callback(); 89 | } 90 | }) 91 | 92 | // call the callback immediately to update notes, tags, and other information as soon as possible 93 | for (const callback of this.onPaperChangeListeners) { 94 | callback(); 95 | } 96 | } 97 | 98 | onClose(event): void { 99 | console.log('PapersWebSocket: Connection Closed.'); 100 | } 101 | 102 | onError(): void { 103 | console.log('PapersWebSocket: Error happened'); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/readcube/settings.ts: -------------------------------------------------------------------------------- 1 | import joplin from "api"; 2 | import { SettingItemType } from "api/types"; 3 | import { 4 | ENABLE_CUSTOM_STYLE, 5 | ENABLE_ENHANCED_BLOCKQUOTE, 6 | PAPERS_COOKIE, PAPERS_CREATE_PAPER_NOTE_IN_CURRENT_FOLDER, PAPERS_SERVICE_PROVIDER, PaperServiceType, 7 | ZOTERO_USER_API_KEY, 8 | ZOTERO_USER_ID 9 | } from "./common"; 10 | 11 | export namespace settings { 12 | const SECTION = 'FeatureSettings'; 13 | 14 | export async function register() { 15 | await joplin.settings.registerSection(SECTION, { 16 | label: "Bundle Papers", 17 | iconName: "fa fa-graduation-cap", 18 | }); 19 | 20 | let PLUGIN_SETTINGS = {}; 21 | 22 | PLUGIN_SETTINGS[PAPERS_CREATE_PAPER_NOTE_IN_CURRENT_FOLDER] = { 23 | value: true, 24 | public: true, 25 | section: SECTION, 26 | type: SettingItemType.Bool, 27 | label: 'Create paper notes in current folder by default (Restart required)', 28 | } 29 | 30 | PLUGIN_SETTINGS[PAPERS_SERVICE_PROVIDER] = { 31 | value: 'Zotero', 32 | public: true, 33 | isEnum: true, 34 | options: { 35 | Readcube : 'ReadCube Papers', 36 | Zotero: 'Zotero' 37 | }, 38 | section: SECTION, 39 | type: SettingItemType.String, 40 | label: 'Your paper reference provider', 41 | description: "You MUST delete the papers.sqlite file after switching the provider. You can find it in the directory contains userchrome.css -> plugin-data -> com.septemberhx.pluginBundle", 42 | } 43 | 44 | PLUGIN_SETTINGS[PAPERS_COOKIE] = { 45 | value: '', 46 | public: true, 47 | section: SECTION, 48 | type: SettingItemType.String, 49 | label: 'Cookie for ReadCube Papers', 50 | description: "Visit ReadCube Papers web app in your web browser, open development tools and copy your cookies (requires restart)", 51 | } 52 | 53 | PLUGIN_SETTINGS[ENABLE_CUSTOM_STYLE] = { 54 | value: false, 55 | public: true, 56 | section: SECTION, 57 | type: SettingItemType.Bool, 58 | label: 'Enable Custom CSS style', 59 | description: "Header auto numbering, Times New Roman font family, and more (requires restart)", 60 | } 61 | 62 | PLUGIN_SETTINGS[ENABLE_ENHANCED_BLOCKQUOTE] = { 63 | value: false, 64 | public: true, 65 | section: SECTION, 66 | type: SettingItemType.Bool, 67 | label: 'Enable created user name, modified date, and more colors for annotations', 68 | description: "NEED Enhancement plugin. It can add [color=red][name=SeptemberHX][date=19700101] to the annotation references", 69 | } 70 | 71 | PLUGIN_SETTINGS[ZOTERO_USER_ID] = { 72 | value: 0, 73 | public: true, 74 | section: SECTION, 75 | type: SettingItemType.Int, 76 | label: 'Zotero User Id', 77 | description: 'Get your user id from https://www.zotero.org/settings/keys' 78 | } 79 | 80 | PLUGIN_SETTINGS[ZOTERO_USER_API_KEY] = { 81 | value: '', 82 | public: true, 83 | section: SECTION, 84 | type: SettingItemType.String, 85 | label: 'Zotero User API Key', 86 | description: 'Get your API Key from https://www.zotero.org/settings/keys. PLEASE create separate keys for different Joplin clients. Otherwise the information may not be updated in time due to the subscription limitation of each API key' 87 | } 88 | 89 | await joplin.settings.registerSettings(PLUGIN_SETTINGS); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/readcube/ui/citation-popup/index.ts: -------------------------------------------------------------------------------- 1 | import joplin from "api"; 2 | import {CITATION_POPUP_ID} from "../../common"; 3 | import {AnnotationItem, PaperItem} from "../../lib/base/paperType"; 4 | const fs = joplin.require("fs-extra"); 5 | 6 | let popupHandle: string = ""; 7 | 8 | 9 | export async function selectAnnotationPopup(refs: AnnotationItem[]): Promise { 10 | let fakePaperItems = []; 11 | for (let annotation of refs) { 12 | let item = new PaperItem(); 13 | item.id = annotation.id; 14 | item.title = annotation.text ? annotation.text : ""; 15 | item.authors = annotation.note ? [annotation.note] : [""]; 16 | item.journal = annotation.type; 17 | item.year = annotation.page; 18 | fakePaperItems.push(item); 19 | } 20 | return await selectPapersPopup(fakePaperItems); 21 | } 22 | 23 | 24 | /** 25 | * Show a dialog for the user to choose from a list of references 26 | * to be inserted in the note content 27 | * @returns ID of the selected reference 28 | */ 29 | export async function selectPapersPopup(refs: PaperItem[]): Promise { 30 | // If the dialog was not initialized, create it and get its handle 31 | if (popupHandle === "") { 32 | popupHandle = await joplin.views.dialogs.create(CITATION_POPUP_ID); 33 | } 34 | 35 | await loadAssets(refs); 36 | const result = await joplin.views.dialogs.open(popupHandle); 37 | 38 | if (result.id === "cancel") return []; 39 | 40 | let selectedRefsIDs: string[] = JSON.parse( 41 | result.formData["main"]["output"] 42 | ); 43 | 44 | /* Return an array of selected references' IDS */ 45 | return selectedRefsIDs; 46 | } 47 | 48 | async function loadAssets(refs: PaperItem[]): Promise { 49 | const installationDir = await joplin.plugins.installationDir(); 50 | let html: string = await fs.readFile( 51 | installationDir + "/readcube/ui/citation-popup/view.html", 52 | "utf8" 53 | ); 54 | html = html.replace("", fromRefsToHTML(refs)); 55 | 56 | await joplin.views.dialogs.setHtml(popupHandle, html); 57 | await joplin.views.dialogs.addScript( 58 | popupHandle, 59 | "./readcube/ui/citation-popup/lib/autoComplete.min.css" 60 | ); 61 | await joplin.views.dialogs.addScript( 62 | popupHandle, 63 | "./readcube/ui/citation-popup/lib/autoComplete.min.js" 64 | ); 65 | await joplin.views.dialogs.addScript( 66 | popupHandle, 67 | "./readcube/ui/citation-popup/lib/he.min.js" 68 | ); 69 | await joplin.views.dialogs.addScript( 70 | popupHandle, 71 | "./readcube/ui/citation-popup/view.css" 72 | ); 73 | await joplin.views.dialogs.addScript( 74 | popupHandle, 75 | "./readcube/ui/citation-popup/view.js" 76 | ); 77 | } 78 | 79 | function fromRefsToHTML(refs: PaperItem[]): string { 80 | const JSONString = JSON.stringify( 81 | refs.map((ref) => { 82 | return { 83 | id: ref.id, 84 | title: ref.title, 85 | author: ref.authors, 86 | year: ref.year, 87 | from: ref.journal, 88 | }; 89 | }) 90 | ); 91 | const ans: string = ` 92 | 95 | `; 96 | return ans; 97 | } 98 | -------------------------------------------------------------------------------- /src/readcube/ui/citation-popup/lib/autoComplete.min.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Minified by jsDelivr using clean-css v4.2.3. 3 | * Original file: /npm/@tarekraafat/autocomplete.js@10.1.5/dist/css/autoComplete.02.css 4 | * 5 | * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files 6 | */ 7 | .autoComplete_wrapper { 8 | display: inline-block; 9 | position: relative; 10 | } 11 | .autoComplete_wrapper > input { 12 | width: 600px; 13 | height: 40px; 14 | padding-left: 10px; 15 | font-size: 1rem; 16 | color: #747474; 17 | border-radius: 4px; 18 | border: 1px solid rgba(33, 33, 33, 0.2); 19 | outline: 0; 20 | } 21 | .autoComplete_wrapper > input::placeholder { 22 | color: rgba(123, 123, 123, 0.5); 23 | transition: all 0.3s ease; 24 | } 25 | .autoComplete_wrapper > ul { 26 | position: absolute; 27 | max-height: 377px; 28 | overflow-y: scroll; 29 | top: 100%; 30 | left: 0; 31 | right: 0; 32 | padding: 0; 33 | margin: 0.5rem 0 0 0; 34 | border-radius: 4px; 35 | background-color: #fff; 36 | border: 1px solid rgba(33, 33, 33, 0.1); 37 | z-index: 1000; 38 | outline: 0; 39 | } 40 | .autoComplete_wrapper > ul > li { 41 | padding: 10px 20px; 42 | list-style: none; 43 | text-align: left; 44 | font-size: 16px; 45 | color: #212121; 46 | transition: all 0.1s ease-in-out; 47 | border-radius: 3px; 48 | background-color: #fff; 49 | white-space: nowrap; 50 | overflow: hidden; 51 | text-overflow: ellipsis; 52 | transition: all 0.2s ease; 53 | } 54 | .autoComplete_wrapper > ul > li::selection { 55 | color: rgba(#fff, 0); 56 | background-color: rgba(#fff, 0); 57 | } 58 | .autoComplete_wrapper > ul > li:hover { 59 | cursor: pointer; 60 | background-color: rgba(123, 123, 123, 0.1); 61 | } 62 | .autoComplete_wrapper > ul > li mark { 63 | background-color: transparent; 64 | color: #ff7a7a; 65 | font-weight: 700; 66 | } 67 | .autoComplete_wrapper > ul > li mark::selection { 68 | color: rgba(#fff, 0); 69 | background-color: rgba(#fff, 0); 70 | } 71 | .autoComplete_wrapper > ul > li[aria-selected="true"] { 72 | background-color: rgba(123, 123, 123, 0.1); 73 | } 74 | @media only screen and (max-width: 600px) { 75 | .autoComplete_wrapper > input { 76 | width: 18rem; 77 | } 78 | } 79 | /*# sourceMappingURL=/sm/38debd88dbaf12078724075dd58d53e5259e5e982a7072de58f4a96dab354ff8.map */ 80 | -------------------------------------------------------------------------------- /src/readcube/ui/citation-popup/view.css: -------------------------------------------------------------------------------- 1 | * { 2 | overflow-wrap: break-word; 3 | box-sizing: border-box; 4 | } 5 | 6 | #joplin-plugin-content { 7 | width: 900px; 8 | } 9 | 10 | main { 11 | height: 100%; 12 | width: 100%; 13 | padding: 30px; 14 | text-align: center; 15 | } 16 | 17 | #selected_refs_list { 18 | height: 400px; 19 | width: 100%; 20 | font-size: 18px; 21 | margin-top: 30px; 22 | padding: 15px; 23 | list-style: none; 24 | text-align: left; 25 | overflow-y: auto; 26 | } 27 | 28 | #selected_refs_list li { 29 | padding: 10px 0; 30 | padding-right: 100px; 31 | position: relative; 32 | width: 100%; 33 | } 34 | 35 | #selected_refs_list .icon_remove { 36 | position: absolute; 37 | right: 0; 38 | top: 50%; 39 | transform: translateY(-50%); 40 | color: orangered; 41 | cursor: pointer; 42 | width: 30px; 43 | height: 30px; 44 | line-height: 30px; 45 | text-align: center; 46 | user-select: none; 47 | } 48 | #selected_refs_list .icon_remove:hover { 49 | background-color: rgba(0, 0, 0, 0.2); 50 | } 51 | -------------------------------------------------------------------------------- /src/readcube/ui/citation-popup/view.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 15 | 16 |
    17 | Select some items to continue 18 | 26 |
27 |
28 | 29 | 30 |
31 | 32 |
33 | -------------------------------------------------------------------------------- /src/readcube/utils/click-and-clear.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @ignore 3 | * BEGIN HEADER 4 | * 5 | * Contains: clickAndClear 6 | * CVM-Role: Utility function 7 | * Maintainer: Hendrik Erz 8 | * License: GNU GPL v3 9 | * 10 | * Description: A small helper function that is intended to be used with 11 | * CodeMirror rendering plugins. 12 | * 13 | * END HEADER 14 | */ 15 | 16 | import CodeMirror, { TextMarker } from 'codemirror' 17 | 18 | /** 19 | * Returns a callback that performs a "click and clear" operation on a rendered 20 | * textmarker, i.e. remove the marker and place the cursor precisely where the 21 | * user clicked 22 | * 23 | * @param {TextMarker} marker The text marker 24 | * @param {CodeMirror} cm The CodeMirror instance 25 | * 26 | * @return {Function} The callback 27 | */ 28 | export default function clickAndClear ( 29 | marker: TextMarker, 30 | cm: CodeMirror.Editor 31 | ): (e: MouseEvent) => void { 32 | return (e: MouseEvent) => { 33 | marker.clear() 34 | cm.setCursor(cm.coordsChar({ left: e.clientX, top: e.clientY })) 35 | cm.focus() 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/readcube/utils/cm-utils.ts: -------------------------------------------------------------------------------- 1 | import {Editor, Position} from "codemirror"; 2 | 3 | export function isRangeSelected(from: Position, to: Position, cm: Editor): boolean { 4 | let selected = false; 5 | for (let selection of cm.getDoc().listSelections()) { 6 | if (from.line < selection.from().line || (from.line === selection.from().line && from.ch < selection.from().ch) 7 | || to.line > selection.to().line || (to.line === selection.to().line && to.ch > selection.to().ch)) { 8 | ; 9 | } else { 10 | selected = true; 11 | break; 12 | } 13 | } 14 | return selected; 15 | } 16 | 17 | export function isCursorOutRange(cursorPos: Position, from: Position, to: Position) { 18 | return cursorPos.line < from.line || cursorPos.line > to.line 19 | || (cursorPos.line === from.line && cursorPos.ch < from.ch) 20 | || (cursorPos.line === to.line && cursorPos.ch > to.ch); 21 | } 22 | 23 | export function findLineWidgetAtLine(editor: Editor, lineNumber: number, className: string) { 24 | // check whether there exists rendered line widget 25 | const line = editor.lineInfo(lineNumber); 26 | if (line.widgets) { 27 | for (const wid of line.widgets) { 28 | if (wid.className === className) { 29 | return wid; 30 | } 31 | } 32 | } 33 | return null; 34 | } 35 | -------------------------------------------------------------------------------- /src/readcube/utils/paperCardGenerator.ts: -------------------------------------------------------------------------------- 1 | import {PaperItem} from "../lib/base/paperType"; 2 | 3 | export const colorMap = { 4 | 1: '#ffd638', 5 | 2: '#94ed96', 6 | 3: '#feb6c1', 7 | 4: '#dba1da', 8 | 5: '#fe0013', 9 | 6: '#001df8', 10 | 7: '#000000', 11 | 8: '#137f1a', 12 | 9: '#7e087d', 13 | 10: '#ffa42c' 14 | }; 15 | 16 | 17 | export function buildPaperCard(item: PaperItem, options) { 18 | if (item) { 19 | let stars = '☆☆☆☆☆'; 20 | switch (item.rating) { 21 | case 1: 22 | stars = '★☆☆☆☆'; 23 | break; 24 | case 2: 25 | stars = '★★☆☆☆'; 26 | break; 27 | case 3: 28 | stars = '★★★☆☆'; 29 | break; 30 | case 4: 31 | stars = '★★★★☆'; 32 | break; 33 | case 5: 34 | stars = '★★★★★'; 35 | break; 36 | default: 37 | break; 38 | } 39 | 40 | return ` 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
${item.title}
${item.authors.join(', ')}
${item.journal}${item.year}${item.tags.length > 0 ? item.tags : 'No tags'}${stars}
${item.abstract}
User Notes:
${item.notes}
64 | ` 65 | } else { 66 | return `
Paper does not exist.
Please check your paper id.
` 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/readcube/utils/reg.ts: -------------------------------------------------------------------------------- 1 | export const PAPER_ID_REG = /id:\s*(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/; 2 | -------------------------------------------------------------------------------- /src/relatedNotes/settings.ts: -------------------------------------------------------------------------------- 1 | import joplin from "../../api"; 2 | import {SettingItemType} from "../../api/types"; 3 | import {RelatedNoteSettings} from "./types"; 4 | 5 | const RELATED_NOTE_COLLAPSED_BY_DEFAULT = 'related_note_collapsed_by_default'; 6 | 7 | 8 | export namespace settings { 9 | const SECTION = 'RelatedNoteTodoSettings'; 10 | 11 | export async function register() { 12 | await joplin.settings.registerSection(SECTION, { 13 | label: "Bundle Related Notes", 14 | iconName: "fas fa-yin-yang", 15 | }); 16 | 17 | let PLUGIN_SETTINGS = {}; 18 | 19 | PLUGIN_SETTINGS[RELATED_NOTE_COLLAPSED_BY_DEFAULT] = { 20 | value: true, 21 | public: true, 22 | section: SECTION, 23 | type: SettingItemType.Bool, 24 | label: 'Show collapsed related notes by default', 25 | }; 26 | 27 | await joplin.settings.registerSettings(PLUGIN_SETTINGS); 28 | } 29 | 30 | export async function getSettings() { 31 | const settings = new RelatedNoteSettings(); 32 | settings.collapsed = await joplin.settings.value(RELATED_NOTE_COLLAPSED_BY_DEFAULT); 33 | return settings; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/relatedNotes/types.ts: -------------------------------------------------------------------------------- 1 | export interface SidebarStatus { 2 | mentionFilter: true, 3 | mentionedFilter: true, 4 | bidirectionFilter: true, 5 | sortFilter: string, 6 | tabIndex: number, 7 | settings: RelatedNoteSettings, 8 | } 9 | 10 | 11 | export class RelatedNoteSettings { 12 | collapsed: boolean = true; 13 | } 14 | -------------------------------------------------------------------------------- /src/scripts/dailyNote/dailyNote.css: -------------------------------------------------------------------------------- 1 | table.dailynote-table { 2 | text-align: center; 3 | font-size: smaller; 4 | width: 100%; 5 | table-layout: fixed; 6 | border-spacing: 3px; 7 | border-collapse: unset; 8 | } 9 | 10 | table.dailynote-table td { 11 | height: 3em; 12 | } 13 | 14 | table.dailynote-table .day:hover { 15 | background-color: #ececec !important; 16 | } 17 | 18 | table.dailynote-table .day { 19 | border-radius: 4px; 20 | } 21 | 22 | table.dailynote-table .curr-day { 23 | background-color: khaki !important; 24 | color: dimgrey; 25 | } 26 | 27 | table.dailynote-table div.dot-container { 28 | display: inline-flex; 29 | } 30 | 31 | table.dailynote-table div.noNote div.dot-container { 32 | visibility: hidden; 33 | } 34 | 35 | table.dailynote-table svg.dot { 36 | height: 0.6em; 37 | } 38 | 39 | table.dailynote-table svg.dot.filled.level-1 { 40 | fill: yellowgreen; 41 | } 42 | 43 | table.dailynote-table svg.dot.filled.level-5 { 44 | fill: red; 45 | } 46 | 47 | table.dailynote-table td.prev-month, 48 | table.dailynote-table td.next-month { 49 | color: lightgray; 50 | } 51 | 52 | table.dailynote-table thead { 53 | font-weight: bold; 54 | } 55 | 56 | button.btn.btn-current { 57 | font-size: small; 58 | } 59 | 60 | div.month-container { 61 | padding: 5px 10px; 62 | vertical-align: middle; 63 | width: 100%; 64 | } 65 | 66 | button.button-current { 67 | width: 50%; 68 | color: cornflowerblue; 69 | vertical-align: middle; 70 | font-weight: bold; 71 | } 72 | 73 | button.btn.button-next, 74 | button.btn.button-previous { 75 | color: cornflowerblue; 76 | font-weight: bold; 77 | } 78 | -------------------------------------------------------------------------------- /src/scripts/dailyNote/dailyNote.js: -------------------------------------------------------------------------------- 1 | function calendarCellClicked(dateStr) { 2 | webviewApi.postMessage({ 3 | name: 'sidebar_dailynote_day_clicked', 4 | id: dateStr 5 | }) 6 | } 7 | 8 | function showCalendarFor(year, month) { 9 | webviewApi.postMessage({ 10 | name: 'sidebar_dailynote_show_calendar_for', 11 | id: { 12 | year: year, 13 | month: month 14 | } 15 | }) 16 | } 17 | -------------------------------------------------------------------------------- /src/scripts/dailyNote/dialog.css: -------------------------------------------------------------------------------- 1 | div#joplin-plugin-content { 2 | font-size: initial; 3 | text-align: left; 4 | width: 400px; 5 | } 6 | -------------------------------------------------------------------------------- /src/scripts/history/history.css: -------------------------------------------------------------------------------- 1 | div.history-container { 2 | overflow: auto; 3 | text-overflow: clip; 4 | background-color: var(--joplin-background-color); 5 | color: var(--joplin-color); 6 | } 7 | 8 | div.history-container .hist-title { 9 | color: var(--joplin-color); 10 | font-weight: bold; 11 | text-decoration: none; 12 | margin: 5px; 13 | } 14 | 15 | div.history-container .hist-section { 16 | margin: 5px; 17 | } 18 | 19 | div.history-container .hist-item { 20 | vertical-align: top; 21 | text-overflow: clip; 22 | overflow-x: hidden; 23 | overflow-y: hidden; 24 | white-space: nowrap; 25 | } 26 | 27 | div.history-container .hist-item a { 28 | color: var(--joplin-color); 29 | text-decoration: none; 30 | } 31 | 32 | div.history-container .hist-item a:active, a:hover { 33 | font-weight: bold; 34 | } 35 | 36 | div.history-container .hist-loader { 37 | text-align: center; 38 | margin: 0px; 39 | text-overflow: clip; 40 | overflow-x: hidden; 41 | overflow-y: hidden; 42 | white-space: nowrap; 43 | } 44 | 45 | div.history-container .hist-loader a { 46 | color: var(--joplin-color); 47 | text-decoration: none; 48 | } 49 | 50 | div.history-container .hist-loader a:active, a:hover { 51 | font-weight: bold; 52 | } 53 | 54 | div.history-container .hist-plot { 55 | vertical-align: top; 56 | stroke-width: 0.1; 57 | } 58 | 59 | div.history-container ::-webkit-scrollbar { 60 | width: 7px; 61 | height: 7px; 62 | } 63 | 64 | div.history-container ::-webkit-scrollbar-corner { 65 | background: none; 66 | } 67 | 68 | div.history-container ::-webkit-scrollbar-track { 69 | border: none; 70 | } 71 | 72 | div.history-container ::-webkit-scrollbar-thumb { 73 | background: rgba(100, 100, 100, 0.3); 74 | border-radius: 5px; 75 | } 76 | 77 | div.history-container ::-webkit-scrollbar-track:hover { 78 | background: rgba(0, 0, 0, 0.1); 79 | } 80 | 81 | div.history-container ::-webkit-scrollbar-thumb:hover { 82 | background: rgba(100, 100, 100, 0.7); 83 | } 84 | 85 | div.history-container .hist-item strong a { 86 | color: var(--bs-accordion-active-color); 87 | } 88 | 89 | div.history-container button.accordion-button { 90 | font-weight: bold; 91 | } 92 | -------------------------------------------------------------------------------- /src/scripts/history/history.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('click', event => { 2 | const element = event.target; 3 | if ((element.className === 'hist-item') || (element.className === 'hist-title')) { 4 | // Post the message and slug info back to the plugin: 5 | webviewApi.postMessage({ 6 | name: 'openHistory', 7 | hash: element.dataset.slug, 8 | line: element.dataset.line, 9 | }); 10 | } 11 | if (element.className === 'hist-loader') { 12 | webviewApi.postMessage({ 13 | name: 'loadHistory', 14 | }) 15 | } 16 | }); 17 | -------------------------------------------------------------------------------- /src/scripts/inlineTodo/inlineTodo.css: -------------------------------------------------------------------------------- 1 | .inline-todo-div { 2 | font-size: 0.9em; 3 | word-break: break-all; 4 | } 5 | 6 | .inline-todo-div.badge.rounded-pill { 7 | vertical-align: middle; 8 | } 9 | 10 | .inline-todo-div .form-check-label:hover { 11 | cursor: pointer; 12 | } 13 | 14 | .inline-todo-div p { 15 | display: inline !important; 16 | } 17 | 18 | .inline-todo-div .form-check-label a { 19 | pointer-events: none; 20 | } 21 | 22 | .inline-todo-div div.task-infos { 23 | display: flex; 24 | float: right; 25 | } 26 | 27 | .inline-todo-div div.task-tags { 28 | display: inline; 29 | } 30 | 31 | .inline-todo-div span.badge.rounded-pill { 32 | opacity: 0.75; 33 | } 34 | 35 | .inline-todo-div ul#pills-tab { 36 | padding-top: 1em; 37 | } 38 | 39 | i.fas.no-task-icon { 40 | font-size: 500%; 41 | opacity: 0.3; 42 | margin-top: 1em; 43 | margin-bottom: 30px; 44 | display: block; 45 | } 46 | 47 | p.no-task-text { 48 | font-style: italic; 49 | opacity: 0.5; 50 | } 51 | 52 | div.no-task-cheer { 53 | text-align: center; 54 | } 55 | 56 | div.inline-todo-div li.nav-item { 57 | margin-left: 0.65em; 58 | margin-right: 0.65em; 59 | } 60 | 61 | div.inline-todo-div li.list-group-item.priority-4 { 62 | border-left: 5px solid transparent; 63 | } 64 | 65 | div.inline-todo-div li.list-group-item.priority-3 { 66 | border-left: 5px solid #549644; 67 | } 68 | 69 | div.inline-todo-div li.list-group-item.priority-2 { 70 | border-left: 5px solid #f8d15f; 71 | } 72 | 73 | div.inline-todo-div li.list-group-item.priority-1 { 74 | border-left: 5px solid #e33e2f; 75 | } 76 | 77 | div.inline-todo-div span.badge.bg-primary, 78 | div.inline-todo-div span.badge.rounded-pill.bg-info, 79 | div.inline-todo-div span.badge.assignee { 80 | opacity: 0.75; 81 | } 82 | 83 | div.inline-todo-div .accordion-body { 84 | padding: 0; 85 | } 86 | 87 | div.inline-todo-div #accordionExpiredTask button.accordion-button { 88 | color: crimson; 89 | font-weight: bold; 90 | } 91 | 92 | div.inline-todo-div button.accordion-button { 93 | font-weight: bold; 94 | } 95 | 96 | div.inline-todo-div span.badge.assignee { 97 | background: coral; 98 | } 99 | 100 | div#taskSelectorsDiv { 101 | text-align: center; 102 | margin-bottom: 4px; 103 | } 104 | 105 | select#assignee-selector, 106 | select#tag-selector, 107 | select#due-selector { 108 | width: 30%; 109 | margin: 0 2px; 110 | display: inline; 111 | font-size: smaller; 112 | } 113 | 114 | div.inline-todo-div div.search-input { 115 | padding-left: 0.5em; 116 | padding-right: 0.5em; 117 | } 118 | 119 | div.inline-todo-div div.task-description { 120 | font-size: small; 121 | opacity: 0.8; 122 | margin-left: 1em; 123 | margin-top: 0.3em; 124 | } 125 | -------------------------------------------------------------------------------- /src/scripts/inlineTodo/inlineTodo.js: -------------------------------------------------------------------------------- 1 | function todoItemClicked(id) { 2 | webviewApi.postMessage({ 3 | name: 'sidebar_todo_item_clicked', 4 | id: id 5 | }); 6 | } 7 | 8 | function todoItemChanged(id, checked) { 9 | if (checked) { 10 | webviewApi.postMessage({ 11 | name: 'sidebar_todo_item_checked', 12 | id: id 13 | }) 14 | } 15 | } 16 | 17 | function todoTypeTabItemClicked(id) { 18 | webviewApi.postMessage({ 19 | name: 'sidebar_todo_type_tab_item_clicked', 20 | id: id 21 | }); 22 | } 23 | 24 | function onFilterProjectChanged() { 25 | var x = document.getElementById("assignee-selector").value; 26 | webviewApi.postMessage({ 27 | name: 'sidebar_todo_filter_project_changed', 28 | id: x 29 | }); 30 | } 31 | 32 | function onFilterTagChanged() { 33 | var x = document.getElementById("tag-selector").value; 34 | webviewApi.postMessage({ 35 | name: 'sidebar_todo_filter_tag_changed', 36 | id: x 37 | }); 38 | } 39 | 40 | function onFilterDueChanged() { 41 | var x = document.getElementById("due-selector").value; 42 | webviewApi.postMessage({ 43 | name: 'sidebar_todo_filter_due_changed', 44 | id: x 45 | }); 46 | } 47 | 48 | function onSearchChanged() { 49 | if (event.keyCode === 13) { 50 | webviewApi.postMessage({ 51 | name: 'sidebar_todo_search_changed', 52 | id: event.target.value ? event.target.value : '' 53 | }); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/scripts/outline/webview.css: -------------------------------------------------------------------------------- 1 | .outline-content { 2 | /*min-height: calc(100vh - 3em);*/ 3 | padding: 5px 4 | } 5 | 6 | .outline-content .toc-item-link { 7 | padding: 0 2px; 8 | text-decoration: none; 9 | } 10 | 11 | .outline-content .toc-item-link:hover { 12 | font-weight: bold; 13 | } 14 | 15 | .outline-content { 16 | font-family: var(--joplin-font-family); 17 | background-color: var(--joplin-background-color); 18 | margin: 10px 0 0 0; 19 | } 20 | 21 | .outline-content .toc-item-link { 22 | padding: 5px; 23 | font-weight: normal; 24 | text-decoration: none; 25 | line-height: 1.3em; 26 | color: var(--joplin-color); 27 | font-size: 0.9em; 28 | } 29 | 30 | .outline-content .toc-item-link:hover { 31 | background-color: var(--joplin-selected-color); 32 | border-radius: 4px; 33 | } 34 | 35 | i.fas.fa-scroll.no-toc-warn-icon { 36 | font-size: 500%; 37 | opacity: 0.3; 38 | margin-top: 1em; 39 | margin-bottom: 30px; 40 | } 41 | 42 | p.no-toc-warn-text { 43 | font-style: italic; 44 | opacity: 0.5; 45 | } 46 | 47 | div.no-toc-warn { 48 | text-align: center; 49 | } 50 | 51 | .outline-content .toc-item-link.current-header { 52 | color: var(--joplin-url-color); 53 | font-weight: bold; 54 | } 55 | -------------------------------------------------------------------------------- /src/scripts/outline/webview.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | /* eslint-disable no-unused-vars */ 3 | 4 | function tocItemLinkClicked(dataset) { 5 | webviewApi.postMessage({ 6 | name: 'scrollToHeader', 7 | lineno: dataset.lineno, 8 | hash: dataset.slug, 9 | }); 10 | } 11 | 12 | function copyInnerLink(dataset, text) { 13 | webviewApi.postMessage({ 14 | name: 'contextMenu', 15 | hash: dataset.slug, 16 | content: text, 17 | }); 18 | 19 | document.getElementById('header').innerHTML = 'Copy successful!'; 20 | setTimeout(() => { 21 | document.getElementById('header').innerHTML = 'Outline'; 22 | }, 800); 23 | } 24 | 25 | function scrollToTop() { 26 | webviewApi.postMessage({ 27 | name: 'scrollToHeader', 28 | lineno: 1, 29 | hash: 'rendered-md', 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /src/scripts/readcube/popup.css: -------------------------------------------------------------------------------- 1 | div#joplin-plugin-content { 2 | font-size: initial; 3 | text-align: left; 4 | width: 400px; 5 | } 6 | -------------------------------------------------------------------------------- /src/scripts/readcube/readcube.css: -------------------------------------------------------------------------------- 1 | .readcube-paper-div div.journal { 2 | font-size: smaller; 3 | padding: 3px 0; 4 | font-style: italic; 5 | font-family: Times New Roman; 6 | } 7 | 8 | .readcube-paper-div div.journal.with-url { 9 | text-decoration: underline; 10 | cursor: pointer; 11 | } 12 | 13 | .readcube-paper-div div.title { 14 | font-weight: bold; 15 | font-size: smaller; 16 | padding: 3px 0; 17 | color: var(--joplin-url-color); 18 | cursor: pointer; 19 | word-wrap: break-word; 20 | word-break: break-word; 21 | hyphens: auto; 22 | } 23 | 24 | .readcube-paper-div div.authors { 25 | padding: 3px 0; 26 | } 27 | 28 | .readcube-paper-div div.tags { 29 | padding: 3px 0; 30 | } 31 | 32 | .readcube-paper-div div.rate { 33 | padding: 3px 0; 34 | } 35 | 36 | .readcube-paper-div div.abstract { 37 | font-family: Times New Roman; 38 | font-size: 0.9em; 39 | padding: 3px 0; 40 | text-overflow: ellipsis; 41 | overflow: hidden; 42 | display: -webkit-box; 43 | -webkit-box-orient: vertical; 44 | -webkit-line-clamp: 15; 45 | word-wrap: break-word; 46 | word-break: break-word; 47 | hyphens: auto; 48 | } 49 | 50 | .readcube-paper-div ul#pills-paper-tab { 51 | padding-top: 0.5em; 52 | } 53 | 54 | .readcube-paper-div li.nav-item { 55 | margin-left: 1em; 56 | margin-right: 1em; 57 | } 58 | 59 | div#pills-paper-info { 60 | margin-left: 5px; 61 | margin-right: 5px; 62 | } 63 | 64 | .readcube-paper-div div.authors span.badge.text-bg-light { 65 | margin-right: 5px; 66 | } 67 | 68 | .readcube-paper-div div.tag-rate, 69 | .paper-list .paper-info-header, 70 | .paper-list .paper-info-author-tag { 71 | display: grid; 72 | justify-content: space-between; 73 | grid-template-columns: auto auto; 74 | } 75 | 76 | .readcube-paper-div div.non-paper-note { 77 | text-align: center; 78 | } 79 | 80 | .readcube-paper-div .non-paper-icon { 81 | font-size: 500%; 82 | opacity: 0.3; 83 | margin-top: 1em; 84 | margin-bottom: 30px; 85 | } 86 | 87 | .readcube-paper-div .non-paper-text { 88 | font-style: italic; 89 | opacity: 0.5; 90 | } 91 | 92 | .readcube-paper-div .notes { 93 | border: 1px solid var(--joplin-selected-color); 94 | border-radius: 4px; 95 | padding: 4px; 96 | font-size: small; 97 | margin-top: 0.8em; 98 | } 99 | 100 | .readcube-paper-div .user-note-label { 101 | text-align: center; 102 | font-weight: bold; 103 | background: var(--joplin-selected-color); 104 | margin: -4px -4px 4px; 105 | } 106 | 107 | .paper-annos li.list-group-item { 108 | font-size: small; 109 | } 110 | 111 | .paper-annos span.anno-page { 112 | opacity: 0.5; 113 | } 114 | 115 | .paper-annos .anno-part { 116 | margin: 4px 0; 117 | } 118 | 119 | .paper-annos span.anno-text { 120 | word-wrap: break-word; 121 | word-break: break-word; 122 | hyphens: auto; 123 | padding-left: 0.5em; 124 | display: inline-block; 125 | } 126 | 127 | .paper-annos .anno-info, 128 | .paper-refs-list .ref-info-header { 129 | display: grid; 130 | justify-content: space-between; 131 | grid-template-columns: auto auto auto; 132 | } 133 | 134 | .paper-annos i.fas { 135 | padding: 2px; 136 | } 137 | 138 | .paper-annos .anno-buttons, 139 | .paper-list .paper-info-buttons, 140 | .paper-refs-list .ref-info-buttons { 141 | opacity: 0; 142 | color: dimgray; 143 | transition: opacity 500ms; 144 | } 145 | 146 | .paper-list li.list-group-item { 147 | font-size: small; 148 | } 149 | 150 | span.paper-info-title { 151 | font-weight: bold; 152 | display: block; 153 | margin-bottom: 5px; 154 | } 155 | 156 | span.paper-info-journal-year { 157 | text-overflow: ellipsis; 158 | overflow: hidden; 159 | white-space: nowrap; 160 | margin-right: 10px; 161 | font-size: smaller; 162 | font-style: italic; 163 | } 164 | 165 | div.paper-annos div.search-input, 166 | div.paper-refs-list div.search-input { 167 | padding-left: 0.5em; 168 | padding-right: 0.5em; 169 | } 170 | 171 | div.readcube-paper-div p { 172 | margin-bottom: 0; 173 | } 174 | 175 | div.readcube-paper-div .paper-selector { 176 | margin: 0 20px; 177 | padding-top: 10px; 178 | } 179 | 180 | div.paper-refs-list .ref-info-header { 181 | margin-bottom: 5px; 182 | } 183 | 184 | .paper-refs-list li.list-group-item { 185 | font-size: small; 186 | } 187 | 188 | div.paper-refs-list .ref-info-title { 189 | display: block; 190 | font-weight: bold; 191 | word-wrap: break-word; 192 | word-break: break-word; 193 | hyphens: auto; 194 | } 195 | 196 | .paper-refs-list .ref-info-authors, 197 | .paper-refs-list .ref-info-journal { 198 | white-space: nowrap; 199 | text-overflow: ellipsis; 200 | overflow: hidden; 201 | display: block; 202 | color: gray; 203 | } 204 | 205 | .paper-refs-list .ref-info-journal { 206 | font-style: italic; 207 | } 208 | 209 | .paper-refs-list span.ref-info-ordinal { 210 | margin-left: -1em; 211 | } 212 | 213 | .paper-figures-list figure.paper-figure { 214 | margin-top: 0.5em; 215 | margin-bottom: 0; 216 | font-size: small; 217 | } 218 | 219 | .paper-figures-list img { 220 | max-width: 100%; 221 | margin-bottom: 0.5em; 222 | } 223 | 224 | .paper-figures-list figcaption { 225 | opacity: 0.75; 226 | } 227 | 228 | .paper-info .note { 229 | border-bottom: 1px solid lightgray; 230 | margin-top: 1em; 231 | padding-bottom: 1em; 232 | } 233 | 234 | ul.list-group.paper-list { 235 | border: transparent; 236 | } 237 | -------------------------------------------------------------------------------- /src/scripts/readcube/readcube.js: -------------------------------------------------------------------------------- 1 | function paperTabClicked(id) { 2 | webviewApi.postMessage({ 3 | name: 'sidebar_paper_tab_item_clicked', 4 | id: id 5 | }); 6 | } 7 | 8 | function annotationMouseOverAndOut(over) { 9 | if (event.target) { 10 | const buttonsEle = event.target.querySelector('.anno-buttons'); 11 | if (buttonsEle) { 12 | buttonsEle.style.opacity = over ? 1 : 0; 13 | } 14 | } 15 | } 16 | 17 | function paperItemMouseOverAndOut(over) { 18 | if (event.target) { 19 | const buttonsEle = event.target.querySelector('.paper-info-buttons'); 20 | if (buttonsEle) { 21 | buttonsEle.style.opacity = over ? 1 : 0; 22 | } 23 | } 24 | } 25 | 26 | function refItemMouseOverAndOut(over) { 27 | if (event.target) { 28 | const buttonsEle = event.target.querySelector('.ref-info-buttons'); 29 | if (buttonsEle) { 30 | buttonsEle.style.opacity = over ? 1 : 0; 31 | } 32 | } 33 | } 34 | 35 | function annotationExternalLinkClicked(annotation_link) { 36 | webviewApi.postMessage({ 37 | name: 'sidebar_open_item', 38 | id: annotation_link 39 | }); 40 | } 41 | 42 | function annotationCopyLinkClicked(annotation_id) { 43 | webviewApi.postMessage({ 44 | name: 'sidebar_annotation_copy_link_clicked', 45 | id: annotation_id 46 | }); 47 | } 48 | 49 | function annotationCopyClicked(annotation_id) { 50 | webviewApi.postMessage({ 51 | name: 'sidebar_annotation_copy_clicked', 52 | id: annotation_id 53 | }); 54 | } 55 | 56 | function annotationCiteClicked(annotation_id) { 57 | webviewApi.postMessage({ 58 | name: 'sidebar_annotation_cite_clicked', 59 | id: annotation_id 60 | }); 61 | } 62 | 63 | function onSearchPressed() { 64 | if (event.keyCode === 13) { 65 | webviewApi.postMessage({ 66 | name: 'sidebar_papers_anno_search_changed', 67 | id: event.target.value ? event.target.value : '' 68 | }); 69 | } 70 | } 71 | 72 | function onRefSearchPressed() { 73 | if (event.keyCode === 13) { 74 | webviewApi.postMessage({ 75 | name: 'sidebar_papers_ref_search_changed', 76 | id: event.target.value ? event.target.value : '' 77 | }); 78 | } 79 | } 80 | 81 | function onPaperTitleClicked(remote_url) { 82 | webviewApi.postMessage({ 83 | name: 'sidebar_open_item', 84 | id: remote_url 85 | }); 86 | } 87 | 88 | function onPaperFigureClicked() { 89 | if (event.target) { 90 | const img = event.target; 91 | if (img && img.width > 0 && img.height > 0) { 92 | var canvas = document.createElement("canvas"); 93 | canvas.width = img.naturalWidth; 94 | canvas.height = img.naturalHeight; 95 | var ctx = canvas.getContext("2d"); 96 | ctx.drawImage(img, 0, 0); 97 | var dataURL = canvas.toDataURL("image/png"); 98 | webviewApi.postMessage({ 99 | name: 'sidebar_copy_img_by_url', 100 | id: dataURL 101 | }); 102 | } 103 | } 104 | } 105 | 106 | function onPaperSelectorChanged() { 107 | var x = document.getElementById("paper-selector").value; 108 | webviewApi.postMessage({ 109 | name: 'sidebar_paper_selector_changed', 110 | id: x 111 | }); 112 | } 113 | -------------------------------------------------------------------------------- /src/scripts/relatedNotes/relatedNotes.css: -------------------------------------------------------------------------------- 1 | span.related-element-parent.badge.text-bg-light { 2 | text-overflow: ellipsis; 3 | overflow: hidden; 4 | } 5 | 6 | .related-notes-div .related-element-info { 7 | margin-top: 0.5em; 8 | opacity: 0.75; 9 | } 10 | 11 | .related-notes-div .related-element-info { 12 | margin-top: 0.5em; 13 | display: grid; 14 | justify-content: space-between; 15 | grid-template-columns: auto auto; 16 | } 17 | 18 | .related-notes-div span.related-element-title { 19 | font-weight: bold; 20 | color: var(--joplin-url-color); 21 | cursor: pointer; 22 | } 23 | 24 | .related-element-parent .fa-folder-open { 25 | margin-right: 0.25em; 26 | } 27 | 28 | .related-notes-div { 29 | font-size: 0.9em; 30 | } 31 | 32 | .related-notes-div .related-element-body { 33 | text-overflow: ellipsis; 34 | overflow: hidden; 35 | display: -webkit-box; 36 | -webkit-box-orient: vertical; 37 | -webkit-line-clamp: 5; 38 | word-wrap: break-word; 39 | word-break: break-word; 40 | hyphens: auto; 41 | font-size: smaller; 42 | opacity: 0.8; 43 | } 44 | 45 | .related-notes-div .related-element-title { 46 | display: grid; 47 | justify-content: space-between; 48 | grid-template-columns: auto auto; 49 | } 50 | 51 | .related-notes-div span.related-element-type { 52 | margin-left: 0.5em; 53 | opacity: 0.5; 54 | } 55 | 56 | .related-element-body { 57 | margin-left: 1em; 58 | } 59 | 60 | .related-element-body h1 { 61 | font-size: 1.5em; 62 | } 63 | 64 | .related-element-body h2 { 65 | font-size: 1.35em; 66 | } 67 | 68 | .related-element-body h3 { 69 | font-size: 1.3em; 70 | } 71 | 72 | .related-element-body h4 { 73 | font-size: 1.25em; 74 | } 75 | 76 | .related-element-body h5 { 77 | font-size: 1.2em; 78 | } 79 | 80 | .related-element-body h6 { 81 | font-size: 1.15em; 82 | } 83 | 84 | .relatedNoteList button.accordion-button { 85 | font-weight: bold; 86 | } 87 | 88 | .accordion-body.related-element-contexts { 89 | padding: 0.4em; 90 | } 91 | 92 | .relatedNoteList span.badge.rounded-pill.text-bg-secondary { 93 | font-size: xx-small; 94 | margin-left: -1em; 95 | margin-right: 0.5em; 96 | } 97 | 98 | .related-notes-div li.nav-item { 99 | margin-left: 1em; 100 | margin-right: 1em; 101 | } 102 | 103 | ul#pills-related-notes-tab { 104 | padding-top: 1em; 105 | padding-bottom: 1em; 106 | } 107 | 108 | #relatedNoteList2 .accordion-button:not(.collapsed), 109 | #relatedNoteList3 .accordion-button:not(.collapsed) { 110 | color: lightseagreen; 111 | } 112 | 113 | .related-notes-div .fa-folder-open { 114 | margin-right: 0.3em; 115 | } 116 | 117 | .related-notes-div span.badge.text-bg-primary.folder { 118 | margin-left: auto; 119 | opacity: 0.75; 120 | font-size: x-small; 121 | } 122 | 123 | .related-notes-div .accordion-button::after { 124 | margin-left: 0.5em; 125 | } 126 | -------------------------------------------------------------------------------- /src/scripts/relatedNotes/relatedNotes.js: -------------------------------------------------------------------------------- 1 | function onRelatedTitleClicked(noteId, line) { 2 | webviewApi.postMessage({ 3 | name: 'sidebar_related_notes_item_clicked', 4 | id: noteId, 5 | line: line 6 | }) 7 | } 8 | 9 | function onRelatedArrowClicked(noteId, lineR) { 10 | webviewApi.postMessage({ 11 | name: 'sidebar_related_notes_arrow_clicked', 12 | id: noteId, 13 | lineR: lineR 14 | }) 15 | } 16 | 17 | function relatedNoteTabClicked(id) { 18 | webviewApi.postMessage({ 19 | name: 'sidebar_related_note_item_tab_clicked', 20 | id: id 21 | }); 22 | } 23 | 24 | function jumpToNoteLine(noteId, lineNumber) { 25 | webviewApi.postMessage({ 26 | name: 'sidebar_related_note_context_clicked', 27 | id: noteId, 28 | line: lineNumber - 1 29 | }); 30 | } 31 | -------------------------------------------------------------------------------- /src/scripts/sidebars/custom.css: -------------------------------------------------------------------------------- 1 | html { 2 | overflow: auto; 3 | } 4 | 5 | #header { 6 | margin-top: 10px; 7 | font-size: 13px; 8 | font-weight: bold; 9 | text-decoration: none; 10 | color: var(--joplin-color); 11 | } 12 | 13 | ::-webkit-scrollbar { 14 | width: 7px; 15 | height: 7px; 16 | } 17 | 18 | ::-webkit-scrollbar-corner { 19 | background: none; 20 | } 21 | 22 | ::-webkit-scrollbar-track { 23 | border: none; 24 | } 25 | 26 | ::-webkit-scrollbar-thumb { 27 | background: rgba(100, 100, 100, 0.3); 28 | border-radius: 5px; 29 | } 30 | 31 | ::-webkit-scrollbar-track:hover { 32 | background: rgba(0, 0, 0, 0.1); 33 | } 34 | 35 | ::-webkit-scrollbar-thumb:hover { 36 | background: rgba(100, 100, 100, 0.7); 37 | } 38 | 39 | .nav { 40 | --bs-nav-link-padding-x: 0.6rem; 41 | --bs-nav-link-padding-y: 0.2rem; 42 | } 43 | 44 | div#myTabContent { 45 | margin-top: 2.1em; 46 | margin-bottom: 1.5em; 47 | } 48 | 49 | ul#myTab { 50 | background-color: var(--joplin-background-color); 51 | } 52 | 53 | div.spinner-border { 54 | text-align: center; 55 | } 56 | 57 | .list-group { 58 | --bs-list-group-border-color: var(--joplin-divider-color); 59 | --bs-list-group-color: var(--joplin-color); 60 | --bs-list-group-bg: var(--joplin-background-color); 61 | border: 1px solid var(--bs-list-group-border-color); 62 | } 63 | 64 | .list-group-item { 65 | border-right: none; 66 | border-top: none; 67 | --bs-list-group-border-color: var(--joplin-divider-color); 68 | } 69 | 70 | html { 71 | background: var(--joplin-background-color); 72 | color: var(--joplin-color); 73 | } 74 | 75 | body { 76 | --bs-body-bg: var(--joplin-background-color); 77 | --bs-body-color: var(--joplin-color); 78 | } 79 | 80 | .accordion { 81 | --bs-accordion-color: var(--joplin-color); 82 | --bs-accordion-bg: var(--joplin-background-color); 83 | } 84 | 85 | .nav-tabs { 86 | --bs-nav-tabs-link-active-bg: var(--joplin-selected-color); 87 | --bs-nav-tabs-link-active-color: var(--joplin-color); 88 | --bs-nav-tabs-link-active-border-color: var(--joplin-selected-color); 89 | --bs-nav-tabs-border-color: var(--joplin-selected-color); 90 | --bs-nav-tabs-link-hover-border-color: var(--joplin-selected-color); 91 | } 92 | 93 | div.info-line { 94 | position: fixed; 95 | bottom: 0; 96 | height: 1.5em; 97 | background-color: var(--joplin-background-color); 98 | display: block; 99 | width: 100%; 100 | border-top: 1px solid var(--joplin-selected-color); 101 | font-size: smaller; 102 | } 103 | 104 | div.info-line span.line-text { 105 | margin-left: 1em; 106 | } 107 | 108 | div.info-line .info-line-spans { 109 | display: flex; 110 | float: right; 111 | margin-right: 1em; 112 | } 113 | 114 | div.info-line span { 115 | padding-left: 0.25em; 116 | } 117 | 118 | .card { 119 | --bs-card-bg: var(--joplin-background-color); 120 | --bs-card-border-color: var(--joplin-divider-color); 121 | } 122 | 123 | input.form-control, input.form-control:focus { 124 | background-color: var(--joplin-background-color); 125 | color: var(--joplin-color); 126 | } 127 | 128 | select.form-select { 129 | background-color: var(--joplin-background-color); 130 | color: var(--joplin-color); 131 | } 132 | 133 | .btn-light { 134 | --bs-btn-bg: var(--joplin-background-color); 135 | --bs-btn-border-color: var(--joplin-divider-color); 136 | } 137 | 138 | .accordion-button { 139 | --bs-accordion-btn-padding-y: 0.3em; 140 | --bs-accordion-btn-padding-x: 1em; 141 | } 142 | -------------------------------------------------------------------------------- /src/scripts/sidebars/sidebars.js: -------------------------------------------------------------------------------- 1 | function tabItemClicked(id) { 2 | webviewApi.postMessage({ 3 | name: 'sidebar_tab_item_clicked', 4 | id: id 5 | }); 6 | } 7 | 8 | function onJoplinNoteLinkClicked(noteId) { 9 | webviewApi.postMessage({ 10 | name: 'sidebar_open_item', 11 | id: noteId 12 | }); 13 | } 14 | 15 | webviewApi.onMessage((data) => { 16 | if (data.message.type === 'update') { 17 | const element = document.getElementById(data.message.elementId); 18 | if (element) { 19 | element.innerHTML = data.message.html; 20 | } 21 | } 22 | }); 23 | -------------------------------------------------------------------------------- /src/scripts/writingMarker/writingMarker.css: -------------------------------------------------------------------------------- 1 | div.tagged-sentences { 2 | word-break: break-all; 3 | } 4 | 5 | div.tagged-sentences div.tag-badge { 6 | display: flex; 7 | float: right; 8 | } 9 | 10 | div.tagged-sentence-note-title { 11 | display: inline; 12 | } 13 | 14 | div.tagged-sentences li.list-group-item:hover { 15 | cursor: pointer; 16 | } 17 | -------------------------------------------------------------------------------- /src/scripts/writingMarker/writingMarker.js: -------------------------------------------------------------------------------- 1 | function taggedSentenceClicked(id) { 2 | webviewApi.postMessage({ 3 | name: 'sidebar_tagged_sentence_clicked', 4 | id: id 5 | }); 6 | } 7 | -------------------------------------------------------------------------------- /src/utils/noteUpdateNotify.ts: -------------------------------------------------------------------------------- 1 | import joplin from "../../api"; 2 | import { LAST_NOTE_UPDATE_DATE } from "../common"; 3 | import dateFormat from "dateformat"; 4 | import {searchNoteByUpdatedDate} from "./noteUtils"; 5 | import { debounce } from "ts-debounce"; 6 | 7 | class NoteUpdateNotify { 8 | 9 | lastUpdateDate: Date; 10 | updateCallbacks; 11 | deleteCallbacks; 12 | 13 | constructor() { 14 | this.updateCallbacks = []; 15 | this.deleteCallbacks = []; 16 | } 17 | 18 | debounceRefresh = debounce(async () => { 19 | const [notes, lastUpdatedTime] = await this.findUpdatedNotes(); 20 | if (notes.length > 0) { 21 | this.lastUpdateDate = new Date(lastUpdatedTime); 22 | await this.saveLastUpdateDate(); 23 | 24 | for (const callback of this.updateCallbacks) { 25 | await callback(notes); 26 | } 27 | } 28 | }, 100); 29 | 30 | async onNoteUpdates(callback: (notes) => {}) { 31 | this.updateCallbacks.push(callback); 32 | } 33 | 34 | async onNoteDeleted(callback: (noteId: string) => {}) { 35 | this.deleteCallbacks.push(callback); 36 | } 37 | 38 | async init() { 39 | await this.readLastUpdateDate(); 40 | 41 | await joplin.workspace.onSyncComplete(async () => { 42 | await this.debounceRefresh(); 43 | }); 44 | 45 | await joplin.workspace.onNoteSelectionChange(async () => { 46 | await this.debounceRefresh(); 47 | }) 48 | 49 | await joplin.workspace.onNoteChange(async (event) => { 50 | // https://joplinapp.org/api/references/plugin_api/enums/itemchangeeventtype.html 51 | if (event.event === 3) { 52 | for (const callback of this.deleteCallbacks) { 53 | callback(event.id); 54 | } 55 | } else { 56 | await this.debounceRefresh(); 57 | } 58 | }) 59 | } 60 | 61 | async saveLastUpdateDate() { 62 | await joplin.settings.setValue(LAST_NOTE_UPDATE_DATE, this.lastUpdateDate.toISOString()); 63 | } 64 | 65 | async readLastUpdateDate() { 66 | const dateStr = await joplin.settings.value(LAST_NOTE_UPDATE_DATE); 67 | if (dateStr.length > 0) { 68 | this.lastUpdateDate = new Date(dateStr); 69 | } 70 | } 71 | 72 | async findUpdatedNotes() : Promise<[any[], number]> { 73 | let updatedDate = '19700101'; 74 | if (this.lastUpdateDate) { 75 | updatedDate = dateFormat(this.lastUpdateDate, 'yyyymmdd'); 76 | } 77 | const updatedNotes = await searchNoteByUpdatedDate(updatedDate); 78 | 79 | let results = []; 80 | let lastUpdateTime: number = 0; 81 | for (const note of updatedNotes) { 82 | if (this.lastUpdateDate && note.updated_time > this.lastUpdateDate.valueOf()) { 83 | results.push(note); 84 | } 85 | 86 | if (note.updated_time > lastUpdateTime) { 87 | lastUpdateTime = note.updated_time; 88 | } 89 | } 90 | 91 | if (!this.lastUpdateDate) { 92 | results = updatedNotes; 93 | } 94 | return [results, lastUpdateTime]; 95 | } 96 | } 97 | 98 | const noteUpdateNotify = new NoteUpdateNotify(); 99 | export default noteUpdateNotify; 100 | -------------------------------------------------------------------------------- /src/utils/noteUtils.ts: -------------------------------------------------------------------------------- 1 | import joplin from "../../api"; 2 | 3 | 4 | export async function searchNoteByUpdatedDate(date: string) { 5 | let page = 0; 6 | let results = []; 7 | let r; 8 | do { 9 | page += 1; 10 | // I don't know how the basic search is implemented, it could be that it runs a regex 11 | // query on each note under the hood. If that is the case and this behaviour crushed 12 | // some slow clients, I should consider reverting this back to searching all notes 13 | // (with the rate limiter) 14 | r = await joplin.data.get(['search'], { 15 | query: `updated:${date}`, 16 | fields: ['id', 'body', 'title', 'parent_id', 'is_conflict', 'updated_time'], 17 | page: page 18 | }); 19 | if (r.items) { 20 | results = results.concat(r.items); 21 | } 22 | } while(r.has_more); 23 | return results; 24 | } 25 | 26 | 27 | export async function getAllNotes() { 28 | let page = 1; 29 | let results = []; 30 | let notes; 31 | do { 32 | notes = await joplin.data.get(['notes'], { 33 | fields: ['id', 'title', 'body', 'parent_id', 'is_conflict', 'updated_time'], 34 | page: page 35 | }); 36 | if (notes.items) { 37 | results = results.concat(notes.items); 38 | } 39 | page += 1; 40 | } while (notes.has_more); 41 | return results; 42 | } 43 | 44 | 45 | export async function getNoteTags(noteId) { 46 | let page = 1; 47 | let results = []; 48 | let searchResults; 49 | do { 50 | searchResults = await joplin.data.get(['notes', noteId, 'tags'], { 51 | fields: ['id', 'title'], 52 | page: page 53 | }); 54 | if (searchResults.items) { 55 | results = results.concat(searchResults.items); 56 | } 57 | page += 1; 58 | } while (searchResults.has_more); 59 | return results; 60 | } 61 | 62 | 63 | export async function getPath(noteParentId: string) { 64 | const results = []; 65 | let folder; 66 | do { 67 | folder = await getFolder(noteParentId); 68 | if (!folder) { 69 | break; 70 | } 71 | results.push(folder.title); 72 | if (folder) { 73 | noteParentId = folder.parent_id; 74 | } else { 75 | noteParentId = null; 76 | } 77 | } while (noteParentId); 78 | return results.reverse(); 79 | } 80 | 81 | 82 | export async function getFolder(folderId) { 83 | return await joplin.data.get(['folders', folderId], { fields: ['title', 'id', 'parent_id'] }); 84 | } 85 | -------------------------------------------------------------------------------- /src/utils/stringUtils.ts: -------------------------------------------------------------------------------- 1 | export function lineOfString(target: string, lines: string[]) : number { 2 | let lineNumber = 0; 3 | for (const line of lines) { 4 | lineNumber += 1; 5 | if (line.includes(target)) { 6 | return lineNumber; 7 | } 8 | } 9 | return 0; 10 | } 11 | 12 | 13 | /* 14 | * Find all the appearance of target in lines 15 | */ 16 | export function contextOfAppearance(target: string, lines: string[]) { 17 | let lineNumber = 0; 18 | let results = []; 19 | for (const line of lines) { 20 | lineNumber += 1; 21 | let index = line.indexOf(target); 22 | while (index > 0) { 23 | results.push([lineNumber, line]); 24 | index = line.indexOf(target, index + target.length); 25 | } 26 | } 27 | return results; 28 | } 29 | 30 | 31 | /** 32 | * We need to replace href=":/noteId" with webapi calls 33 | * @param source 34 | */ 35 | export function htmlConvert(source: string) { 36 | let result = source; 37 | const noteIdHrefReg = /href="(:\/\w{32})"/g; 38 | const hrefReg = /href="(.*?)"/g; 39 | let match; 40 | while ((match = noteIdHrefReg.exec(result)) !== null) { 41 | noteIdHrefReg.lastIndex = 0; 42 | result = result.replace(match[0], `href="#" onclick="onJoplinNoteLinkClicked('${match[1]}')"`); 43 | } 44 | 45 | let lastIndex = 0; 46 | while ((match = hrefReg.exec(result)) !== null) { 47 | if (match[1] === '#') { 48 | lastIndex = match.lastIndex; 49 | } else { 50 | match.lastIndex = lastIndex; 51 | result = result.replace(match[0], `href="#" onclick="onJoplinNoteLinkClicked('${match[1]}')"`); 52 | } 53 | } 54 | return result; 55 | } 56 | -------------------------------------------------------------------------------- /src/writingMarker/common.ts: -------------------------------------------------------------------------------- 1 | export class TaggedSentence { 2 | tags: string[]; 3 | text: string; 4 | noteId: string; 5 | noteTitle: string; 6 | index: number; 7 | line: number; 8 | } 9 | -------------------------------------------------------------------------------- /src/writingMarker/htmlGenerator.tsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import {renderToStaticMarkup} from 'react-dom/server' 3 | import {TaggedSentence} from "./common"; 4 | const stc = require('string-to-color'); 5 | var md = require('markdown-it')() 6 | .use(require('markdown-it-mark')); 7 | 8 | function renderHtml(items) { 9 | return
10 |
    11 | { 12 | items.map(item => 13 |
  • taggedSentenceClicked(`${item.noteId}-${item.index}`)}> 14 | 15 | 16 |
    17 |
    18 | {item.noteTitle} 19 |
    20 |
    21 | { 22 | item.tags.map(tag => {tag}) 24 | } 25 |
    26 |
    27 |
  • 28 | ) 29 | } 30 |
31 |
32 | } 33 | 34 | export async function panelHtml(items: TaggedSentence[]) { 35 | return renderToStaticMarkup(renderHtml(items)); 36 | } 37 | -------------------------------------------------------------------------------- /src/writingMarker/index.ts: -------------------------------------------------------------------------------- 1 | import {SidebarPlugin, Sidebars} from "../sidebars/sidebarPage"; 2 | import joplin from "../../api"; 3 | import {panelHtml} from "./panelHtml"; 4 | // import {panelHtml} from "./htmlGenerator"; 5 | import {getAllTaggedSentences, searchTaggedSentencesInNote} from "./utils"; 6 | import {debounce} from "ts-debounce"; 7 | import {TaggedSentence} from "./common"; 8 | import {WRITING_MARKER_PLUGIN_ID} from "../common"; 9 | 10 | class WritingMarkerPlugin extends SidebarPlugin { 11 | 12 | sidebar: Sidebars; 13 | items: {}; 14 | 15 | async refresh() { 16 | await this.updateTaggedSentences(); 17 | let itemArray = []; 18 | for (const noteId in this.items) { 19 | itemArray = itemArray.concat(this.items[noteId]); 20 | } 21 | await this.sidebar.updateHtml(this.id, await panelHtml(itemArray)); 22 | } 23 | 24 | async refreshNote(noteId: string) { 25 | const note = await joplin.data.get(['notes', noteId], { fields: ['id', 'body', 'title', 'parent_id', 'is_conflict'] }); 26 | if (note) { 27 | this.items[noteId] = await searchTaggedSentencesInNote(note); 28 | let itemArray = []; 29 | for (const noteId in this.items) { 30 | itemArray = itemArray.concat(this.items[noteId]); 31 | } 32 | await this.sidebar.updateHtml(this.id, await panelHtml(itemArray)); 33 | } 34 | } 35 | 36 | debounceRefresh = debounce(async () => { 37 | await this.refresh(); 38 | }, 100); 39 | 40 | debounceRefreshNote = debounce(async (noteId: string) => { 41 | await this.refreshNote(noteId); 42 | }, 100); 43 | 44 | constructor() { 45 | super(); 46 | 47 | this.id = WRITING_MARKER_PLUGIN_ID; 48 | this.name = "Writing Marker"; 49 | this.icon = "fas fa-tags"; 50 | this.styles = [ 51 | './scripts/writingMarker/writingMarker.css' 52 | ]; 53 | this.scripts = [ 54 | './scripts/writingMarker/writingMarker.js' 55 | ]; 56 | this.html = '
Under development...
'; 57 | } 58 | 59 | public async init(sidebar: Sidebars) { 60 | this.sidebar = sidebar; 61 | await joplin.workspace.onNoteSelectionChange(async () => { 62 | await this.debounceRefresh(); 63 | }); 64 | 65 | await joplin.workspace.onSyncComplete(async () => { 66 | await this.debounceRefresh(); 67 | }) 68 | 69 | await joplin.workspace.onNoteChange(async (event) => { 70 | await this.debounceRefreshNote(event.id); 71 | }) 72 | 73 | await this.debounceRefresh(); 74 | } 75 | 76 | // Joplin needs to scroll to the previous position. We need a large wait time to avoid scrolling before Joplin 77 | debounceScrollToLine = debounce(async (noteId, lineNumber) => { 78 | await joplin.commands.execute('editor.execCommand', { 79 | name: 'sidebar_cm_scrollToLine', 80 | args: [this.items[noteId][lineNumber].line] 81 | }); 82 | }, 500); 83 | 84 | async panelMsgProcess(msg: any): Promise { 85 | switch (msg.name) { 86 | case 'sidebar_tagged_sentence_clicked': 87 | if (msg.id) { 88 | const items = msg.id.split('-'); 89 | if (items.length === 2) { 90 | await joplin.commands.execute('openItem', `:/${items[0]}`); 91 | await this.debounceScrollToLine(items[0], items[1]); 92 | return true; 93 | } 94 | } 95 | break; 96 | default: 97 | break; 98 | } 99 | return false; 100 | } 101 | 102 | async updateTaggedSentences() { 103 | this.items = await getAllTaggedSentences(); 104 | } 105 | } 106 | 107 | const writingMarkerPlugin = new WritingMarkerPlugin(); 108 | export default writingMarkerPlugin; 109 | -------------------------------------------------------------------------------- /src/writingMarker/panelHtml.ts: -------------------------------------------------------------------------------- 1 | import {TaggedSentence} from "./common"; 2 | var md = require('markdown-it')() 3 | .use(require('markdown-it-mark')); 4 | const stc = require('string-to-color'); 5 | 6 | 7 | export async function panelHtml(items: TaggedSentence[]) { 8 | let results = []; 9 | results.push(`
`) 10 | results.push(`
    `); 11 | 12 | for (const item of items) { 13 | results.push(`
  • ${md.renderInline(item.text)}`); 14 | results.push(`
    `); 15 | results.push(`
    `); 16 | results.push(`${item.noteTitle}`); 17 | results.push(`
    `); 18 | results.push(`
    `); 19 | for (const tag of item.tags) { 20 | results.push(`${tag}`); 21 | } 22 | results.push(`
    `); 23 | results.push(`
    `) 24 | results.push(`
  • `); 25 | } 26 | 27 | results.push(`
`); 28 | results.push(`
`); 29 | return results.join(''); 30 | } 31 | -------------------------------------------------------------------------------- /src/writingMarker/utils.ts: -------------------------------------------------------------------------------- 1 | import joplin from "../../api"; 2 | import {TaggedSentence} from "./common"; 3 | 4 | const taggedSentenceReg = /\(([^\s)]+?)::([^)]+)\)/g; 5 | 6 | export async function getAllTaggedSentences() { 7 | let taggedSentences = {}; 8 | let page = 0; 9 | let r; 10 | do { 11 | page += 1; 12 | // I don't know how the basic search is implemented, it could be that it runs a regex 13 | // query on each note under the hood. If that is the case and this behaviour crushed 14 | // some slow clients, I should consider reverting this back to searching all notes 15 | // (with the rate limiter) 16 | r = await joplin.data.get(['search'], { query: taggedSentenceReg, fields: ['id', 'body', 'title', 'parent_id', 'is_conflict'], page: page }); 17 | if (r.items) { 18 | for (let note of r.items) { 19 | taggedSentences[note.id] = await searchTaggedSentencesInNote(note); 20 | } 21 | } 22 | } while(r.has_more); 23 | return taggedSentences; 24 | } 25 | 26 | export async function searchTaggedSentencesInNote(note) { 27 | // Conflict notes are duplicates usually 28 | if (note.is_conflict) { return; } 29 | let matches = []; 30 | let match; 31 | let index = 0; 32 | let lineNumber = 0; 33 | taggedSentenceReg.lastIndex = 0; 34 | for (const line of note.body.split('\n')) { 35 | while ((match = taggedSentenceReg.exec(line)) !== null) { 36 | // For todoitems in daily notes, we consider the note date as the default task date 37 | const item = new TaggedSentence(); 38 | item.tags = match[1].split('|'); 39 | item.noteId = note.id; 40 | item.noteTitle = note.title; 41 | item.text = match[2]; 42 | item.index = index; 43 | item.line = lineNumber; 44 | matches.push(item); 45 | index += 1; 46 | } 47 | lineNumber += 1; 48 | } 49 | 50 | return matches; 51 | } 52 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist/", 4 | "module": "commonjs", 5 | "target": "es2015", 6 | "jsx": "react", 7 | "allowJs": true, 8 | "baseUrl": ".", 9 | "allowSyntheticDefaultImports": true 10 | } 11 | } 12 | --------------------------------------------------------------------------------