1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-12-26 23:38:08 +02:00

Compare commits

...

30 Commits

Author SHA1 Message Date
Laurent Cozic
89576de289 Merge branch 'release-1.3' into plugin_content_scripts 2020-10-21 00:23:00 +01:00
Laurent Cozic
c75aa21ffd Fixed tests 2020-10-21 00:19:52 +01:00
Laurent Cozic
075187729d Fixed tests 2020-10-21 00:11:53 +01:00
Laurent Cozic
14696b8c65 Fixed slow rendering of note 2020-10-20 23:27:58 +01:00
Laurent Cozic
61c09f5bf8 Clean up 2020-10-20 22:35:21 +01:00
Laurent Cozic
9f7ea7d865 Updated doc 2020-10-20 20:05:31 +01:00
Laurent Cozic
98bf3bde8d Finished converting plugins 2020-10-20 19:56:34 +01:00
Laurent Cozic
fe90d92e01 Simplified how Markdown-It plugins are created 2020-10-20 17:52:02 +01:00
Laurent Cozic
5292fc1402 Tools: Escape HTML when generating changelog 2020-10-20 17:16:09 +01:00
Laurent Cozic
03063f1137 All: Fixed setting issue that would cause a password to be saved in plain text in the database, even when the keychain is working 2020-10-20 16:37:14 +01:00
Laurent Cozic
b125a768b8 Tools: Added test units for keychains on macOS and Windows 2020-10-20 16:16:18 +01:00
Laurent Cozic
a721f170e4 Doc: Added info about search filters 2020-10-20 12:12:00 +01:00
Laurent Cozic
76cd69ea16 Electron release v1.3.7 2020-10-20 12:01:12 +01:00
Laurent Cozic
45d4f277e2 Merge branch 'dev' into release-1.3 2020-10-20 12:00:39 +01:00
Naveen M V
fc2a52aa1a Desktop, Cli; Fix notebook search filter (#3946) 2020-10-20 11:54:46 +01:00
Roman Musin
b3e5a1e48d Android: do not show long press menu on press and drag (#3939) 2020-10-20 11:51:24 +01:00
Laurent Cozic
45eb902030 Fixed tests 2020-10-20 11:49:15 +01:00
Ian Slinger
456f7ac00c Desktop, Cli: Import <strike>,<s> tags (strikethrough) from Evernote (#3936) 2020-10-20 11:47:48 +01:00
Aaron
a93bda71fe All: Resolves #3691: Added support for a custom S3 URL (#3921) 2020-10-20 11:44:11 +01:00
Alkindi42
0f9d92dd3d Doc: add archlinux package for pre-release in docs (#3875) 2020-10-20 11:42:41 +01:00
Laurent Cozic
5543e9ef64 Merge branch 'release-1.3' of https://github.com/laurent22/joplin into release-1.3 2020-10-20 11:14:58 +01:00
Laurent Cozic
22dd613660 Revert "Plugins: Adding support for command boolean expressions"
This reverts commit f8f46db910.

Feature was implemented in 3a57cfea02
2020-10-20 11:13:56 +01:00
Laurent Cozic
47c7b864cb Clean up rules 2020-10-19 16:40:11 +01:00
Laurent Cozic
d927a238bb Fixed tests 2020-10-19 14:29:40 +01:00
Laurent Cozic
388a56c5dd Add support for content scripts 2020-10-19 14:00:47 +01:00
Helmut K. C. Tessarek
71bf0437c1 Desktop: Tray: Exit -> Quit (#3945) 2020-10-18 12:57:04 +01:00
Tomáš Bambas
eca4e24362 All: Translation: Update cs_CZ.po (#3940) 2020-10-17 14:01:32 -04:00
Andros Fenollosa
9a6efb7b37 All: Translation: Update es_ES.po (#3929)
* Update locale es

* Finish translate
2020-10-17 14:00:48 -04:00
jduar
4b666cbbd2 All: Translation: Update pt-PT.po (#3924)
* Updated the Portuguese (pt-PT) translation.

* Updated translator name and email.
2020-10-17 13:58:49 -04:00
Laurent Cozic
f8f46db910 Plugins: Adding support for command boolean expressions 2020-10-17 16:50:07 +01:00
137 changed files with 6920 additions and 1021 deletions

View File

@@ -64,10 +64,13 @@ CliClient/build/
# AUTO-GENERATED - EXCLUDED TYPESCRIPT BUILD
CliClient/app/LinkSelector.js
CliClient/app/services/plugins/PluginRunner.js
CliClient/tests/fsDriver.js
CliClient/tests/InMemoryCache.js
CliClient/tests/MdToHtml.js
CliClient/tests/models_Setting.js
CliClient/tests/services_CommandService.js
CliClient/tests/services_InteropService.js
CliClient/tests/services_keychainService.js
CliClient/tests/services_PluginService.js
CliClient/tests/services_rest_Api.js
CliClient/tests/services/plugins/api/JoplinSetting.js
@@ -215,22 +218,36 @@ ReactNativeClient/lib/components/screens/UpgradeSyncTargetScreen.js
ReactNativeClient/lib/components/SelectDateTimeDialog.js
ReactNativeClient/lib/errorUtils.js
ReactNativeClient/lib/eventManager.js
ReactNativeClient/lib/fs-driver-node.js
ReactNativeClient/lib/hooks/useEffectDebugger.js
ReactNativeClient/lib/hooks/useImperativeHandlerDebugger.js
ReactNativeClient/lib/hooks/usePrevious.js
ReactNativeClient/lib/hooks/usePropsDebugger.js
ReactNativeClient/lib/InMemoryCache.js
ReactNativeClient/lib/joplin-renderer/MarkupToHtml.js
ReactNativeClient/lib/joplin-renderer/MdToHtml.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/checkbox.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/code_inline.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fence.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fountain.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/highlight_keywords.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/html_image.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/image.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/katex.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/link_open.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/mermaid.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/sanitize_html.js
ReactNativeClient/lib/joplin-renderer/noteStyle.js
ReactNativeClient/lib/joplin-renderer/pathUtils.js
ReactNativeClient/lib/JoplinServerApi.js
ReactNativeClient/lib/locale.js
ReactNativeClient/lib/Logger.js
ReactNativeClient/lib/markdownUtils.js
ReactNativeClient/lib/markupLanguageUtils.js
ReactNativeClient/lib/models/Alarm.js
ReactNativeClient/lib/models/Setting.js
ReactNativeClient/lib/ntpDate.js
ReactNativeClient/lib/path-utils.js
ReactNativeClient/lib/PoorManIntervals.js
ReactNativeClient/lib/reducer.js
ReactNativeClient/lib/services/AlarmService.js
@@ -291,6 +308,7 @@ ReactNativeClient/lib/services/plugins/PluginService.js
ReactNativeClient/lib/services/plugins/reducer.js
ReactNativeClient/lib/services/plugins/sandboxProxy.js
ReactNativeClient/lib/services/plugins/ToolbarButtonController.js
ReactNativeClient/lib/services/plugins/utils/contentScriptsToRendererRules.js
ReactNativeClient/lib/services/plugins/utils/createViewHandle.js
ReactNativeClient/lib/services/plugins/utils/executeSandboxCall.js
ReactNativeClient/lib/services/plugins/utils/manifestFromObject.js

18
.gitignore vendored
View File

@@ -58,10 +58,13 @@ plugin_types/
# AUTO-GENERATED - EXCLUDED TYPESCRIPT BUILD
CliClient/app/LinkSelector.js
CliClient/app/services/plugins/PluginRunner.js
CliClient/tests/fsDriver.js
CliClient/tests/InMemoryCache.js
CliClient/tests/MdToHtml.js
CliClient/tests/models_Setting.js
CliClient/tests/services_CommandService.js
CliClient/tests/services_InteropService.js
CliClient/tests/services_keychainService.js
CliClient/tests/services_PluginService.js
CliClient/tests/services_rest_Api.js
CliClient/tests/services/plugins/api/JoplinSetting.js
@@ -209,22 +212,36 @@ ReactNativeClient/lib/components/screens/UpgradeSyncTargetScreen.js
ReactNativeClient/lib/components/SelectDateTimeDialog.js
ReactNativeClient/lib/errorUtils.js
ReactNativeClient/lib/eventManager.js
ReactNativeClient/lib/fs-driver-node.js
ReactNativeClient/lib/hooks/useEffectDebugger.js
ReactNativeClient/lib/hooks/useImperativeHandlerDebugger.js
ReactNativeClient/lib/hooks/usePrevious.js
ReactNativeClient/lib/hooks/usePropsDebugger.js
ReactNativeClient/lib/InMemoryCache.js
ReactNativeClient/lib/joplin-renderer/MarkupToHtml.js
ReactNativeClient/lib/joplin-renderer/MdToHtml.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/checkbox.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/code_inline.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fence.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fountain.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/highlight_keywords.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/html_image.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/image.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/katex.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/link_open.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/mermaid.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/sanitize_html.js
ReactNativeClient/lib/joplin-renderer/noteStyle.js
ReactNativeClient/lib/joplin-renderer/pathUtils.js
ReactNativeClient/lib/JoplinServerApi.js
ReactNativeClient/lib/locale.js
ReactNativeClient/lib/Logger.js
ReactNativeClient/lib/markdownUtils.js
ReactNativeClient/lib/markupLanguageUtils.js
ReactNativeClient/lib/models/Alarm.js
ReactNativeClient/lib/models/Setting.js
ReactNativeClient/lib/ntpDate.js
ReactNativeClient/lib/path-utils.js
ReactNativeClient/lib/PoorManIntervals.js
ReactNativeClient/lib/reducer.js
ReactNativeClient/lib/services/AlarmService.js
@@ -285,6 +302,7 @@ ReactNativeClient/lib/services/plugins/PluginService.js
ReactNativeClient/lib/services/plugins/reducer.js
ReactNativeClient/lib/services/plugins/sandboxProxy.js
ReactNativeClient/lib/services/plugins/ToolbarButtonController.js
ReactNativeClient/lib/services/plugins/utils/contentScriptsToRendererRules.js
ReactNativeClient/lib/services/plugins/utils/createViewHandle.js
ReactNativeClient/lib/services/plugins/utils/executeSandboxCall.js
ReactNativeClient/lib/services/plugins/utils/manifestFromObject.js

18
.ignore
View File

@@ -7,10 +7,13 @@
# AUTO-GENERATED - EXCLUDED TYPESCRIPT BUILD
CliClient/app/LinkSelector.js
CliClient/app/services/plugins/PluginRunner.js
CliClient/tests/fsDriver.js
CliClient/tests/InMemoryCache.js
CliClient/tests/MdToHtml.js
CliClient/tests/models_Setting.js
CliClient/tests/services_CommandService.js
CliClient/tests/services_InteropService.js
CliClient/tests/services_keychainService.js
CliClient/tests/services_PluginService.js
CliClient/tests/services_rest_Api.js
CliClient/tests/services/plugins/api/JoplinSetting.js
@@ -158,22 +161,36 @@ ReactNativeClient/lib/components/screens/UpgradeSyncTargetScreen.js
ReactNativeClient/lib/components/SelectDateTimeDialog.js
ReactNativeClient/lib/errorUtils.js
ReactNativeClient/lib/eventManager.js
ReactNativeClient/lib/fs-driver-node.js
ReactNativeClient/lib/hooks/useEffectDebugger.js
ReactNativeClient/lib/hooks/useImperativeHandlerDebugger.js
ReactNativeClient/lib/hooks/usePrevious.js
ReactNativeClient/lib/hooks/usePropsDebugger.js
ReactNativeClient/lib/InMemoryCache.js
ReactNativeClient/lib/joplin-renderer/MarkupToHtml.js
ReactNativeClient/lib/joplin-renderer/MdToHtml.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/checkbox.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/code_inline.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fence.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fountain.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/highlight_keywords.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/html_image.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/image.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/katex.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/link_open.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/mermaid.js
ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/sanitize_html.js
ReactNativeClient/lib/joplin-renderer/noteStyle.js
ReactNativeClient/lib/joplin-renderer/pathUtils.js
ReactNativeClient/lib/JoplinServerApi.js
ReactNativeClient/lib/locale.js
ReactNativeClient/lib/Logger.js
ReactNativeClient/lib/markdownUtils.js
ReactNativeClient/lib/markupLanguageUtils.js
ReactNativeClient/lib/models/Alarm.js
ReactNativeClient/lib/models/Setting.js
ReactNativeClient/lib/ntpDate.js
ReactNativeClient/lib/path-utils.js
ReactNativeClient/lib/PoorManIntervals.js
ReactNativeClient/lib/reducer.js
ReactNativeClient/lib/services/AlarmService.js
@@ -234,6 +251,7 @@ ReactNativeClient/lib/services/plugins/PluginService.js
ReactNativeClient/lib/services/plugins/reducer.js
ReactNativeClient/lib/services/plugins/sandboxProxy.js
ReactNativeClient/lib/services/plugins/ToolbarButtonController.js
ReactNativeClient/lib/services/plugins/utils/contentScriptsToRendererRules.js
ReactNativeClient/lib/services/plugins/utils/createViewHandle.js
ReactNativeClient/lib/services/plugins/utils/executeSandboxCall.js
ReactNativeClient/lib/services/plugins/utils/manifestFromObject.js

View File

@@ -8,7 +8,7 @@ const Note = require('lib/models/Note.js');
const Tag = require('lib/models/Tag.js');
const Setting = require('lib/models/Setting').default;
const { reg } = require('lib/registry.js');
const { fileExtension } = require('lib/path-utils.js');
const { fileExtension } = require('lib/path-utils');
const { _ } = require('lib/locale');
const fs = require('fs-extra');
const { cliUtils } = require('./cli-utils.js');

View File

@@ -1,5 +1,5 @@
const fs = require('fs-extra');
const { fileExtension, dirname } = require('lib/path-utils.js');
const { fileExtension, dirname } = require('lib/path-utils');
const wrap_ = require('word-wrap');
const { languageCode } = require('lib/locale');

View File

@@ -2,7 +2,7 @@
const fs = require('fs-extra');
const Logger = require('lib/Logger').default;
const { dirname } = require('lib/path-utils.js');
const { dirname } = require('lib/path-utils');
const { DatabaseDriverNode } = require('lib/database-driver-node.js');
const { JoplinDatabase } = require('lib/joplin-database.js');
const BaseModel = require('lib/BaseModel.js');

View File

@@ -5,7 +5,7 @@ const DecryptionWorker = require('lib/services/DecryptionWorker');
const BaseItem = require('lib/models/BaseItem');
const Setting = require('lib/models/Setting').default;
const shim = require('lib/shim').default;
const pathUtils = require('lib/path-utils.js');
const pathUtils = require('lib/path-utils');
const imageType = require('image-type');
const readChunk = require('read-chunk');

View File

@@ -3,8 +3,8 @@
const { time } = require('lib/time-utils.js');
const Logger = require('lib/Logger').default;
const Resource = require('lib/models/Resource.js');
const { dirname } = require('lib/path-utils.js');
const { FsDriverNode } = require('./fs-driver-node.js');
const { dirname } = require('lib/path-utils');
const FsDriverNode = require('lib/fs-driver-node').default;
const lodash = require('lodash');
const exec = require('child_process').exec;
const fs = require('fs-extra');

View File

@@ -24,7 +24,7 @@ const MasterKey = require('lib/models/MasterKey');
const Setting = require('lib/models/Setting').default;
const Revision = require('lib/models/Revision.js');
const Logger = require('lib/Logger').default;
const { FsDriverNode } = require('lib/fs-driver-node.js');
const FsDriverNode = require('lib/fs-driver-node').default;
const { shimInit } = require('lib/shim-init-node.js');
const { _ } = require('lib/locale');
const { FileApiDriverLocal } = require('lib/file-api-driver-local.js');

File diff suppressed because it is too large Load Diff

View File

@@ -2,25 +2,29 @@
# Copyright (C) 2017 Lucas Vieites
# Copyright (C) 2019 Andros Fenollosa
# Copyright (C) 2019 Germán Martín
# Copyright (C) 2020 Andros Fenollosa
# This file is distributed under the same license as the Joplin-CLI package.
# Lucas Vieites <lucas.vieites@gmail.com>, 2017.
# Andros Fenollosa <andros@fenollosa.email>, 2019.
# Germán Martín <gmag11@gmail.com>, 2019.
# Fernando Pindado <fpindado@gmail.com>, 2020.
# Andros Fenollosa <andros@fenollosa.email>, 2020.
#
msgid ""
msgstr ""
"Project-Id-Version: Joplin-CLI 1.0.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: Fernando Pindado <fpindado@gmail.com>\n"
"Last-Translator: Andros Fenollosa <andros@fenollosa.email>\n"
"Language-Team: Spanish <lucas.vieites@gmail.com>\n"
"Language: es_ES\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Generator: Poedit 2.4.1\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"POT-Creation-Date: \n"
"PO-Revision-Date: \n"
#: ElectronClient/services/plugins/UserWebviewDialogButtonBar.js:20
#: ElectronClient/checkForUpdates.js:139
@@ -528,12 +532,14 @@ msgstr "Creando nuevo %s..."
#: ElectronClient/gui/NoteEditor/NoteEditor.js:373
msgid "The following attachments are being watched for changes:"
msgstr ""
"Los siguientes adjuntos están siendo vigilados para ver si hay cambios:"
#: ElectronClient/gui/NoteEditor/NoteEditor.js:376
msgid ""
"The attachments will no longer be watched when you switch to a different "
"note."
msgstr ""
"Los archivos adjuntos ya no se verán cuándo cambies a una nota diferente."
#: ElectronClient/gui/NoteEditor/NoteEditor.js:381
#, javascript-format
@@ -649,12 +655,15 @@ msgid ""
"may take a few minutes to complete and the app needs to be restarted. To "
"proceed please click on the link."
msgstr ""
"El objetivo de sincronización necesita ser actualizado antes de que Joplin "
"pueda sincronizarse. La operación puede tardar unos minutos en completarse y "
"la aplicación necesita ser reiniciada. Para proceder, por favor, haz clic en "
"el enlace."
#: ElectronClient/gui/MainScreen/MainScreen.js:416
#: ElectronClient/gui/MainScreen/MainScreen.min.js:306
#, fuzzy
msgid "Restart and upgrade"
msgstr "Claves maestras que necesitan actualización"
msgstr "Reiniciar y actualizar"
#: ElectronClient/gui/MainScreen/MainScreen.js:420
#: ElectronClient/gui/MainScreen/MainScreen.min.js:313
@@ -814,9 +823,8 @@ msgid "Toggle sidebar"
msgstr "Cambia la barra lateral"
#: ElectronClient/gui/MainScreen/commands/toggleEditors.js:17
#, fuzzy
msgid "Toggle editors"
msgstr "Cambia el diseño del editor"
msgstr "Intercambiar editores"
#: ElectronClient/gui/MainScreen/commands/selectTemplate.js:23
msgid "Template file:"
@@ -1321,9 +1329,8 @@ msgid "Import"
msgstr "Importar"
#: ElectronClient/gui/MenuBar.js:343
#, fuzzy
msgid "Export all"
msgstr "Exportar"
msgstr "Exportar todo"
#: ElectronClient/gui/MenuBar.js:356
#, javascript-format
@@ -1404,38 +1411,36 @@ msgstr "Adjuntos"
#: ElectronClient/gui/KeymapConfig/ShortcutRecorder.js:48
msgid "Press the shortcut"
msgstr ""
msgstr "Presiona el atajo"
#: ElectronClient/gui/KeymapConfig/ShortcutRecorder.js:48
msgid ""
"Press the shortcut and then press ENTER. Or, press BACKSPACE to clear the "
"shortcut."
msgstr ""
"Pulse el atajo y luego ENTER. O bien, pulse RETROCESO para borrar el atajo."
#: ElectronClient/gui/KeymapConfig/KeymapConfigScreen.js:62
#: ReactNativeClient/lib/services/KeymapService.js:142
#, fuzzy, javascript-format
#, javascript-format
msgid "Error: %s"
msgstr "Error"
msgstr "Error: %s"
#: ElectronClient/gui/KeymapConfig/KeymapConfigScreen.js:125
msgid "Command"
msgstr ""
msgstr "Comando"
#: ElectronClient/gui/KeymapConfig/KeymapConfigScreen.js:126
#, fuzzy
msgid "Keyboard Shortcut"
msgstr "Modo de teclado"
msgstr "Atajo de teclado"
#: ElectronClient/gui/KeymapConfig/utils/getLabel.js:24
#, fuzzy
msgid "Hide Joplin"
msgstr "Acerca de Joplin"
msgstr "Ocultar Joplin"
#: ElectronClient/gui/KeymapConfig/utils/getLabel.js:28
#, fuzzy
msgid "Preferences"
msgstr "Preferencias..."
msgstr "Preferencias"
#: ElectronClient/gui/NoteContentPropertiesDialog.js:77
msgid "Words"
@@ -1480,6 +1485,8 @@ msgstr "Estadísticas"
msgid ""
"The app is now going to close. Please relaunch it to complete the process."
msgstr ""
"La aplicación se va a cerrar. Por favor, vuelva a iniciarla para completar "
"el proceso."
#: ElectronClient/app.js:340
#, javascript-format
@@ -1491,9 +1498,8 @@ msgid "Exit"
msgstr "Salir"
#: ElectronClient/commands/copyDevCommand.js:17
#, fuzzy
msgid "Copy dev mode command to clipboard"
msgstr "Copiar la ruta en el portapapeles"
msgstr "Copiar el comando del modo de desarrollo al portapapeles"
#: ElectronClient/commands/startExternalEditing.js:18
msgid "Edit in external editor"
@@ -1505,13 +1511,12 @@ msgid "Error opening note in editor: %s"
msgstr "Error abriendo la nota en el editor: %s"
#: ElectronClient/commands/toggleExternalEditing.js:16
#, fuzzy
msgid "Toggle external editing"
msgstr "Detener la edición externa"
msgstr "Intercambiar la edición externa"
#: ElectronClient/commands/toggleExternalEditing.js:42
msgid "Stop"
msgstr ""
msgstr "Parar"
#: ElectronClient/commands/stopExternalEditing.js:16
msgid "Stop external editing"
@@ -1740,7 +1745,7 @@ msgstr ""
#: CliClient/app/command-sync.js:35
msgid "Upgrade the sync target to the latest version."
msgstr ""
msgstr "Actualiza el objetivo de sincronización a la última versión."
#: CliClient/app/command-sync.js:105
#, javascript-format
@@ -2247,10 +2252,10 @@ msgstr ""
"No se puede cargar el módulo «%s» para el formato «%s» y destino \"%s\""
#: ReactNativeClient/lib/services/interop/InteropService.js:152
#, fuzzy, javascript-format
#, javascript-format
msgid "Cannot load \"%s\" module for format \"%s\" and target \"%s\""
msgstr ""
"No se puede cargar el módulo «%s» para el formato «%s» y destino \"%s\""
"No se puede cargar el módulo %s para el formato %s y el objetivo “%s”"
#: ReactNativeClient/lib/services/interop/InteropService.js:187
#, javascript-format
@@ -2267,23 +2272,23 @@ msgstr "Notas restauradas"
#: ReactNativeClient/lib/services/KeymapService.js:236
msgid "command"
msgstr ""
msgstr "comando"
#: ReactNativeClient/lib/services/KeymapService.js:236
#: ReactNativeClient/lib/services/KeymapService.js:241
#, javascript-format
msgid "\"%s\" is missing the required \"%s\" property."
msgstr ""
msgstr "A “%s” le falta la propiedad requerida de “%s”."
#: ReactNativeClient/lib/services/KeymapService.js:241
#: ReactNativeClient/lib/services/KeymapService.js:248
msgid "accelerator"
msgstr ""
msgstr "acelerador"
#: ReactNativeClient/lib/services/KeymapService.js:248
#, fuzzy, javascript-format
#, javascript-format
msgid "Invalid %s: %s."
msgstr "Respuesta inválida: %s"
msgstr "Inválido %s: %s."
#: ReactNativeClient/lib/services/KeymapService.js:266
#, javascript-format
@@ -2291,11 +2296,13 @@ msgid ""
"Accelerator \"%s\" is used for \"%s\" and \"%s\" commands. This may lead to "
"unexpected behaviour."
msgstr ""
"El acelerador “%s” se usa para los comandos “%s” y “%s”. Esto puede llevar a "
"un comportamiento inesperado."
#: ReactNativeClient/lib/services/KeymapService.js:291
#, javascript-format
msgid "Accelerator \"%s\" is not valid."
msgstr ""
msgstr "El acelerador “%s” no es válido."
#: ReactNativeClient/lib/services/report.js:121
msgid "Items that cannot be synchronised"
@@ -2445,7 +2452,7 @@ msgstr "Versión del perfil: %s"
#: ReactNativeClient/lib/versionInfo.js:23
#, javascript-format
msgid "Keychain Supported: %s"
msgstr ""
msgstr "Llavero soportado: %s"
#: ReactNativeClient/lib/JoplinServerApi.js:71
#, javascript-format
@@ -2849,7 +2856,7 @@ msgstr "Añadir título"
#: ReactNativeClient/lib/components/screens/UpgradeSyncTargetScreen.js:42
msgid "Sync Target Upgrade"
msgstr ""
msgstr "Actualización del objetivo de sincronización"
#: ReactNativeClient/lib/components/screens/encryption-config.js:119
#, javascript-format
@@ -2941,6 +2948,8 @@ msgstr ""
#: ReactNativeClient/lib/components/screen-header.js:453
msgid "The sync target needs to be upgraded. Press this banner to proceed."
msgstr ""
"El objetivo de sincronización necesita ser mejorado. Presiona este banner "
"para proceder."
#: ReactNativeClient/lib/components/side-menu-content.js:126
#, javascript-format
@@ -3137,7 +3146,7 @@ msgstr "sí"
#: ReactNativeClient/lib/models/Setting.js:66
#, javascript-format
msgid "(wysiwyg: %s)"
msgstr ""
msgstr "(wysiwyg: %s)"
#: ReactNativeClient/lib/models/Setting.js:66
msgid "no"
@@ -3180,7 +3189,7 @@ msgstr "Nord"
#: ReactNativeClient/lib/models/Setting.js:80
msgid "Aritim Dark"
msgstr ""
msgstr "Aritim Oscuro"
#: ReactNativeClient/lib/models/Setting.js:81
msgid "OLED Dark"
@@ -3229,15 +3238,15 @@ msgstr "Contraseña de WebDAV"
#: ReactNativeClient/lib/models/Setting.js:214
msgid "AWS S3 bucket"
msgstr ""
msgstr "AWS S3 bucket"
#: ReactNativeClient/lib/models/Setting.js:225
msgid "AWS key"
msgstr ""
msgstr "AWS key"
#: ReactNativeClient/lib/models/Setting.js:235
msgid "AWS secret"
msgstr ""
msgstr "AWS secret"
#: ReactNativeClient/lib/models/Setting.js:247
msgid "Attachment download behaviour"
@@ -3695,9 +3704,8 @@ msgid "Web Clipper"
msgstr "Web Clipper"
#: ReactNativeClient/lib/models/Setting.js:1292
#, fuzzy
msgid "Keyboard Shortcuts"
msgstr "Modo de teclado"
msgstr "Atajos de teclado"
#: ReactNativeClient/lib/models/Setting.js:1299
msgid ""
@@ -3744,7 +3752,7 @@ msgstr "OneDrive"
#: ReactNativeClient/lib/SyncTargetAmazonS3.js:28
msgid "AWS S3"
msgstr ""
msgstr "AWS S3"
#: ReactNativeClient/lib/commands/historyForward.js:16
msgid "Forward"

View File

@@ -7,14 +7,16 @@ msgid ""
msgstr ""
"Project-Id-Version: Joplin-CLI 1.0.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: Diogo Caveiro \n"
"Last-Translator: João Duarte <jduar@protonmail.com>\n"
"Language-Team: \n"
"Language: pt_PT\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: Poedit 2.2.4\n"
"X-Generator: Poedit 2.4.1\n"
"POT-Creation-Date: \n"
"PO-Revision-Date: \n"
#: ElectronClient/services/plugins/UserWebviewDialogButtonBar.js:20
#: ElectronClient/checkForUpdates.js:139
@@ -112,29 +114,28 @@ msgid "Full Release Notes"
msgstr "Notas de Lançamento Completas"
#: ElectronClient/InteropServiceHelper.js:153
#, fuzzy, javascript-format
#, javascript-format
msgid "Exporting to \"%s\" as \"%s\" format. Please wait..."
msgstr "A importar de \"%s\" com o formato \"%s\". Por favor, aguarde..."
msgstr "A exportar para \"%s\" com o formato \"%s\". Por favor, aguarde..."
#: ElectronClient/InteropServiceHelper.js:170
#, fuzzy, javascript-format
#, javascript-format
msgid "Could not export notes: %s"
msgstr "Não foi possível atualizar a chave mestra: %s"
msgstr "Não foi possível exportar as notas: %s"
#: ElectronClient/plugins/GotoAnything.min.js:459
#, fuzzy
msgid ""
"Type a note title or part of its content to jump to it. Or type # followed "
"by a tag name, or @ followed by a notebook name."
msgstr ""
"Digite um título de nota para avançar para o mesmo. Ou digite # seguido do "
"título de uma etiqueta, ou @ seguido do nome de um bloco de notas, ou / "
"seguido do conteúdo da nota."
"Escreva um título de uma nota ou parte do seu conteúdo para saltar para o "
"mesmo. Ou digite # seguido de um nome de etiqueta, ou @ seguido de um nome "
"de um caderno."
#: ElectronClient/plugins/GotoAnything.min.js:499
#: ElectronClient/gui/KeymapConfig/utils/getLabel.js:20
msgid "Goto Anything..."
msgstr "Ir até qualquer coisa..."
msgstr "Saltar para..."
#: ElectronClient/gui/NoteListControls/commands/focusSearch.js:15
msgid "Search in all the notes"
@@ -178,9 +179,9 @@ msgid "Delete"
msgstr "Eliminar"
#: ElectronClient/gui/ResourceScreen.js:94
#, fuzzy, javascript-format
#, javascript-format
msgid "Delete attachment \"%s\"?"
msgstr "Eliminar nota \"%s\"?"
msgstr "Eliminar anexo \"%s\"?"
#: ElectronClient/gui/ResourceScreen.js:140
msgid ""
@@ -188,6 +189,9 @@ msgid ""
"notes. Please be careful when deleting one of them as they cannot be "
"restored afterwards."
msgstr ""
"Esta é uma ferramenta avançada para ver os anexos que estão ligados às suas "
"notas. Por favor tenha cuidado ao apagar um deles já que não poderão ser "
"repostos de seguida."
#: ElectronClient/gui/ResourceScreen.js:141
msgid "Please wait..."
@@ -195,13 +199,13 @@ msgstr "Por favor, aguarde..."
#: ElectronClient/gui/ResourceScreen.js:143
msgid "No resources!"
msgstr "Sem fontes!"
msgstr "Sem recursos!"
#: ElectronClient/gui/ResourceScreen.js:145
#, javascript-format
msgid "Warning: not all resources shown for performance reasons (limit: %s)."
msgstr ""
"Aviso: nem todas as fontes apresentadas por razões de desempenho (limite: "
"Aviso: nem todos os recursos apresentadas por razões de desempenho (limite: "
"%s)."
#: ElectronClient/gui/PromptDialog.min.js:249
@@ -427,11 +431,11 @@ msgstr "Anexar ficheiro"
#: ElectronClient/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.js:584
msgid "Code Block"
msgstr ""
msgstr "Bloco de Código"
#: ElectronClient/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.js:593
msgid "Inline Code"
msgstr ""
msgstr "Código em Linha"
#: ElectronClient/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.js:608
#: ElectronClient/gui/NoteEditor/commands/editorCommandDeclarations.js:83
@@ -440,13 +444,12 @@ msgstr "Inserir Data e Hora"
#: ElectronClient/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.js:1030
msgid "Drop notes or files here"
msgstr ""
msgstr "Insira notas ou ficheiros aqui"
#: ElectronClient/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.js:1030
#: ElectronClient/gui/MainScreen/MainScreen.min.js:419
#, fuzzy
msgid "Code View"
msgstr "Código"
msgstr "Vista de Código"
#: ElectronClient/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.js:1030
#, javascript-format
@@ -454,18 +457,18 @@ msgid ""
"Please wait for all attachments to be downloaded and decrypted. You may also "
"switch to %s to edit the note."
msgstr ""
"Por favor espere que todos os anexados sejam transferidos e desencriptados. "
"Também pode mudar para %s para editar a nota."
#: ElectronClient/gui/NoteEditor/NoteBody/TinyMCE/plugins/lists.js:2151
#, fuzzy
msgid "Checkbox list"
msgstr "Campo de seleção"
msgstr "Lista de caixas de seleção"
#: ElectronClient/gui/NoteEditor/NoteBody/CodeMirror/CodeMirror.js:165
msgid "strong text"
msgstr "texto destacado"
#: ElectronClient/gui/NoteEditor/NoteBody/CodeMirror/CodeMirror.js:166
#, fuzzy
msgid "emphasised text"
msgstr "texto realçado"
@@ -526,13 +529,14 @@ msgstr "A criar novo/a %s..."
#: ElectronClient/gui/NoteEditor/NoteEditor.js:373
msgid "The following attachments are being watched for changes:"
msgstr ""
msgstr "Os anexos seguintes estão a ser monitorizados quanto a alterações:"
#: ElectronClient/gui/NoteEditor/NoteEditor.js:376
msgid ""
"The attachments will no longer be watched when you switch to a different "
"note."
msgstr ""
"Os anexos deixarão de ser monitorizados quando mudar para uma nota diferente."
#: ElectronClient/gui/NoteEditor/NoteEditor.js:381
#, javascript-format
@@ -549,7 +553,7 @@ msgstr "Guardar como..."
#: ElectronClient/gui/NoteEditor/utils/contextMenu.js:65
msgid "Reveal file in folder"
msgstr ""
msgstr "Revelar arquivo na pasta"
#: ElectronClient/gui/NoteEditor/utils/contextMenu.js:73
msgid "Copy path to clipboard"
@@ -649,12 +653,15 @@ msgid ""
"may take a few minutes to complete and the app needs to be restarted. To "
"proceed please click on the link."
msgstr ""
"O alvo de sincronização deve ser atualizado antes que o Joplin possa "
"sincronizar. A operação pode demorar alguns minutos a ser completa e a "
"aplicação precisará de ser reiniciada. Para proceder, por favor clique na "
"ligação."
#: ElectronClient/gui/MainScreen/MainScreen.js:416
#: ElectronClient/gui/MainScreen/MainScreen.min.js:306
#, fuzzy
msgid "Restart and upgrade"
msgstr "Chaves mestras que necessitam de atualização"
msgstr "Reiniciar e atualizar"
#: ElectronClient/gui/MainScreen/MainScreen.js:420
#: ElectronClient/gui/MainScreen/MainScreen.min.js:313
@@ -712,11 +719,11 @@ msgstr "Procurar..."
#: ElectronClient/gui/MainScreen/commands/moveToFolder.js:17
msgid "Move to notebook"
msgstr "Mudar para o bloco de notas"
msgstr "Mudar para o caderno"
#: ElectronClient/gui/MainScreen/commands/moveToFolder.js:36
msgid "Move to notebook:"
msgstr "Mudar para o bloco de notas:"
msgstr "Mudar para o caderno:"
#: ElectronClient/gui/MainScreen/commands/setTags.js:16
#: ElectronClient/gui/SideBar/SideBar.js:426
@@ -814,9 +821,8 @@ msgid "Toggle sidebar"
msgstr "Alternar a barra lateral"
#: ElectronClient/gui/MainScreen/commands/toggleEditors.js:17
#, fuzzy
msgid "Toggle editors"
msgstr "Alternar a estrutura do editor"
msgstr "Alternar editores"
#: ElectronClient/gui/MainScreen/commands/selectTemplate.js:23
msgid "Template file:"
@@ -824,7 +830,7 @@ msgstr "Ficheiro do modelo:"
#: ElectronClient/gui/MainScreen/commands/showNoteContentProperties.js:16
msgid "Statistics..."
msgstr ""
msgstr "Estatísticas..."
#: ElectronClient/gui/EncryptionConfigScreen.min.js:96
#: ElectronClient/gui/KeymapConfig/ShortcutRecorder.js:49
@@ -1148,13 +1154,12 @@ msgstr ""
#: ElectronClient/gui/NoteList/NoteList.min.js:151
#: ElectronClient/gui/NoteList/NoteList.js:160
msgid "Custom order"
msgstr ""
msgstr "Ordem personalizada"
#: ElectronClient/gui/NoteList/NoteList.min.js:151
#: ElectronClient/gui/NoteList/NoteList.js:160
#, fuzzy
msgid "View"
msgstr "&Ver"
msgstr "Ver"
#: ElectronClient/gui/NoteList/NoteList.min.js:151
#: ElectronClient/gui/NoteList/NoteList.js:160
@@ -1169,12 +1174,13 @@ msgid ""
"To manually sort the notes, the sort order must be changed to \"%s\" in the "
"menu \"%s\" > \"%s\""
msgstr ""
"Para ordenar as notas manualmente, a ordem deve ser alterada para \"%s\" no "
"menu \"%s\" > \"%s\""
#: ElectronClient/gui/NoteList/NoteList.min.js:152
#: ElectronClient/gui/NoteList/NoteList.js:161
#, fuzzy
msgid "Do it now"
msgstr "Obter agora:"
msgstr "Fazer agora"
#: ElectronClient/gui/NoteList/NoteList.min.js:423
#: ElectronClient/gui/NoteList/NoteList.js:412
@@ -1287,9 +1293,8 @@ msgid "Options"
msgstr "Opções"
#: ElectronClient/gui/MenuBar.js:266
#, fuzzy
msgid "Note attachments..."
msgstr "Anexos"
msgstr "Anexos das notas..."
#: ElectronClient/gui/MenuBar.js:296 ElectronClient/gui/MenuBar.js:366
#: ElectronClient/gui/MenuBar.js:659
@@ -1320,9 +1325,8 @@ msgid "Import"
msgstr "Importar"
#: ElectronClient/gui/MenuBar.js:343
#, fuzzy
msgid "Export all"
msgstr "Exportar"
msgstr "Exportar todos"
#: ElectronClient/gui/MenuBar.js:356
#, javascript-format
@@ -1360,9 +1364,8 @@ msgid "Zoom Out"
msgstr "Reduzir"
#: ElectronClient/gui/MenuBar.js:516
#, fuzzy
msgid "&Note"
msgstr "Nota"
msgstr "&Nota"
#: ElectronClient/gui/MenuBar.js:525
msgid "&Tools"
@@ -1399,44 +1402,42 @@ msgid "Dropbox Login"
msgstr "Acesso Dropbox"
#: ElectronClient/gui/Root.js:105 ElectronClient/gui/Root.min.js:105
#, fuzzy
msgid "Note attachments"
msgstr "Anexos"
msgstr "Anexos das notas"
#: ElectronClient/gui/KeymapConfig/ShortcutRecorder.js:48
msgid "Press the shortcut"
msgstr ""
msgstr "Prima o atalho"
#: ElectronClient/gui/KeymapConfig/ShortcutRecorder.js:48
msgid ""
"Press the shortcut and then press ENTER. Or, press BACKSPACE to clear the "
"shortcut."
msgstr ""
"Prima o atalho e de seguida prima ENTER. Ou então, prima BACKSPACE para "
"apagar o atalho."
#: ElectronClient/gui/KeymapConfig/KeymapConfigScreen.js:62
#: ReactNativeClient/lib/services/KeymapService.js:142
#, fuzzy, javascript-format
#, javascript-format
msgid "Error: %s"
msgstr "Erro"
msgstr "Erro: %s"
#: ElectronClient/gui/KeymapConfig/KeymapConfigScreen.js:125
msgid "Command"
msgstr ""
msgstr "Comando"
#: ElectronClient/gui/KeymapConfig/KeymapConfigScreen.js:126
#, fuzzy
msgid "Keyboard Shortcut"
msgstr "Modo de Teclado"
msgstr "Atalhos de Teclado"
#: ElectronClient/gui/KeymapConfig/utils/getLabel.js:24
#, fuzzy
msgid "Hide Joplin"
msgstr "Sobre o Joplin"
msgstr "Esconder o Joplin"
#: ElectronClient/gui/KeymapConfig/utils/getLabel.js:28
#, fuzzy
msgid "Preferences"
msgstr "Preferências..."
msgstr "Preferências"
#: ElectronClient/gui/NoteContentPropertiesDialog.js:77
msgid "Words"
@@ -1471,17 +1472,18 @@ msgstr "Visualizador"
#: ElectronClient/gui/NoteContentPropertiesDialog.js:106
#, javascript-format
msgid "Read time: %s min"
msgstr ""
msgstr "Tempo de leitura: %s min"
#: ElectronClient/gui/NoteContentPropertiesDialog.js:109
#, fuzzy
msgid "Statistics"
msgstr "Estado"
msgstr "Estatísticas"
#: ElectronClient/bridge.js:177
msgid ""
"The app is now going to close. Please relaunch it to complete the process."
msgstr ""
"A aplicação vai fechar. Por favor volte a executá-la para completar o "
"processo."
#: ElectronClient/app.js:340
#, javascript-format
@@ -1493,9 +1495,8 @@ msgid "Exit"
msgstr "Sair"
#: ElectronClient/commands/copyDevCommand.js:17
#, fuzzy
msgid "Copy dev mode command to clipboard"
msgstr "Copiar caminho para a área de transferência"
msgstr "Copiar comando de modo dev para a área de transferências"
#: ElectronClient/commands/startExternalEditing.js:18
msgid "Edit in external editor"
@@ -1507,13 +1508,12 @@ msgid "Error opening note in editor: %s"
msgstr "Erro a abrir a nota no editor: %s"
#: ElectronClient/commands/toggleExternalEditing.js:16
#, fuzzy
msgid "Toggle external editing"
msgstr "Parar a edição externa"
msgstr "Alternar edição externa"
#: ElectronClient/commands/toggleExternalEditing.js:42
msgid "Stop"
msgstr ""
msgstr "Parar"
#: ElectronClient/commands/stopExternalEditing.js:16
msgid "Stop external editing"
@@ -1649,8 +1649,8 @@ msgid ""
msgstr ""
"Em qualquer comando, uma nota ou caderno pode ser indicada pelo título ou "
"ID, ou através dos atalhos `$n` ou `$b` para, respetivamente, a nota ou "
"bloco de notas atualmente selecionado. O `$c` pode ser usado para indicar o "
"item atualmente selecionado."
"caderno atualmente selecionado. O `$c` pode ser usado para indicar o item "
"atualmente selecionado."
#: CliClient/app/command-help.js:79
msgid "To move from one pane to another, press Tab or Shift+Tab."
@@ -1743,7 +1743,7 @@ msgstr ""
#: CliClient/app/command-sync.js:35
msgid "Upgrade the sync target to the latest version."
msgstr ""
msgstr "Atualize o alvo de sincronização para a última versão."
#: CliClient/app/command-sync.js:105
#, javascript-format
@@ -1771,9 +1771,8 @@ msgid "Synchronisation target: %s (%s)"
msgstr "Destino de sincronização: %s (%s)"
#: CliClient/app/command-sync.js:177
#, fuzzy
msgid "Cannot initialise synchroniser."
msgstr "Não é possível alterar item encriptado."
msgstr "Não é possível inicializar o sincronizador."
#: CliClient/app/command-sync.js:207
msgid "Starting synchronisation..."
@@ -1916,9 +1915,8 @@ msgstr ""
"desencriptados em segundo plano e estarão disponíveis brevemente."
#: CliClient/app/gui/NoteWidget.js:50
#, fuzzy
msgid "You may also type `status` for more information."
msgstr "Não peça confirmação."
msgstr "Pode também escrever `status` para mais informação."
#: CliClient/app/gui/FolderListWidget.js:31
msgid "Search:"
@@ -1962,14 +1960,16 @@ msgstr ""
"vários minutos, dependendo de quanto há para desencriptar."
#: CliClient/app/command-e2ee.js:53
#, fuzzy, javascript-format
#, javascript-format
msgid "Decrypted items: %d"
msgstr "Itens desencriptados: %s / %s"
msgstr "Itens desencriptados: %d"
#: CliClient/app/command-e2ee.js:54
#, javascript-format
msgid "Skipped items: %d (use --retry-failed-items to retry decrypting them)"
msgstr ""
"Itens ignorados: %d (use --retry-failed-items para tentar desencriptá-los "
"novamente)"
#: CliClient/app/command-e2ee.js:68
msgid "Completed decryption."
@@ -2018,9 +2018,9 @@ msgid "Do not ask for confirmation."
msgstr "Não peça confirmação."
#: CliClient/app/command-import.js:27
#, fuzzy, javascript-format
#, javascript-format
msgid "Output format: %s"
msgstr "Formato da origem: %s"
msgstr "Formato da saída: %s"
#: CliClient/app/command-import.js:65
msgid "Importing notes..."
@@ -2051,6 +2051,8 @@ msgstr "Exibe um resumo sobre as notas e os cadernos."
msgid ""
"To retry decryption of these items. Run `e2ee decrypt --retry-failed-items`"
msgstr ""
"Para tentar desencriptar estes itens novamente. Execute `e2ee decrypt --"
"retry-failed-items`"
#: CliClient/app/command-undone.js:12
msgid "Marks a to-do as non-completed."
@@ -2244,14 +2246,17 @@ msgid "HTML Directory"
msgstr "Diretório HTML"
#: ReactNativeClient/lib/services/interop/InteropService.js:127
#, fuzzy, javascript-format
#, javascript-format
msgid "Cannot load \"%s\" module for format \"%s\" and output \"%s\""
msgstr "Não é possível carregar o módulo \"%s\" para o formato \"%s\"."
msgstr ""
"Não é possível carregar o módulo \"%s\" para o formato \"%s\" e saída \"%s\""
#: ReactNativeClient/lib/services/interop/InteropService.js:152
#, fuzzy, javascript-format
#, javascript-format
msgid "Cannot load \"%s\" module for format \"%s\" and target \"%s\""
msgstr "Não é possível carregar o módulo \"%s\" para o formato \"%s\"."
msgstr ""
"Não é possível carregar o módulo \"%s\" para o formato \"%s\" e o alvo \"%s"
"\"."
#: ReactNativeClient/lib/services/interop/InteropService.js:187
#, javascript-format
@@ -2269,35 +2274,37 @@ msgstr "Notas Recuperadas"
#: ReactNativeClient/lib/services/KeymapService.js:236
msgid "command"
msgstr ""
msgstr "comando"
#: ReactNativeClient/lib/services/KeymapService.js:236
#: ReactNativeClient/lib/services/KeymapService.js:241
#, javascript-format
msgid "\"%s\" is missing the required \"%s\" property."
msgstr ""
msgstr "Está em falta a propriedade \"%s\" de \"%s\"."
#: ReactNativeClient/lib/services/KeymapService.js:241
#: ReactNativeClient/lib/services/KeymapService.js:248
msgid "accelerator"
msgstr ""
msgstr "acelerador"
#: ReactNativeClient/lib/services/KeymapService.js:248
#, fuzzy, javascript-format
msgid "Invalid %s: %s."
msgstr "Resposta inválida: %s"
msgstr "\"%s\" inválida: %s"
#: ReactNativeClient/lib/services/KeymapService.js:266
#, javascript-format
#, fuzzy, javascript-format
msgid ""
"Accelerator \"%s\" is used for \"%s\" and \"%s\" commands. This may lead to "
"unexpected behaviour."
msgstr ""
"O acelerador \"%s\" é usado para comandos \"%s\" e \"%s\". Isto pode levar a "
"comportamentos inesperados."
#: ReactNativeClient/lib/services/KeymapService.js:291
#, javascript-format
#, fuzzy, javascript-format
msgid "Accelerator \"%s\" is not valid."
msgstr ""
msgstr "O acelerador \"%s\" não é válido."
#: ReactNativeClient/lib/services/report.js:121
msgid "Items that cannot be synchronised"
@@ -2309,9 +2316,9 @@ msgid ""
"target. In order to find these items, either search for the title or the ID "
"(which is displayed in brackets above)."
msgstr ""
"Esses itens permanecerão no dispositivo, mas não serão enviados para o "
"destino de sincronização. Para encontrar estes itens, procure o título ou o "
"ID (que é apresentado entre parênteses acima)."
"Esses itens permanecerão no dispositivo, mas não serão enviados para o alvo "
"de sincronização. Para encontrar estes itens, procure o título ou o ID (que "
"é apresentado entre parênteses acima)."
#: ReactNativeClient/lib/services/report.js:130
#, javascript-format
@@ -2447,7 +2454,7 @@ msgstr "Versão do Perfil: %s"
#: ReactNativeClient/lib/versionInfo.js:23
#, javascript-format
msgid "Keychain Supported: %s"
msgstr ""
msgstr "Porta-Chaves Suportado: %s"
#: ReactNativeClient/lib/JoplinServerApi.js:71
#, javascript-format
@@ -2849,7 +2856,7 @@ msgstr "Adicionar título"
#: ReactNativeClient/lib/components/screens/UpgradeSyncTargetScreen.js:42
msgid "Sync Target Upgrade"
msgstr ""
msgstr "Atualização do Alvo de Sincronização"
#: ReactNativeClient/lib/components/screens/encryption-config.js:119
#, javascript-format
@@ -2877,7 +2884,7 @@ msgid ""
"the data! To enable encryption, please enter your password below."
msgstr ""
"Ativar a encriptação significa que *todas* as suas notas e anexos serão "
"ressincronizados e enviados encriptados para o destino de sincronização. Não "
"ressincronizados e enviados encriptados para o alvo de sincronização. Não "
"perca a palavra-passe pois, por razões de segurança, esta será a única forma "
"de desencriptar os dados! Para ativar a encriptação, introduza a sua palavra-"
"passe abaixo."
@@ -2939,8 +2946,11 @@ msgstr ""
"Alguns itens não puderam ser sincronizados. Prima para mais informações."
#: ReactNativeClient/lib/components/screen-header.js:453
#, fuzzy
msgid "The sync target needs to be upgraded. Press this banner to proceed."
msgstr ""
"O alvo de sincronização precisa de ser atualizado. Clique neste banner para "
"proceder."
#: ReactNativeClient/lib/components/side-menu-content.js:126
#, javascript-format
@@ -3021,7 +3031,7 @@ msgid ""
"the sync target is accessible. The reported error was:"
msgstr ""
"Erro. Por favor verifique se o endereço, nome de utilizador, palavra-passe, "
"etc. estão corretos e se o destino de sincronização está acessível. O erro "
"etc. estão corretos e se o alvo de sincronização está acessível. O erro "
"reportado foi:"
#: ReactNativeClient/lib/components/note-list.js:97
@@ -3086,17 +3096,20 @@ msgid "Downloaded"
msgstr "Transferido"
#: ReactNativeClient/lib/models/Resource.js:371
#, fuzzy, javascript-format
#, javascript-format
msgid "Attachment conflict: \"%s\""
msgstr "Anexos"
msgstr "Anexos em conflito: \"%s\""
#: ReactNativeClient/lib/models/Resource.js:372
#, fuzzy, javascript-format
#, javascript-format
msgid ""
"There was a [conflict](%s) on the attachment below.\n"
"\n"
"%s"
msgstr "Ocorreu um erro ao transferir este anexo:"
msgstr ""
"Ocorreu um [conflito](%s) no anexo em baixo.\n"
"\n"
"%s"
#: ReactNativeClient/lib/models/BaseItem.js:721
msgid "Encrypted"
@@ -3104,7 +3117,7 @@ msgstr "Encriptado"
#: ReactNativeClient/lib/models/BaseItem.js:781
msgid "Encrypted items cannot be modified"
msgstr "Não é possível modificar tens encriptados"
msgstr "Não é possível modificar itens encriptados"
#: ReactNativeClient/lib/models/Note.js:27
msgid "created date"
@@ -3112,7 +3125,7 @@ msgstr "data criada"
#: ReactNativeClient/lib/models/Note.js:28
msgid "custom order"
msgstr ""
msgstr "ordem personalizada"
#: ReactNativeClient/lib/models/Note.js:92
msgid "This note does not have geolocation information."
@@ -3129,20 +3142,18 @@ msgid "Cannot move note to \"%s\" notebook"
msgstr "Não é possível mover a nota para o caderno \"%s\""
#: ReactNativeClient/lib/models/Setting.js:65
#, fuzzy
msgid "yes"
msgstr "Sim"
msgstr "sim"
#: ReactNativeClient/lib/models/Setting.js:65
#: ReactNativeClient/lib/models/Setting.js:66
#, javascript-format
msgid "(wysiwyg: %s)"
msgstr ""
msgstr "(wysiwyg: %s)"
#: ReactNativeClient/lib/models/Setting.js:66
#, fuzzy
msgid "no"
msgstr "n"
msgstr "não"
#: ReactNativeClient/lib/models/Setting.js:68
#, javascript-format
@@ -3181,7 +3192,7 @@ msgstr "Nórdico"
#: ReactNativeClient/lib/models/Setting.js:80
msgid "Aritim Dark"
msgstr ""
msgstr "Escuro Aritim"
#: ReactNativeClient/lib/models/Setting.js:81
msgid "OLED Dark"
@@ -3196,8 +3207,8 @@ msgid ""
"The target to synchonise to. Each sync target may have additional parameters "
"which are named as `sync.NUM.NAME` (all documented below)."
msgstr ""
"O destino para a sincronização. Cada destino de sincronização pode ter "
"parâmetros adicionais que são designados como `sync.NUM.NUM.NAME` (todos "
"O destino para a sincronização. Cada alvo de sincronização pode ter "
"parâmetros adicionais que são designados como `sync.NUM.NAME` (todos "
"documentados abaixo)."
#: ReactNativeClient/lib/models/Setting.js:131
@@ -3230,15 +3241,15 @@ msgstr "Palavra-passe WebDAV"
#: ReactNativeClient/lib/models/Setting.js:214
msgid "AWS S3 bucket"
msgstr ""
msgstr "Bucket AWS S3"
#: ReactNativeClient/lib/models/Setting.js:225
msgid "AWS key"
msgstr ""
msgstr "Chave AWS"
#: ReactNativeClient/lib/models/Setting.js:235
msgid "AWS secret"
msgstr ""
msgstr "Segredo AWS"
#: ReactNativeClient/lib/models/Setting.js:247
msgid "Attachment download behaviour"
@@ -3250,10 +3261,9 @@ msgid ""
"In \"Auto\", they are downloaded when you open the note. In \"Always\", all "
"the attachments are downloaded whether you open the note or not."
msgstr ""
"No modo \"Manual\", os anexos são transferidos apenas quando é dado um "
"clique neles. Em \"Automático\", eles são transferidos quando a nota é "
"aberta. Em \"Sempre\", todos os anexos são transferidos, quer a nota seja "
"aberta ou não."
"No modo \"Manual\", os anexos são transferidos apenas quando são clicados. "
"Em \"Automático\", eles são transferidos quando a nota é aberta. Em \"Sempre"
"\", todos os anexos são transferidos, quer a nota seja aberta ou não."
#: ReactNativeClient/lib/models/Setting.js:251
msgid "Always"
@@ -3289,15 +3299,15 @@ msgstr "Tema"
#: ReactNativeClient/lib/models/Setting.js:337
msgid "Automatically switch theme to match system theme"
msgstr ""
msgstr "Mudar automaticamente o tema para combinar com o tema do sistema"
#: ReactNativeClient/lib/models/Setting.js:348
msgid "Preferred light theme"
msgstr ""
msgstr "Tema claro preferido"
#: ReactNativeClient/lib/models/Setting.js:361
msgid "Preferred dark theme"
msgstr ""
msgstr "Tema escuro preferido"
#: ReactNativeClient/lib/models/Setting.js:365
msgid "Show note counts"
@@ -3460,15 +3470,14 @@ msgid "Editor font family"
msgstr "Família da letra do editor"
#: ReactNativeClient/lib/models/Setting.js:556
#, fuzzy
msgid ""
"This should be a *monospace* font or some elements will render incorrectly. "
"If the font is incorrect or empty, it will default to a generic monospace "
"font."
msgstr ""
"Este deverá ser um tipo de letra *mono-espaçado* ou não funcionará "
"corretamente. Se o tipo de letra estiver incorreto ou em branco, será pré-"
"definida para um tipo de letra mono-espaçado genérico."
"corretamente. Se o tipo de letra estiver incorreto ou em branco, reverterá "
"para um tipo de letra mono-espaçado genérico pré-definido."
#: ReactNativeClient/lib/models/Setting.js:595
msgid "Custom stylesheet for Joplin-wide app styles"
@@ -3482,7 +3491,7 @@ msgstr "Atualizar a aplicação automaticamente"
#: ReactNativeClient/lib/models/Setting.js:601
msgid "Get pre-releases when checking for updates"
msgstr "Obtenha versões de pré-lançamento ao verificar atualizações"
msgstr "Obtenha versões de pré-lançamento ao verificar se há atualizações"
#: ReactNativeClient/lib/models/Setting.js:601
#, javascript-format
@@ -3491,7 +3500,7 @@ msgstr "Consulte a página de pré-lançamento para obter mais detalhes: %s"
#: ReactNativeClient/lib/models/Setting.js:609
msgid "Synchronisation interval"
msgstr "Periodicidade de sincronização"
msgstr "Intervalo de sincronização"
#: ReactNativeClient/lib/models/Setting.js:613
#: ReactNativeClient/lib/models/Setting.js:614
@@ -3610,8 +3619,8 @@ msgid ""
"Fail-safe: Do not wipe out local data when sync target is empty (often the "
"result of a misconfiguration or bug)"
msgstr ""
"À prova de falhas: Não elimine os dados locais quando o destino de "
"sincronização está em brancp (muitas vezes o resultado de uma má "
"Segurança contra falhas: Não elimine os dados locais quando o alvo de "
"sincronização está em branco (muitas vezes o resultado de uma má "
"configuração ou erro)"
#: ReactNativeClient/lib/models/Setting.js:695
@@ -3641,7 +3650,7 @@ msgstr "Manter histórico de notas por"
#: ReactNativeClient/lib/models/Setting.js:735
msgid "Notebook list growth factor"
msgstr ""
msgstr "Fator de crescimento do caderno"
#: ReactNativeClient/lib/models/Setting.js:736
#: ReactNativeClient/lib/models/Setting.js:748
@@ -3652,14 +3661,18 @@ msgid ""
"item with a factor of 2 will take twice as much space as an item with a "
"factor of 1.Restart app to see changes."
msgstr ""
"A propriedade fator define como um item aumentará ou diminuirá para ocupar o "
"espaço disponível no seu contentor com respeito aos outros itens. Como tal, "
"um item com um fator de 2 ocupará o dobro do espaço de um item com um fator "
"de 1. Reinicie a aplicação para ver as alterações."
#: ReactNativeClient/lib/models/Setting.js:747
msgid "Note list growth factor"
msgstr ""
msgstr "Fator de crescimento da lista de notas"
#: ReactNativeClient/lib/models/Setting.js:759
msgid "Note area growth factor"
msgstr ""
msgstr "Fator de crescimento da área de notas"
#: ReactNativeClient/lib/models/Setting.js:1272
msgid "General"
@@ -3694,9 +3707,8 @@ msgid "Web Clipper"
msgstr "Recorte Web"
#: ReactNativeClient/lib/models/Setting.js:1292
#, fuzzy
msgid "Keyboard Shortcuts"
msgstr "Modo de Teclado"
msgstr "Atalhos do Teclado"
#: ReactNativeClient/lib/models/Setting.js:1299
msgid ""
@@ -3708,6 +3720,12 @@ msgid ""
"formatting. It is indicated below which plugins are compatible or not with "
"the WYSIWYG editor."
msgstr ""
"Estes plugins modificam o renderizador de Markdown com recursos adicionais. "
"Note que, enquanto estes recursos podem ser úteis, não são Markdown padrão "
"e, como tal, a maioria deles só funcionará no Joplin. Adicionalmente, alguns "
"deles são *incompatíveis* com o editor WYSIWYG. Se abrir uma nota que use um "
"destes plugins nesse editor, perderá a formatação do plugin. Está indicado "
"abaixo quais os plugins que são ou não compatíveis com o editor WYSIWYG."
#: ReactNativeClient/lib/models/Setting.js:1301
#, javascript-format
@@ -3736,11 +3754,11 @@ msgstr "OneDrive"
#: ReactNativeClient/lib/SyncTargetAmazonS3.js:28
msgid "AWS S3"
msgstr ""
msgstr "AWS S3"
#: ReactNativeClient/lib/commands/historyForward.js:16
msgid "Forward"
msgstr ""
msgstr "Avançar"
#: ReactNativeClient/lib/shim-init-node.js:158
#, javascript-format

View File

@@ -4,7 +4,7 @@ require('app-module-path').addPath(__dirname);
const os = require('os');
const { time } = require('lib/time-utils.js');
const { filename } = require('lib/path-utils.js');
const { filename } = require('lib/path-utils');
const { asyncTest, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('test-utils.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');

View File

@@ -4,7 +4,7 @@ require('app-module-path').addPath(__dirname);
const os = require('os');
const { time } = require('lib/time-utils.js');
const { filename } = require('lib/path-utils.js');
const { filename } = require('lib/path-utils');
const { asyncTest, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('test-utils.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');

View File

@@ -4,7 +4,7 @@ require('app-module-path').addPath(__dirname);
const os = require('os');
const { time } = require('lib/time-utils.js');
const { filename } = require('lib/path-utils.js');
const { filename } = require('lib/path-utils');
const { asyncTest, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('test-utils.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');

View File

@@ -1,7 +1,7 @@
require('app-module-path').addPath(__dirname);
const { asyncTest } = require('test-utils.js');
const MarkupToHtml = require('lib/joplin-renderer/MarkupToHtml');
const MarkupToHtml = require('lib/joplin-renderer/MarkupToHtml').default;
describe('MarkupToHtml', function() {

View File

@@ -1,24 +1,11 @@
/* eslint-disable no-unused-vars */
require('app-module-path').addPath(__dirname);
const os = require('os');
const { time } = require('lib/time-utils.js');
const { filename } = require('lib/path-utils.js');
const { asyncTest, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('test-utils.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const BaseModel = require('lib/BaseModel.js');
const { filename } = require('lib/path-utils');
const { asyncTest, setupDatabaseAndSynchronizer, switchClient } = require('test-utils.js');
const shim = require('lib/shim').default;
const MdToHtml = require('lib/joplin-renderer/MdToHtml');
const { enexXmlToMd } = require('lib/import-enex-md-gen.js');
const MdToHtml = require('lib/joplin-renderer/MdToHtml').default;
const { themeStyle } = require('lib/theme');
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
function newTestMdToHtml(options = null) {
function newTestMdToHtml(options:any = null) {
options = {
ResourceModel: {
isResourceUrl: () => false,
@@ -32,7 +19,7 @@ function newTestMdToHtml(options = null) {
describe('MdToHtml', function() {
beforeEach(async (done) => {
beforeEach(async (done:Function) => {
await setupDatabaseAndSynchronizer(1);
await switchClient(1);
done();
@@ -52,14 +39,14 @@ describe('MdToHtml', function() {
// if (mdFilename !== 'sanitize_9.md') continue;
const mdToHtmlOptions = {
const mdToHtmlOptions:any = {
bodyOnly: true,
};
if (mdFilename === 'checkbox_alternative.md') {
mdToHtmlOptions.plugins = {
checkbox: {
renderingType: 2,
checkboxRenderingType: 2,
},
};
}
@@ -96,7 +83,7 @@ describe('MdToHtml', function() {
}));
it('should return enabled plugin assets', asyncTest(async () => {
const pluginOptions = {};
const pluginOptions:any = {};
const pluginNames = MdToHtml.pluginNames();
for (const n of pluginNames) pluginOptions[n] = { enabled: false };
@@ -126,7 +113,7 @@ describe('MdToHtml', function() {
// In this case, the HTML contains both the style and
// the rendered markdown wrapped in a DIV.
const result = await mdToHtml.render('just **testing**');
expect(result.cssStrings.length).toBe(0);
expect(result.cssStrings.length).toBeGreaterThan(0);
expect(result.html.indexOf('rendered-md') >= 0).toBe(true);
}));
@@ -137,7 +124,7 @@ describe('MdToHtml', function() {
// with no wrapper and no style.
// The style is instead in the cssStrings property.
const result = await mdToHtml.render('just **testing**', null, { bodyOnly: true });
expect(result.cssStrings.length).toBe(1);
expect(result.cssStrings.length).toBeGreaterThan(0);
expect(result.html.trim()).toBe('just <strong>testing</strong>');
}));
@@ -147,7 +134,7 @@ describe('MdToHtml', function() {
// It is similar to the bodyOnly option, excepts that
// the rendered Markdown is wrapped in a DIV
const result = await mdToHtml.render('just **testing**', null, { splitted: true });
expect(result.cssStrings.length).toBe(1);
expect(result.cssStrings.length).toBeGreaterThan(0);
expect(result.html.trim()).toBe('<div id="rendered-md"><p>just <strong>testing</strong></p>\n</div>');
}));

View File

@@ -0,0 +1,18 @@
import FsDriverNode from 'lib/fs-driver-node';
const { expectThrow } = require('test-utils.js');
describe('fsDriver', function() {
it('should resolveRelativePathWithinDir', () => {
const fsDriver = new FsDriverNode();
expect(fsDriver.resolveRelativePathWithinDir('/test/temp', './my/file.txt')).toBe('/test/temp/my/file.txt');
expect(fsDriver.resolveRelativePathWithinDir('/', './test')).toBe('/test');
expect(fsDriver.resolveRelativePathWithinDir('/test', 'myfile.txt')).toBe('/test/myfile.txt');
expect(fsDriver.resolveRelativePathWithinDir('/test/temp', './mydir/../test.txt')).toBe('/test/temp/test.txt');
expectThrow(() => fsDriver.resolveRelativePathWithinDir('/test/temp', '../myfile.txt'));
expectThrow(() => fsDriver.resolveRelativePathWithinDir('/test/temp', './mydir/../../test.txt'));
expectThrow(() => fsDriver.resolveRelativePathWithinDir('/test/temp', '/var/local/no.txt'));
});
});

View File

@@ -2,7 +2,7 @@
require('app-module-path').addPath(__dirname);
const { extractExecutablePath, quotePath, unquotePath, friendlySafeFilename, toFileProtocolPath } = require('lib/path-utils.js');
const { extractExecutablePath, quotePath, unquotePath, friendlySafeFilename, toFileProtocolPath } = require('lib/path-utils');
const { asyncTest, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('test-utils.js');
process.on('unhandledRejection', (reason, p) => {

View File

@@ -299,7 +299,7 @@ describe('services_KeymapService', () => {
],
[
{ command: 'showLocalSearch', accelerator: 'Option+Cmd+S' },
{ command: 'print', accelerator: 'Cmd+G' /* Default of gotoAnything */ },
{ command: 'print', accelerator: 'Cmd+P' /* Default of gotoAnything */ },
{ command: 'focusElementNoteTitle', accelerator: 'Option+Shift+Cmd+J' },
],
];
@@ -317,7 +317,7 @@ describe('services_KeymapService', () => {
],
[
{ command: 'showLocalSearch', accelerator: 'Ctrl+Alt+S' },
{ command: 'print', accelerator: 'Ctrl+G' /* Default of gotoAnything */ },
{ command: 'print', accelerator: 'Ctrl+P' /* Default of gotoAnything */ },
{ command: 'focusElementNoteTitle', accelerator: 'Ctrl+Alt+Shift+J' },
],
];

View File

@@ -1,5 +1,10 @@
import PluginRunner from '../app/services/plugins/PluginRunner';
import PluginService from 'lib/services/plugins/PluginService';
import { ContentScriptType } from 'lib/services/plugins/api/types';
import MdToHtml from 'lib/joplin-renderer/MdToHtml';
import Setting from 'lib/models/Setting';
import shim from 'lib/shim';
import uuid from 'lib/uuid';
require('app-module-path').addPath(__dirname);
const { asyncTest, setupDatabaseAndSynchronizer, switchClient, expectThrow } = require('test-utils.js');
@@ -148,4 +153,52 @@ describe('services_PluginService', function() {
}
}));
it('should register a Markdown-it plugin', asyncTest(async () => {
const contentScriptPath = `${Setting.value('tempDir')}/markdownItTestPlugin${uuid.createNano()}.js`;
await shim.fsDriver().copy(`${testPluginDir}/content_script/src/markdownItTestPlugin.js`, contentScriptPath);
const service = newPluginService();
const plugin = await service.loadPluginFromString('example', Setting.value('tempDir'), `
/* joplin-manifest:
{
"manifest_version": 1,
"name": "JS Bundle test",
"description": "JS Bundle Test plugin",
"version": "1.0.0",
"author": "Laurent Cozic",
"homepage_url": "https://joplinapp.org"
}
*/
joplin.plugins.register({
onStart: async function() {
await joplin.plugins.registerContentScript('markdownItPlugin', 'justtesting', '${contentScriptPath}');
},
});
`);
await service.runPlugin(plugin);
const contentScripts = plugin.contentScriptsByType(ContentScriptType.MarkdownItPlugin);
expect(contentScripts.length).toBe(1);
expect(!!contentScripts[0].path).toBe(true);
const contentScript = contentScripts[0];
const mdToHtml = new MdToHtml();
const module = require(contentScript.path).default;
mdToHtml.loadExtraRendererRule(contentScript.id, module({}));
const result = await mdToHtml.render([
'```justtesting',
'something',
'```',
].join('\n'));
expect(result.html.includes('JUST TESTING: something')).toBe(true);
await shim.fsDriver().remove(contentScriptPath);
}));
});

View File

@@ -1,60 +0,0 @@
/* eslint-disable no-unused-vars */
require('app-module-path').addPath(__dirname);
const { asyncTest, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('test-utils.js');
const shim = require('lib/shim').default;
const Setting = require('lib/models/Setting').default;
const KeychainService = require('lib/services/keychain/KeychainService').default;
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
function describeIfCompatible(name, fn) {
if (['win32', 'darwin'].includes(shim.platformName())) {
return describe(name, fn);
}
}
describeIfCompatible('services_KeychainService', function() {
beforeEach(async (done) => {
await setupDatabaseAndSynchronizer(1, { keychainEnabled: true });
await switchClient(1, { keychainEnabled: true });
await Setting.deleteKeychainPasswords();
done();
});
afterEach(async (done) => {
await Setting.deleteKeychainPasswords();
done();
});
it('should be enabled on macOS and Windows', asyncTest(async () => {
expect(Setting.value('keychain.supported')).toBe(1);
}));
it('should set, get and delete passwords', asyncTest(async () => {
const service = KeychainService.instance();
const isSet = await service.setPassword('zz_testunit', 'password');
expect(isSet).toBe(true);
const password = await service.password('zz_testunit');
expect(password).toBe('password');
await service.deletePassword('zz_testunit');
expect(await service.password('zz_testunit')).toBe(null);
}));
it('should save and load secure settings', asyncTest(async () => {
Setting.setObjectValue('encryption.passwordCache', 'testing', '123456');
await Setting.saveAll();
await Setting.load();
const passwords = Setting.value('encryption.passwordCache');
expect(passwords.testing).toBe('123456');
}));
});

View File

@@ -0,0 +1,94 @@
import KeychainService from 'lib/services/keychain/KeychainService';
import shim from 'lib/shim';
import Setting from 'lib/models/Setting';
const { db, asyncTest, setupDatabaseAndSynchronizer, switchClient } = require('test-utils.js');
function describeIfCompatible(name:string, fn:any) {
if (['win32', 'darwin'].includes(shim.platformName())) {
return describe(name, fn);
}
}
describeIfCompatible('services_KeychainService', function() {
beforeEach(async (done:Function) => {
await setupDatabaseAndSynchronizer(1, { keychainEnabled: true });
await switchClient(1, { keychainEnabled: true });
await Setting.deleteKeychainPasswords();
done();
});
afterEach(async (done:Function) => {
await Setting.deleteKeychainPasswords();
done();
});
it('should be enabled on macOS and Windows', asyncTest(async () => {
expect(Setting.value('keychain.supported')).toBe(1);
}));
it('should set, get and delete passwords', asyncTest(async () => {
const service = KeychainService.instance();
const isSet = await service.setPassword('zz_testunit', 'password');
expect(isSet).toBe(true);
const password = await service.password('zz_testunit');
expect(password).toBe('password');
await service.deletePassword('zz_testunit');
expect(await service.password('zz_testunit')).toBe(null);
}));
it('should save and load secure settings', asyncTest(async () => {
Setting.setObjectValue('encryption.passwordCache', 'testing', '123456');
await Setting.saveAll();
await Setting.load();
const passwords = Setting.value('encryption.passwordCache');
expect(passwords.testing).toBe('123456');
}));
it('should delete db settings if they have been saved in keychain', asyncTest(async () => {
// First save some secure settings and make sure it ends up in the databse
KeychainService.instance().enabled = false;
Setting.setValue('sync.5.password', 'password');
await Setting.saveAll();
{
// Check that it is in the database
const row = await db().selectOne('SELECT * FROM settings WHERE key = "sync.5.password"');
expect(row.value).toBe('password');
}
KeychainService.instance().enabled = true;
// Change any setting to make sure a save operation is triggered
Setting.setValue('sync.5.path', '/tmp');
// Save the settings - now db secure keys should have been cleared and moved to keychain
await Setting.saveAll();
{
// Check that it's been removed from the database
const row = await db().selectOne('SELECT * FROM settings WHERE key = "sync.5.password"');
expect(row).toBe(undefined);
}
// However we should still get it via the Setting class, since it will use the keychain
expect(Setting.value('sync.5.password')).toBe('password');
// Now do it again - because there was a bug that would cause the second attempt to save to the db instead
Setting.setValue('sync.5.username', 'john');
await Setting.saveAll();
{
// Check that it's been removed from the database
const row = await db().selectOne('SELECT * FROM settings WHERE key = "sync.5.password"');
expect(row).toBe(undefined);
}
}));
});

View File

@@ -0,0 +1,2 @@
dist/*
node_modules/

View File

@@ -0,0 +1,14 @@
# Joplin Plugin
This is a template to create a new Joplin plugin.
The main two files you will want to look at are:
- `/src/index.ts`, which contains the entry point for the plugin source code.
- `/src/manifest.json`, which is the plugin manifest. It contains information such as the plugin a name, version, etc.
The plugin is built using webpack, which create the compiled code in `/dist`. The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript.
## Building the plugin
To build the plugin, simply run `npm run dist`.

View File

@@ -0,0 +1,15 @@
import Plugin from '../Plugin';
import Joplin from './Joplin';
import Logger from 'lib/Logger';
/**
* @ignore
*/
export default class Global {
private joplin_;
private requireWhiteList_;
constructor(logger: Logger, implementation: any, plugin: Plugin, store: any);
get joplin(): Joplin;
private requireWhiteList;
require(filePath: string): any;
get process(): any;
}

View File

@@ -0,0 +1,38 @@
import Plugin from '../Plugin';
import JoplinData from './JoplinData';
import JoplinPlugins from './JoplinPlugins';
import JoplinWorkspace from './JoplinWorkspace';
import JoplinFilters from './JoplinFilters';
import JoplinCommands from './JoplinCommands';
import JoplinViews from './JoplinViews';
import JoplinInterop from './JoplinInterop';
import JoplinSettings from './JoplinSettings';
import Logger from 'lib/Logger';
/**
* This is the main entry point to the Joplin API. You can access various services using the provided accessors.
*/
export default class Joplin {
private data_;
private plugins_;
private workspace_;
private filters_;
private commands_;
private views_;
private interop_;
private settings_;
constructor(logger: Logger, implementation: any, plugin: Plugin, store: any);
get data(): JoplinData;
get plugins(): JoplinPlugins;
get workspace(): JoplinWorkspace;
/**
* @ignore
*
* Not sure if it's the best way to hook into the app
* so for now disable filters.
*/
get filters(): JoplinFilters;
get commands(): JoplinCommands;
get views(): JoplinViews;
get interop(): JoplinInterop;
get settings(): JoplinSettings;
}

View File

@@ -0,0 +1,51 @@
import { Command } from './types';
/**
* This class allows executing or registering new Joplin commands. Commands can be executed or associated with
* {@link JoplinViewsToolbarButtons | toolbar buttons} or {@link JoplinViewsMenuItems | menu items}.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/register_command)
*
* ## Executing Joplin's internal commands
*
* It is also possible to execute internal Joplin's commands which, as of now, are not well documented.
* You can find the list directly on GitHub though at the following locations:
*
* https://github.com/laurent22/joplin/tree/dev/ElectronClient/gui/MainScreen/commands
* https://github.com/laurent22/joplin/tree/dev/ElectronClient/commands
* https://github.com/laurent22/joplin/tree/dev/ElectronClient/gui/NoteEditor/commands/editorCommandDeclarations.ts
*
* To view what arguments are supported, you can open any of these files and look at the `execute()` command.
*/
export default class JoplinCommands {
/**
* <span class="platform-desktop">desktop</span> Executes the given command.
* The `props` are the arguments passed to the command, and they vary based on the command
*
* ```typescript
* // Create a new note in the current notebook:
* await joplin.commands.execute('newNote');
*
* // Create a new sub-notebook under the provided notebook
* // Note: internally, notebooks are called "folders".
* await joplin.commands.execute('newFolder', { parent_id: "SOME_FOLDER_ID" });
* ```
*/
execute(commandName: string, props?: any): Promise<any>;
/**
* <span class="platform-desktop">desktop</span> Registers a new command.
*
* ```typescript
* // Register a new commmand called "testCommand1"
*
* await joplin.commands.register({
* name: 'testCommand1',
* label: 'My Test Command 1',
* iconName: 'fas fa-music',
* execute: () => {
* alert('Testing plugin command 1');
* },
* });
* ```
*/
register(command: Command): Promise<void>;
}

View File

@@ -0,0 +1,47 @@
import { Path } from './types';
/**
* This module provides access to the Joplin data API: https://joplinapp.org/api/references/rest_api/
* This is the main way to retrieve data, such as notes, notebooks, tags, etc.
* or to update them or delete them.
*
* This is also what you would use to search notes, via the `search` endpoint.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/simple)
*
* 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.
* And each method takes these parameters:
*
* * `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.
* * `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.
* * `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.
* * `files`: (Optional) Used to create new resources and associate them with files.
*
* 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.
*
* For example:
*
* ```typescript
* // Get a note ID, title and body
* const noteId = 'some_note_id';
* const note = await joplin.data.get(['notes', noteId], { fields: ['id', 'title', 'body'] });
*
* // Get all folders
* const folders = await joplin.data.get(['folders']);
*
* // Set the note body
* await joplin.data.put(['notes', noteId], null, { body: "New note body" });
*
* // Create a new note under one of the folders
* await joplin.data.post(['notes'], null, { body: "my new note", title: "some title", parent_id: folders[0].id });
* ```
*/
export default class JoplinData {
private api_;
private pathSegmentRegex_;
private serializeApiBody;
private pathToString;
get(path: Path, query?: any): Promise<any>;
post(path: Path, query?: any, body?: any, files?: any[]): Promise<any>;
put(path: Path, query?: any, body?: any, files?: any[]): Promise<any>;
delete(path: Path, query?: any): Promise<any>;
}

View File

@@ -0,0 +1,10 @@
/**
* @ignore
*
* Not sure if it's the best way to hook into the app
* so for now disable filters.
*/
export default class JoplinFilters {
on(name: string, callback: Function): Promise<void>;
off(name: string, callback: Function): Promise<void>;
}

View File

@@ -0,0 +1,17 @@
import { ExportModule, ImportModule } from './types';
/**
* Provides a way to create modules to import external data into Joplin or to export notes into any arbitrary format.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/json_export)
*
* To implement an import or export module, you would simply define an object with various event handlers that are called
* by the application during the import/export process.
*
* See the documentation of the [[ExportModule]] and [[ImportModule]] for more information.
*
* 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/
*/
export default class JoplinInterop {
registerExportModule(module: ExportModule): Promise<void>;
registerImportModule(module: ImportModule): Promise<void>;
}

View File

@@ -0,0 +1,24 @@
import Plugin from '../Plugin';
import Logger from 'lib/Logger';
import { Script } from './types';
/**
* This class provides access to plugin-related features.
*/
export default class JoplinPlugins {
private logger;
private plugin;
constructor(logger: Logger, plugin: Plugin);
/**
* 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.
* That `onStart` method will be executed as soon as the plugin is loaded.
*
* ```typescript
* joplin.plugins.register({
* onStart: async function() {
* // Run your plugin code here
* }
* });
* ```
*/
register(script: Script): Promise<void>;
}

View File

@@ -0,0 +1,43 @@
import Plugin from '../Plugin';
import { SettingItem, SettingSection } from './types';
/**
* 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.
*
* Settings are essentially key/value pairs.
*
* 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
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/settings)
*/
export default class JoplinSettings {
private plugin_;
constructor(plugin: Plugin);
private namespacedKey;
/**
* Registers a new setting. Note that registering a setting item is dynamic and will be gone next time Joplin starts.
* What it means is that you need to register the setting every time the plugin starts (for example in the onStart event).
* 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
* reason the plugin fails to start at some point.
*/
registerSetting(key: string, settingItem: SettingItem): Promise<void>;
/**
* Registers a new setting section. Like for registerSetting, it is dynamic and needs to be done every time the plugin starts.
*/
registerSection(name: string, section: SettingSection): Promise<void>;
/**
* Gets a setting value (only applies to setting you registered from your plugin)
*/
value(key: string): Promise<any>;
/**
* Sets a setting value (only applies to setting you registered from your plugin)
*/
setValue(key: string, value: any): Promise<void>;
/**
* Gets a global setting value, including app-specific settings and those set by other plugins.
*
* The list of available settings is not documented yet, but can be found by looking at the source code:
*
* https://github.com/laurent22/joplin/blob/3539a452a359162c461d2849829d2d42973eab50/ReactNativeClient/lib/models/Setting.ts#L142
*/
globalValue(key: string): Promise<any>;
}

View File

@@ -0,0 +1,28 @@
import Plugin from '../Plugin';
import JoplinViewsDialogs from './JoplinViewsDialogs';
import JoplinViewsMenuItems from './JoplinViewsMenuItems';
import JoplinViewsMenus from './JoplinViewsMenus';
import JoplinViewsToolbarButtons from './JoplinViewsToolbarButtons';
import JoplinViewsPanels from './JoplinViewsPanels';
/**
* This namespace provides access to view-related services.
*
* 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.
* 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.
*/
export default class JoplinViews {
private store;
private plugin;
private dialogs_;
private panels_;
private menuItems_;
private menus_;
private toolbarButtons_;
private implementation_;
constructor(implementation: any, plugin: Plugin, store: any);
get dialogs(): JoplinViewsDialogs;
get panels(): JoplinViewsPanels;
get menuItems(): JoplinViewsMenuItems;
get menus(): JoplinViewsMenus;
get toolbarButtons(): JoplinViewsToolbarButtons;
}

View File

@@ -0,0 +1,36 @@
import Plugin from '../Plugin';
import { ButtonSpec, ViewHandle, ButtonId } from './types';
/**
* Allows creating and managing dialogs. A dialog is modal window that contains a webview and a row of buttons. You can update the update the webview using the `setHtml` method.
* Dialogs are hidden by default and you need to call `open()` to open them. Once the user clicks on a button, the `open` call will return and provide the button ID that was
* clicked on. There is currently no "close" method since the dialog should be thought as a modal one and thus can only be closed by clicking on one of the buttons.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/dialog)
*/
export default class JoplinViewsDialogs {
private store;
private plugin;
private implementation_;
constructor(implementation: any, plugin: Plugin, store: any);
private controller;
/**
* Creates a new dialog
*/
create(): Promise<ViewHandle>;
/**
* Displays a message box with OK/Cancel buttons. Returns the button index that was clicked - "0" for OK and "1" for "Cancel"
*/
showMessageBox(message: string): Promise<number>;
/**
* Sets the dialog HTML content
*/
setHtml(handle: ViewHandle, html: string): Promise<string>;
/**
* Sets the dialog buttons.
*/
setButtons(handle: ViewHandle, buttons: ButtonSpec[]): Promise<ButtonSpec[]>;
/**
* Opens the dialog
*/
open(handle: ViewHandle): Promise<ButtonId>;
}

View File

@@ -0,0 +1,16 @@
import { CreateMenuItemOptions, MenuItemLocation } from './types';
import Plugin from '../Plugin';
/**
* Allows creating and managing menu items.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/register_command)
*/
export default class JoplinViewsMenuItems {
private store;
private plugin;
constructor(plugin: Plugin, store: any);
/**
* 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.
*/
create(commandName: string, location?: MenuItemLocation, options?: CreateMenuItemOptions): Promise<void>;
}

View File

@@ -0,0 +1,18 @@
import { MenuItem, MenuItemLocation } from './types';
import Plugin from '../Plugin';
/**
* Allows creating menus.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/menu)
*/
export default class JoplinViewsMenus {
private store;
private plugin;
constructor(plugin: Plugin, store: any);
private registerCommandAccelerators;
/**
* 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
* menu as a sub-menu of the application build-in menus.
*/
create(label: string, menuItems: MenuItem[], location?: MenuItemLocation): Promise<void>;
}

View File

@@ -0,0 +1,30 @@
import Plugin from '../Plugin';
import { ViewHandle } from './types';
/**
* Allows creating and managing view panels. View panels currently are displayed at the right of the sidebar and allows displaying any HTML content (within a webview) and update it in real-time. For example
* it could be used to display a table of content for the active note, or display various metadata or graph.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/toc)
*/
export default class JoplinViewsPanels {
private store;
private plugin;
constructor(plugin: Plugin, store: any);
private controller;
/**
* Creates a new panel
*/
create(): Promise<ViewHandle>;
/**
* Sets the panel webview HTML
*/
setHtml(handle: ViewHandle, html: string): Promise<string>;
/**
* Adds and loads a new JS or CSS files into the panel.
*/
addScript(handle: ViewHandle, scriptPath: string): Promise<void>;
/**
* Called when a message is sent from the webview (using postMessage).
*/
onMessage(handle: ViewHandle, callback: Function): Promise<void>;
}

View File

@@ -0,0 +1,16 @@
import { ToolbarButtonLocation } from './types';
import Plugin from '../Plugin';
/**
* Allows creating and managing toolbar buttons.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/register_command)
*/
export default class JoplinViewsToolbarButtons {
private store;
private plugin;
constructor(plugin: Plugin, store: any);
/**
* Creates a new toolbar button and associate it with the given command.
*/
create(commandName: string, location: ToolbarButtonLocation): Promise<void>;
}

View File

@@ -0,0 +1,34 @@
/**
* The workspace service provides access to all the parts of Joplin that are being worked on - i.e. the currently selected notes or notebooks as well
* as various related events, such as when a new note is selected, or when the note content changes.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins)
*/
export default class JoplinWorkspace {
private store;
constructor(_implementation: any, store: any);
/**
* Called when a new note or notes are selected.
*/
onNoteSelectionChange(callback: Function): Promise<void>;
/**
* Called when the content of a note changes.
*/
onNoteContentChange(callback: Function): Promise<void>;
/**
* Called when an alarm associated with a to-do is triggered.
*/
onNoteAlarmTrigger(callback: Function): Promise<void>;
/**
* Called when the synchronisation process has finished.
*/
onSyncComplete(callback: Function): Promise<void>;
/**
* Gets the currently selected note
*/
selectedNote(): Promise<any>;
/**
* Gets the IDs of the selected notes (can be zero, one, or many). Use the data API to retrieve information about these notes.
*/
selectedNoteIds(): Promise<string[]>;
}

View File

@@ -0,0 +1,5 @@
import type Joplin from './Joplin';
declare const joplin:Joplin;
export default joplin;

View File

@@ -0,0 +1,279 @@
// =================================================================
// Command API types
// =================================================================
export interface Command {
name: string
label: string
iconName?: string,
execute(props:any):Promise<any>
isEnabled?(props:any):boolean
mapStateToProps?(state:any):any
}
// =================================================================
// Interop API types
// =================================================================
export enum FileSystemItem {
File = 'file',
Directory = 'directory',
}
export enum ImportModuleOutputFormat {
Markdown = 'md',
Html = 'html',
}
/**
* Used to implement a module to export data from Joplin. [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/CliClient/tests/support/plugins/json_export) for an example.
*
* In general, all the event handlers you'll need to implement take a `context` object as a first argument. This object will contain the export or import path as well as various optional properties, such as which notes or notebooks need to be exported.
*
* To get a better sense of what it will contain it can be useful to print it using `console.info(context)`.
*/
export interface ExportModule {
/**
* The format to be exported, eg "enex", "jex", "json", etc.
*/
format: string,
/**
* The description that will appear in the UI, for example in the menu item.
*/
description: string,
/**
* Whether the module will export a single file or multiple files in a directory. It affects the open dialog that will be presented to the user when using your exporter.
*/
target: FileSystemItem,
/**
* Only applies to single file exporters or importers
* It tells whether the format can package multiple notes into one file.
* For example JEX or ENEX can, but HTML cannot.
*/
isNoteArchive: boolean,
/**
* The extensions of the files exported by your module. For example, it is `["htm", "html"]` for the HTML module, and just `["jex"]` for the JEX module.
*/
fileExtensions?: string[],
/**
* Called when the export process starts.
*/
onInit(context:ExportContext): Promise<void>;
/**
* Called when an item needs to be processed. An "item" can be any Joplin object, such as a note, a folder, a notebook, etc.
*/
onProcessItem(context:ExportContext, itemType:number, item:any):Promise<void>;
/**
* Called when a resource file needs to be exported.
*/
onProcessResource(context:ExportContext, resource:any, filePath:string):Promise<void>;
/**
* Called when the export process is done.
*/
onClose(context:ExportContext):Promise<void>;
}
export interface ImportModule {
/**
* The format to be exported, eg "enex", "jex", "json", etc.
*/
format: string,
/**
* The description that will appear in the UI, for example in the menu item.
*/
description: string,
/**
* Only applies to single file exporters or importers
* It tells whether the format can package multiple notes into one file.
* For example JEX or ENEX can, but HTML cannot.
*/
isNoteArchive: boolean,
/**
* The type of sources that are supported by the module. Tells whether the module can import files or directories or both.
*/
sources: FileSystemItem[],
/**
* Tells the file extensions of the exported files.
*/
fileExtensions?: string[],
/**
* Tells the type of notes that will be generated, either HTML or Markdown (default).
*/
outputFormat?: ImportModuleOutputFormat,
/**
* Called when the import process starts. There is only one event handler within which you should import the complete data.
*/
onExec(context:ImportContext): Promise<void>;
}
export interface ExportOptions {
format?: string,
path?:string,
sourceFolderIds?: string[],
sourceNoteIds?: string[],
modulePath?:string,
target?:FileSystemItem,
}
export interface ExportContext {
destPath: string,
options: ExportOptions,
/**
* You can attach your own custom data using this propery - it will then be passed to each event handler, allowing you to keep state from one event to the next.
*/
userData?: any,
}
export interface ImportContext {
sourcePath: string,
options: any,
warnings: string[],
}
// =================================================================
// Misc types
// =================================================================
export interface Script {
onStart?(event:any):Promise<void>,
}
// =================================================================
// Menu types
// =================================================================
export interface CreateMenuItemOptions {
accelerator: string,
}
export enum MenuItemLocation {
File = 'file',
Edit = 'edit',
View = 'view',
Note = 'note',
Tools = 'tools',
Help = 'help',
Context = 'context',
}
export interface MenuItem {
/**
* Command that should be associated with the menu item. All menu item should
* have a command associated with them unless they are a sub-menu.
*/
commandName?: string,
/**
* Accelerator associated with the menu item
*/
accelerator?: string,
/**
* Menu items that should appear below this menu item. Allows creating a menu tree.
*/
submenu?: MenuItem[],
/**
* Menu item label. If not specified, the command label will be used instead.
*/
label?: string,
}
// =================================================================
// View API types
// =================================================================
export interface ButtonSpec {
id: ButtonId,
title?: string,
onClick?():void,
}
export type ButtonId = string;
export enum ToolbarButtonLocation {
/**
* This toolbar in the top right corner of the application. It applies to the note as a whole, including its metadata.
*/
NoteToolbar = 'noteToolbar',
/**
* This toolbar is right above the text editor. It applies to the note body only.
*/
EditorToolbar = 'editorToolbar',
}
export type ViewHandle = string;
export interface EditorCommand {
name: string;
value?: any;
}
// =================================================================
// Settings types
// =================================================================
export enum SettingItemType {
Int = 1,
String = 2,
Bool = 3,
Array = 4,
Object = 5,
Button = 6,
}
// Redefine a simplified interface to mask internal details
// and to remove function calls as they would have to be async.
export interface SettingItem {
value: any,
type: SettingItemType,
public: boolean,
label:string,
description?:string,
isEnum?: boolean,
section?: string,
options?:any,
appTypes?:string[],
secure?: boolean,
advanced?: boolean,
minimum?: number,
maximum?: number,
step?: number,
}
export interface SettingSection {
label: string,
iconName?: string,
description?: string,
name?: string,
}
// =================================================================
// Data API types
// =================================================================
/**
* An array of at least one element and at most three elements.
*
* [0]: Resource name (eg. "notes", "folders", "tags", etc.)
* [1]: (Optional) Resource ID.
* [2]: (Optional) Resource link.
*/
export type Path = string[];

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,20 @@
{
"name": "joplin_plugin",
"version": "1.0.0",
"description": "",
"scripts": {
"dist": "webpack",
"postinstall": "npm run dist"
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"@types/node": "^14.0.14",
"copy-webpack-plugin": "^6.1.0",
"ts-loader": "^7.0.5",
"typescript": "^3.9.3",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
}
}

View File

@@ -0,0 +1,7 @@
import joplin from 'api';
joplin.plugins.register({
onStart: async function() {
await (joplin.plugins as any).registerContentScript('markdownItPlugin', 'justtesting', './markdownItTestPlugin.js');
},
});

View File

@@ -0,0 +1,8 @@
{
"manifest_version": 1,
"name": "Content Script Test",
"description": "",
"version": "1.0.0",
"author": "",
"homepage_url": ""
}

View File

@@ -0,0 +1,19 @@
function plugin(markdownIt, _options) {
const defaultRender = markdownIt.renderer.rules.fence || function(tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options, env, self);
};
markdownIt.renderer.rules.fence = function(tokens, idx, options, env, self) {
const token = tokens[idx];
if (token.info !== 'justtesting') return defaultRender(tokens, idx, options, env, self);
return `JUST TESTING: ${token.content}`;
};
}
module.exports = {
default: function(_context) {
return {
plugin: plugin,
}
},
}

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"outDir": "./dist/",
"module": "commonjs",
"target": "es2015",
"jsx": "react",
"allowJs": true,
"baseUrl": "."
}
}

View File

@@ -0,0 +1,44 @@
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/index.ts',
target: 'node',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
alias: {
api: path.resolve(__dirname, 'api')
},
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new CopyPlugin({
patterns: [
{
from: "**/*",
context: path.resolve(__dirname, 'src'),
to: path.resolve(__dirname, 'dist'),
globOptions: {
ignore: [
'**/*.ts',
'**/*.tsx',
],
},
},
],
}),
],
};

View File

@@ -24,7 +24,7 @@ const { FileApiDriverDropbox } = require('lib/file-api-driver-dropbox.js');
const { FileApiDriverOneDrive } = require('lib/file-api-driver-onedrive.js');
const { FileApiDriverAmazonS3 } = require('lib/file-api-driver-amazon-s3.js');
const BaseService = require('lib/services/BaseService').default;
const { FsDriverNode } = require('lib/fs-driver-node.js');
const FsDriverNode = require('lib/fs-driver-node').default;
const { time } = require('lib/time-utils.js');
const { shimInit } = require('lib/shim-init-node.js');
const shim = require('lib/shim').default;

View File

@@ -425,7 +425,7 @@ class Application extends BaseApplication {
const contextMenu = Menu.buildFromTemplate([
{ label: _('Open %s', app.electronApp().name), click: () => { app.window().show(); } },
{ type: 'separator' },
{ label: _('Exit'), click: () => { app.quit(); } },
{ label: _('Quit'), click: () => { app.quit(); } },
]);
app.createTray(contextMenu);
}

View File

@@ -2,7 +2,7 @@ import ElectronAppWrapper from './ElectronAppWrapper';
import shim from 'lib/shim';
import { _, setLocale } from 'lib/locale';
const { dirname, toSystemSlashes } = require('lib/path-utils.js');
const { dirname, toSystemSlashes } = require('lib/path-utils');
const { BrowserWindow, nativeTheme } = require('electron');
interface LastSelectedPath {

View File

@@ -3,7 +3,7 @@ const shim = require('lib/shim').default;
const Logger = require('lib/Logger').default;
const { _ } = require('lib/locale');
const fetch = require('node-fetch');
const { fileExtension } = require('lib/path-utils.js');
const { fileExtension } = require('lib/path-utils');
const packageInfo = require('./packageInfo.js');
const compareVersions = require('compare-versions');

View File

@@ -6,7 +6,7 @@ import { _ } from 'lib/locale';
const { connect } = require('react-redux');
const Setting = require('lib/models/Setting').default;
const { themeStyle } = require('lib/theme');
const pathUtils = require('lib/path-utils.js');
const pathUtils = require('lib/path-utils');
const SyncTargetRegistry = require('lib/SyncTargetRegistry');
const shared = require('lib/components/shared/config-shared.js');
const bridge = require('electron').remote.require('./bridge').default;

View File

@@ -3,7 +3,7 @@ const { connect } = require('react-redux');
const Folder = require('lib/models/Folder.js');
const { themeStyle } = require('lib/theme');
const { _ } = require('lib/locale');
const { filename, basename } = require('lib/path-utils.js');
const { filename, basename } = require('lib/path-utils');
const { importEnex } = require('lib/import-enex');
class ImportScreenComponent extends React.Component {

View File

@@ -4,7 +4,7 @@ import { _ } from 'lib/locale';
const { themeStyle } = require('lib/theme');
const DialogButtonRow = require('./DialogButtonRow.min');
const Countable = require('countable');
const markupLanguageUtils = require('lib/markupLanguageUtils');
const markupLanguageUtils = require('lib/markupLanguageUtils').default;
interface NoteContentPropertiesDialogProps {
themeId: number,

View File

@@ -14,20 +14,18 @@ import Editor from './Editor';
import usePluginServiceRegistration from '../../utils/usePluginServiceRegistration';
import Setting from 'lib/models/Setting';
import { _ } from 'lib/locale';
import bridge from '../../../../services/bridge';
import markdownUtils from 'lib/markdownUtils';
import shim from 'lib/shim';
// @ts-ignore
const bridge = require('electron').remote.require('./bridge').default;
// @ts-ignore
const Note = require('lib/models/Note.js');
const { clipboard } = require('electron');
const shared = require('lib/components/shared/note-screen-shared.js');
const Menu = bridge().Menu;
const MenuItem = bridge().MenuItem;
const markdownUtils = require('lib/markdownUtils').default;
const { reg } = require('lib/registry.js');
const dialogs = require('../../../dialogs');
const { themeStyle } = require('lib/theme');
const shim = require('lib/shim').default;
function markupRenderOptions(override: any = null) {
return { ...override };
@@ -37,20 +35,19 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
const styles = styles_(props);
const [renderedBody, setRenderedBody] = useState<RenderedBody>(defaultRenderedBody()); // Viewer content
const [renderedBodyContentKey, setRenderedBodyContentKey] = useState<string>(null);
const [webviewReady, setWebviewReady] = useState(false);
const previousContent = usePrevious(props.content);
const previousRenderedBody = usePrevious(renderedBody);
const previousSearchMarkers = usePrevious(props.searchMarkers);
const previousContentKey = usePrevious(props.contentKey);
const editorRef = useRef(null);
const rootRef = useRef(null);
const webviewRef = useRef(null);
const props_onChangeRef = useRef<Function>(null);
props_onChangeRef.current = props.onChange;
const contentKeyHasChangedRef = useRef(false);
contentKeyHasChangedRef.current = previousContentKey !== props.contentKey;
const rootSize = useRootSize({ rootRef });
@@ -490,7 +487,10 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
useEffect(() => {
let cancelled = false;
const interval = contentKeyHasChangedRef.current ? 0 : 500;
// When a new note is loaded (contentKey is different), we want the note to be displayed
// right away. However once that's done, we put a small delay so that the view is not
// being constantly updated while the user changes the note.
const interval = renderedBodyContentKey !== props.contentKey ? 0 : 500;
const timeoutId = shim.setTimeout(async () => {
let bodyToRender = props.content;
@@ -501,15 +501,25 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
}
const result = await props.markupToHtml(props.contentMarkupLanguage, bodyToRender, markupRenderOptions({ resourceInfos: props.resourceInfos }));
if (cancelled) return;
setRenderedBody(result);
// Since we set `renderedBodyContentKey` here, it means this effect is going to
// be triggered again, but that's hard to avoid and the second call would be cheap
// anyway since the renderered markdown is cached by MdToHtml. We could use a ref
// to avoid this, but a second rendering might still happens anyway to render images,
// resources, or for other reasons. So it's best to focus on making any second call
// to this effect as cheap as possible with caching, etc.
setRenderedBodyContentKey(props.contentKey);
}, interval);
return () => {
cancelled = true;
shim.clearTimeout(timeoutId);
};
}, [props.content, props.contentMarkupLanguage, props.visiblePanes, props.resourceInfos, props.markupToHtml]);
}, [props.content, props.contentKey, renderedBodyContentKey, props.contentMarkupLanguage, props.visiblePanes, props.resourceInfos, props.markupToHtml]);
useEffect(() => {
if (!webviewReady) return;

View File

@@ -27,7 +27,7 @@ function markupRenderOptions(override:any = null) {
return {
plugins: {
checkbox: {
renderingType: 2,
checkboxRenderingType: 2,
},
link_open: {
linkRenderingType: 2,

View File

@@ -33,7 +33,7 @@ const { substrWithEllipsis } = require('lib/string-utils');
const NoteSearchBar = require('../NoteSearchBar.min.js');
const { reg } = require('lib/registry.js');
const { time } = require('lib/time-utils.js');
const markupLanguageUtils = require('lib/markupLanguageUtils');
const markupLanguageUtils = require('lib/markupLanguageUtils').default;
const usePrevious = require('lib/hooks/usePrevious').default;
const Setting = require('lib/models/Setting').default;
const Note = require('lib/models/Note.js');
@@ -150,7 +150,11 @@ function NoteEditor(props: NoteEditorProps) {
return formNote.saveActionQueue.waitForAllDone();
}
const markupToHtml = useMarkupToHtml({ themeId: props.themeId, customCss: props.customCss });
const markupToHtml = useMarkupToHtml({
themeId: props.themeId,
customCss: props.customCss,
plugins: props.plugins,
});
const allAssets = useCallback(async (markupLanguage: number): Promise<any[]> => {
const theme = themeStyle(props.themeId);

View File

@@ -1,13 +1,17 @@
import { useCallback } from 'react';
import { PluginStates } from 'lib/services/plugins/reducer';
import contentScriptsToRendererRules from 'lib/services/plugins/utils/contentScriptsToRendererRules';
import { useCallback, useMemo } from 'react';
import { ResourceInfos } from './types';
import markupLanguageUtils from 'lib/markupLanguageUtils';
import Setting from 'lib/models/Setting';
const { themeStyle } = require('lib/theme');
const Note = require('lib/models/Note');
const Setting = require('lib/models/Setting').default;
const markupLanguageUtils = require('lib/markupLanguageUtils');
interface HookDependencies {
themeId: number,
customCss: string,
plugins: PluginStates,
}
interface MarkupToHtmlOptions {
@@ -15,8 +19,15 @@ interface MarkupToHtmlOptions {
resourceInfos?: ResourceInfos,
}
export default function useMarkupToHtml(dependencies:HookDependencies) {
const { themeId, customCss } = dependencies;
export default function useMarkupToHtml(deps:HookDependencies) {
const { themeId, customCss, plugins } = deps;
const markupToHtml = useMemo(() => {
return markupLanguageUtils.newMarkupToHtml({
resourceBaseUrl: `file://${Setting.value('resourceDir')}/`,
extraRendererRules: contentScriptsToRendererRules(plugins),
});
}, [plugins]);
return useCallback(async (markupLanguage: number, md: string, options: MarkupToHtmlOptions = null): Promise<any> => {
options = {
@@ -38,10 +49,6 @@ export default function useMarkupToHtml(dependencies:HookDependencies) {
delete options.replaceResourceInternalToExternalLinks;
const markupToHtml = markupLanguageUtils.newMarkupToHtml({
resourceBaseUrl: `file://${Setting.value('resourceDir')}/`,
});
const result = await markupToHtml.render(markupLanguage, md, theme, Object.assign({}, {
codeTheme: theme.codeThemeCss,
userCss: customCss || '',
@@ -52,5 +59,5 @@ export default function useMarkupToHtml(dependencies:HookDependencies) {
}, options));
return result;
}, [themeId, customCss]);
}, [themeId, customCss, markupToHtml]);
}

View File

@@ -15,7 +15,7 @@ const { time } = require('lib/time-utils.js');
const ReactTooltip = require('react-tooltip');
const { urlDecode, substrWithEllipsis } = require('lib/string-utils');
const bridge = require('electron').remote.require('./bridge').default;
const markupLanguageUtils = require('lib/markupLanguageUtils');
const markupLanguageUtils = require('lib/markupLanguageUtils').default;
class NoteRevisionViewerComponent extends React.PureComponent {
constructor() {

View File

@@ -24,7 +24,7 @@ const MasterKey = require('lib/models/MasterKey');
const Setting = require('lib/models/Setting').default;
const Revision = require('lib/models/Revision.js');
const Logger = require('lib/Logger').default;
const { FsDriverNode } = require('lib/fs-driver-node.js');
const FsDriverNode = require('lib/fs-driver-node').default;
const { shimInit } = require('lib/shim-init-node.js');
const EncryptionService = require('lib/services/EncryptionService');
const bridge = require('electron').remote.require('./bridge').default;

View File

@@ -7,7 +7,7 @@ const electronApp = require('electron').app;
const ElectronAppWrapper = require('./ElectronAppWrapper').default;
const { initBridge } = require('./bridge');
const Logger = require('lib/Logger').default;
const { FsDriverNode } = require('lib/fs-driver-node.js');
const FsDriverNode = require('lib/fs-driver-node').default;
const envFromArgs = require('lib/envFromArgs');
process.on('unhandledRejection', (reason, p) => {

View File

@@ -1,6 +1,6 @@
{
"name": "Joplin",
"version": "1.3.6",
"version": "1.3.7",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "Joplin",
"version": "1.3.6",
"version": "1.3.7",
"description": "Joplin for Desktop",
"main": "main.js",
"scripts": {

View File

@@ -16,7 +16,7 @@ const { ItemList } = require('../gui/ItemList.min');
const HelpButton = require('../gui/HelpButton.min');
const { surroundKeywords, nextWhitespaceIndex, removeDiacritics } = require('lib/string-utils.js');
const { mergeOverlappingIntervals } = require('lib/ArrayUtils.js');
const markupLanguageUtils = require('lib/markupLanguageUtils');
const markupLanguageUtils = require('lib/markupLanguageUtils').default;
const PLUGIN_NAME = 'gotoAnything';

View File

@@ -96,11 +96,14 @@ export default class PluginRunner extends BasePluginRunner {
if (message.pluginId !== plugin.id) return;
const mappedArgs = mapEventIdsToHandlers(plugin.id, message.args);
const fullPath = `joplin.${message.path}`;
this.logger().debug(`PluginRunner: execute call: ${fullPath}: ${mappedArgs}`);
let result:any = null;
let error:any = null;
try {
result = await executeSandboxCall(plugin.id, pluginApi, `joplin.${message.path}`, mappedArgs, this.eventHandler);
result = await executeSandboxCall(plugin.id, pluginApi, fullPath, mappedArgs, this.eventHandler);
} catch (e) {
error = e ? e : new Error('Unknown error');
}

View File

@@ -10,7 +10,7 @@ export interface Props {
onMessage:Function,
pluginId:string,
viewId:string,
themeId:string,
themeId:number,
minWidth?: number,
minHeight?: number,
fitToContent?: boolean,

View File

@@ -6,7 +6,7 @@ const { camelCaseToDash, formatCssSize } = require('lib/string-utils');
interface HookDependencies {
pluginId: string,
themeId: string,
themeId: number,
}
function themeToCssVariables(theme:any) {

View File

@@ -3,5 +3,5 @@
# This is a convenient way to build and test a plugin demo.
# It could be used to develop plugins too.
PLUGIN_PATH=/home/laurent/source/joplin/CliClient/tests/support/plugins/settings
PLUGIN_PATH=/home/laurent/source/joplin/CliClient/tests/support/plugins/content_script
npm i --prefix="$PLUGIN_PATH" && npm start -- --dev-plugins "$PLUGIN_PATH"

View File

@@ -48,7 +48,7 @@ There are other ways to install the terminal application. However, they are not
Operating system | Method
-----------------|----------------
macOS | `brew install joplin`
Arch Linux | An Arch Linux package is available [here](https://aur.archlinux.org/packages/joplin/). To install it, use an AUR wrapper such as yay: `yay -S joplin`. Both the CLI tool (type `joplin`) and desktop app (type `joplin-desktop`) are packaged. You can also install a compiled version with the [chaotic-aur](https://wiki.archlinux.org/index.php/Unofficial_user_repositories#chaotic-aur) repository. For support, please go to the [GitHub repo](https://github.com/masterkorp/joplin-pkgbuild).
Arch Linux | An Arch Linux package is available [here](https://aur.archlinux.org/packages/joplin/). To install it, use an AUR wrapper such as yay: `yay -S joplin`. Both the CLI tool (type `joplin`) and desktop app (type `joplin-desktop`) are packaged. You can also install a compiled version with the [chaotic-aur](https://wiki.archlinux.org/index.php/Unofficial_user_repositories#chaotic-aur) repository. For support, please go to the [GitHub repo](https://github.com/masterkorp/joplin-pkgbuild). If you are interested in [pre-release](https://joplinapp.org/prereleases/) you have [joplin-beta](https://aur.archlinux.org/packages/joplin-beta).
## Web Clipper
@@ -322,6 +322,9 @@ The currently supported template variables are:
# Searching
Joplin implements the SQLite Full Text Search (FTS4) extension. It means the content of all the notes is indexed in real time and search queries return results very fast. Both [Simple FTS Queries](https://www.sqlite.org/fts3.html#simple_fts_queries) and [Full-Text Index Queries](https://www.sqlite.org/fts3.html#full_text_index_queries) are supported. See below for the list of supported queries:
## Supported queries
Search type | Description | Example
------------|-------------|---------
Single word | Returns all the notes that contain this term. | For example, searching for `cat` will return all the notes that contain this exact word. Note: it will not return the notes that contain the substring - thus, for "cat", notes that contain "cataclysmic" or "prevaricate" will **not** be returned.
@@ -330,8 +333,10 @@ Phrase | Add double quotes to return the notes that contain exactly this phrase.
Prefix | Add a wildcard to return all the notes that contain a term with a specified prefix. | `swim*` - will return all the notes that contain eg. "swim", but also "swimming", "swimsuit", etc. IMPORTANT: The wildcard **can only be at the end** - it will be ignored at the beginning of a word (eg. `*swim`) and will be treated as a literal asterisk in the middle of a word (eg. `ast*rix`)
Switch to basic search | One drawback of Full Text Search is that it ignores most non-alphabetical characters. However in some cases you might want to search for this too. To do that, you can use basic search. You switch to this mode by prefixing your search with a slash `/`. This won't provide the benefits of FTS but it will allow searching exactly for what you need. Note that it can also be much slower, even extremely slow, depending on your query. | `/"- [ ]"` - will return all the notes that contain unchecked checkboxes.
## Search filters
You can also use search filters to further restrict the search.
| Operator | Description | Example |
| --- | --- | --- |
|**-**|If placed before a text term, it excludes the notes that contain that term. You can also place it before a filter to negate it. |`-spam` searches for all notes without the word `spam`.<br>`office -trash` searches for all notes with the word`office` and without the word `trash`.|
@@ -349,6 +354,14 @@ You can also use search filters to further restrict the search.
Note: In CliClient you have to escape the query using `--` when using negated filters.
Eg. `:search -- "-tag:tag1"`.
The filters are implicitely connected by and/or connective depending on the following rules;
- By default, all filters are connected by "AND".
- To override this default behaviour, use the `any` filter, in which case the search terms will be connected by "OR" instead.
- There's an exception for the `notebook` filters which are connected by "OR". The reason being that no note can be in multiple notebooks at once.
## Search order
Notes are sorted by "relevance". Currently it means the notes that contain the requested terms the most times are on top. For queries with multiple terms, it also matters how close to each other the terms are. This is a bit experimental so if you notice a search query that returns unexpected results, please report it in the forum, providing as many details as possible to replicate the issue.
# Goto Anything

View File

@@ -1,5 +1,5 @@
import shim from 'lib/shim';
const { dirname } = require('lib/path-utils.js');
const { dirname } = require('lib/path-utils');
const Setting = require('lib/models/Setting').default;
const pluginAssets = require('./pluginAssets/index');
const KvStore = require('lib/services/KvStore.js');

View File

@@ -43,7 +43,7 @@ const DecryptionWorker = require('lib/services/DecryptionWorker');
const { loadKeychainServiceAndSettings } = require('lib/services/SettingUtils');
const KvStore = require('lib/services/KvStore');
const MigrationService = require('lib/services/MigrationService');
const { toSystemSlashes } = require('lib/path-utils.js');
const { toSystemSlashes } = require('lib/path-utils');
const { setAutoFreeze } = require('immer');
// const ntpClient = require('lib/vendor/ntp-client');
@@ -702,7 +702,9 @@ export default class BaseApplication {
initArgs = Object.assign(initArgs, extraFlags);
this.logger_.addTarget(TargetType.File, { path: `${profileDir}/log.txt` });
// this.logger_.addTarget(TargetType.Console, { level: Logger.LEVEL_DEBUG });
if (Setting.value('env') === 'dev' && !shim.isTestingEnv()) {
// this.logger_.addTarget(TargetType.Console, { level: Logger.LEVEL_DEBUG });
}
this.logger_.setLevel(initArgs.logLevel);
reg.setLogger(this.logger_);

View File

@@ -2,7 +2,7 @@ import shim from 'lib/shim';
import { _ } from 'lib/locale';
const Logger = require('lib/Logger').default;
const JoplinError = require('lib/JoplinError');
const { rtrimSlashes } = require('lib/path-utils.js');
const { rtrimSlashes } = require('lib/path-utils');
const base64 = require('base-64');
interface JoplinServerApiOptions {

View File

@@ -41,6 +41,8 @@ class SyncTargetAmazonS3 extends BaseSyncTarget {
accessKeyId: Setting.value('sync.8.username'),
secretAccessKey: Setting.value('sync.8.password'),
s3UseArnRegion: true, // override the request region with the region inferred from requested resource's ARN
s3ForcePathStyle: true,
endpoint: Setting.value('sync.8.url'),
};
}
@@ -56,6 +58,8 @@ class SyncTargetAmazonS3 extends BaseSyncTarget {
accessKeyId: options.username(),
secretAccessKey: options.password(),
s3UseArnRegion: true,
s3ForcePathStyle: true,
endpoint: options.url(),
};
const api = new S3(apiOptions);

View File

@@ -3,7 +3,7 @@ const shim = require('lib/shim').default;
const parseXmlString = require('xml2js').parseString;
const JoplinError = require('lib/JoplinError');
const URL = require('url-parse');
const { rtrimSlashes } = require('lib/path-utils.js');
const { rtrimSlashes } = require('lib/path-utils');
const base64 = require('base-64');

View File

@@ -2,7 +2,7 @@ import { useEffect, useState, useMemo } from 'react';
import shim from 'lib/shim';
import Setting from 'lib/models/Setting';
const { themeStyle } = require('lib/components/global-style.js');
const markupLanguageUtils = require('lib/markupLanguageUtils');
const markupLanguageUtils = require('lib/markupLanguageUtils').default;
const { assetsToHeaders } = require('lib/joplin-renderer');
interface Source {

View File

@@ -22,7 +22,7 @@ const { BackButtonService } = require('lib/services/back-button.js');
const NavService = require('lib/services/NavService.js');
const BaseModel = require('lib/BaseModel.js');
const { ActionButton } = require('lib/components/action-button.js');
const { fileExtension, safeFileExtension } = require('lib/path-utils.js');
const { fileExtension, safeFileExtension } = require('lib/path-utils');
const mimeUtils = require('lib/mime-utils.js').mime;
const { ScreenHeader } = require('lib/components/screen-header.js');
const NoteTagsDialog = require('lib/components/screens/NoteTagsDialog');

View File

@@ -1,5 +1,5 @@
const moment = require('moment');
const { dirname, basename } = require('lib/path-utils.js');
const { dirname, basename } = require('lib/path-utils');
const shim = require('lib/shim').default;
class FileApiDriverOneDrive {

View File

@@ -1,5 +1,5 @@
const { basicDelta } = require('lib/file-api');
const { rtrimSlashes, ltrimSlashes } = require('lib/path-utils.js');
const { rtrimSlashes, ltrimSlashes } = require('lib/path-utils');
const JoplinError = require('lib/JoplinError');
class FileApiDriverWebDav {

View File

@@ -1,4 +1,4 @@
const { isHidden } = require('lib/path-utils.js');
const { isHidden } = require('lib/path-utils');
const Logger = require('lib/Logger').default;
const shim = require('lib/shim').default;
const BaseItem = require('lib/models/BaseItem.js');

View File

@@ -1,21 +1,24 @@
import { resolve as nodeResolve } from 'path';
const fs = require('fs-extra');
const { time } = require('lib/time-utils.js');
const FsDriverBase = require('lib/fs-driver-base');
class FsDriverNode extends FsDriverBase {
fsErrorToJsError_(error, path = null) {
export default class FsDriverNode extends FsDriverBase {
private fsErrorToJsError_(error:any, path:string = null) {
let msg = error.toString();
if (path !== null) msg += `. Path: ${path}`;
const output = new Error(msg);
const output:any = new Error(msg);
if (error.code) output.code = error.code;
return output;
}
appendFileSync(path, string) {
public appendFileSync(path:string, string:string) {
return fs.appendFileSync(path, string);
}
async appendFile(path, string, encoding = 'base64') {
public async appendFile(path:string, string:string, encoding:string = 'base64') {
try {
return await fs.appendFile(path, string, { encoding: encoding });
} catch (error) {
@@ -23,7 +26,7 @@ class FsDriverNode extends FsDriverBase {
}
}
async writeBinaryFile(path, content) {
public async writeBinaryFile(path:string, content:any) {
try {
// let buffer = new Buffer(content);
const buffer = Buffer.from(content);
@@ -33,7 +36,7 @@ class FsDriverNode extends FsDriverBase {
}
}
async writeFile(path, string, encoding = 'base64') {
public async writeFile(path:string, string:string, encoding:string = 'base64') {
try {
if (encoding === 'buffer') {
return await fs.writeFile(path, string);
@@ -46,7 +49,7 @@ class FsDriverNode extends FsDriverBase {
}
// same as rm -rf
async remove(path) {
public async remove(path:string) {
try {
const r = await fs.remove(path);
return r;
@@ -55,7 +58,7 @@ class FsDriverNode extends FsDriverBase {
}
}
async move(source, dest) {
public async move(source:string, dest:string) {
let lastError = null;
for (let i = 0; i < 5; i++) {
@@ -77,11 +80,11 @@ class FsDriverNode extends FsDriverBase {
throw lastError;
}
exists(path) {
public exists(path:string) {
return fs.pathExists(path);
}
async mkdir(path) {
public async mkdir(path:string) {
// Note that mkdirp() does not throw an error if the directory
// could not be created. This would make the synchroniser to
// incorrectly try to sync with a non-existing dir:
@@ -91,7 +94,7 @@ class FsDriverNode extends FsDriverBase {
return r;
}
async stat(path) {
public async stat(path:string) {
try {
const stat = await fs.stat(path);
return {
@@ -107,11 +110,11 @@ class FsDriverNode extends FsDriverBase {
}
}
async setTimestamp(path, timestampDate) {
public async setTimestamp(path:string, timestampDate:any) {
return fs.utimes(path, timestampDate, timestampDate);
}
async readDirStats(path, options = null) {
public async readDirStats(path:string, options:any = null) {
if (!options) options = {};
if (!('recursive' in options)) options.recursive = false;
@@ -135,7 +138,7 @@ class FsDriverNode extends FsDriverBase {
return output;
}
async open(path, mode) {
public async open(path:string, mode:any) {
try {
return await fs.open(path, mode);
} catch (error) {
@@ -143,7 +146,7 @@ class FsDriverNode extends FsDriverBase {
}
}
async close(handle) {
public async close(handle:any) {
try {
return await fs.close(handle);
} catch (error) {
@@ -151,7 +154,7 @@ class FsDriverNode extends FsDriverBase {
}
}
async readFile(path, encoding = 'utf8') {
public async readFile(path:string, encoding:string = 'utf8') {
try {
if (encoding === 'Buffer') return await fs.readFile(path); // Returns the raw buffer
return await fs.readFile(path, encoding);
@@ -161,7 +164,7 @@ class FsDriverNode extends FsDriverBase {
}
// Always overwrite destination
async copy(source, dest) {
public async copy(source:string, dest:string) {
try {
return await fs.copy(source, dest, { overwrite: true });
} catch (error) {
@@ -169,7 +172,7 @@ class FsDriverNode extends FsDriverBase {
}
}
async unlink(path) {
public async unlink(path:string) {
try {
await fs.unlink(path);
} catch (error) {
@@ -178,7 +181,7 @@ class FsDriverNode extends FsDriverBase {
}
}
async readFileChunk(handle, length, encoding = 'base64') {
public async readFileChunk(handle:any, length:number, encoding:string = 'base64') {
// let buffer = new Buffer(length);
let buffer = Buffer.alloc(length);
const result = await fs.read(handle, buffer, 0, length, null);
@@ -189,10 +192,17 @@ class FsDriverNode extends FsDriverBase {
throw new Error(`Unsupported encoding: ${encoding}`);
}
resolve(path) {
public resolve(path:string) {
return require('path').resolve(path);
}
// Resolves the provided relative path to an absolute path within baseDir. The function
// also checks that the absolute path is within baseDir, to avoid security issues.
// It is expected that baseDir is a safe path (not user-provided).
public resolveRelativePathWithinDir(baseDir:string, relativePath:string) {
const resolvedPath = nodeResolve(baseDir, relativePath);
if (resolvedPath.indexOf(baseDir) !== 0) throw new Error('Resolved path for relative path "' + relativePath + '" is not within base directory "' + baseDir + '"');
return resolvedPath;
}
}
module.exports.FsDriverNode = FsDriverNode;

View File

@@ -160,6 +160,10 @@ class FsDriverRN extends FsDriverBase {
resolve(path) {
throw new Error(`Not implemented: resolve(): ${path}`);
}
resolveRelativePathWithinDir(_baseDir, relativePath) {
throw new Error(`Not implemented: resolveRelativePathWithinDir(): ${relativePath}`);
}
}
module.exports.FsDriverRN = FsDriverRN;

View File

@@ -556,7 +556,7 @@ function enexXmlToMdArray(stream, resources) {
} else if (isStrongTag(n)) {
section.lines.push('**');
} else if (isStrikeTag(n)) {
section.lines.push('(');
section.lines.push('<s>');
} else if (isInlineCodeTag(n)) {
section.lines.push('`');
} else if (n == 'q') {
@@ -739,7 +739,7 @@ function enexXmlToMdArray(stream, resources) {
} else if (isStrongTag(n)) {
section.lines.push('**');
} else if (isStrikeTag(n)) {
section.lines.push(')');
section.lines.push('</s>');
} else if (isInlineCodeTag(n)) {
section.lines.push('`');
} else if (isEmTag(n)) {

View File

@@ -1,6 +1,6 @@
const htmlUtils = require('./htmlUtils');
const utils = require('./utils');
const noteStyle = require('./noteStyle');
const noteStyle = require('./noteStyle').default;
const Setting = require('lib/models/Setting').default;
const { themeStyle } = require('lib/theme');
const InMemoryCache = require('lib/InMemoryCache').default;

View File

@@ -1,20 +1,31 @@
const MdToHtml = require('./MdToHtml');
const MdToHtml = require('./MdToHtml').default;
const HtmlToHtml = require('./HtmlToHtml');
const htmlUtils = require('lib/htmlUtils');
const MarkdownIt = require('markdown-it');
class MarkupToHtml {
constructor(options) {
export enum MarkupLanguage {
Markdown = 1,
Html = 2,
}
export default class MarkupToHtml {
static MARKUP_LANGUAGE_MARKDOWN:number = MarkupLanguage.Markdown;
static MARKUP_LANGUAGE_HTML:number = MarkupLanguage.Html;
private renderers_:any = {};
private options_:any;
private rawMarkdownIt_:any;
constructor(options:any) {
this.options_ = Object.assign({}, {
ResourceModel: {
isResourceUrl: () => false,
},
}, options);
this.renderers_ = {};
}
renderer(markupLanguage) {
renderer(markupLanguage:MarkupLanguage) {
if (this.renderers_[markupLanguage]) return this.renderers_[markupLanguage];
let RendererClass = null;
@@ -31,11 +42,7 @@ class MarkupToHtml {
return this.renderers_[markupLanguage];
}
injectedJavaScript() {
return '';
}
stripMarkup(markupLanguage, markup, options = null) {
stripMarkup(markupLanguage:MarkupLanguage, markup:string, options:any = null) {
if (!markup) return '';
options = Object.assign({}, {
@@ -63,21 +70,16 @@ class MarkupToHtml {
return output;
}
clearCache(markupLanguage) {
clearCache(markupLanguage:MarkupLanguage) {
const r = this.renderer(markupLanguage);
if (r.clearCache) r.clearCache();
}
async render(markupLanguage, markup, theme, options) {
async render(markupLanguage:MarkupLanguage, markup:string, theme:any, options:any) {
return this.renderer(markupLanguage).render(markup, theme, options);
}
async allAssets(markupLanguage, theme) {
async allAssets(markupLanguage:MarkupLanguage, theme:any) {
return this.renderer(markupLanguage).allAssets(theme);
}
}
MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN = 1;
MarkupToHtml.MARKUP_LANGUAGE_HTML = 2;
module.exports = MarkupToHtml;

View File

@@ -1,31 +1,51 @@
import InMemoryCache from 'lib/InMemoryCache';
import noteStyle from './noteStyle';
import { fileExtension } from './pathUtils';
const MarkdownIt = require('markdown-it');
const md5 = require('md5');
const noteStyle = require('./noteStyle');
const { fileExtension } = require('./pathUtils');
const InMemoryCache = require('lib/InMemoryCache').default;
interface RendererRule {
install(context:any, ruleOptions:any):any,
assets?(theme:any):any,
plugin?: any,
}
interface RendererRules {
[pluginName:string]: RendererRule,
}
interface RendererPlugin {
module: any,
options?: any,
}
interface RendererPlugins {
[pluginName:string]: RendererPlugin,
}
// /!\/!\ Note: the order of rules is important!! /!\/!\
const rules = {
const rules:RendererRules = {
fence: require('./MdToHtml/rules/fence').default,
sanitize_html: require('./MdToHtml/rules/sanitize_html').default,
image: require('./MdToHtml/rules/image'),
image: require('./MdToHtml/rules/image').default,
checkbox: require('./MdToHtml/rules/checkbox').default,
katex: require('./MdToHtml/rules/katex'),
link_open: require('./MdToHtml/rules/link_open'),
html_image: require('./MdToHtml/rules/html_image'),
highlight_keywords: require('./MdToHtml/rules/highlight_keywords'),
code_inline: require('./MdToHtml/rules/code_inline'),
fountain: require('./MdToHtml/rules/fountain'),
katex: require('./MdToHtml/rules/katex').default,
link_open: require('./MdToHtml/rules/link_open').default,
html_image: require('./MdToHtml/rules/html_image').default,
highlight_keywords: require('./MdToHtml/rules/highlight_keywords').default,
code_inline: require('./MdToHtml/rules/code_inline').default,
fountain: require('./MdToHtml/rules/fountain').default,
mermaid: require('./MdToHtml/rules/mermaid').default,
};
// const eventManager = require('lib/eventManager').default;
const setupLinkify = require('./MdToHtml/setupLinkify');
const hljs = require('highlight.js');
const uslug = require('uslug');
const markdownItAnchor = require('markdown-it-anchor');
// The keys must match the corresponding entry in Setting.js
const plugins = {
const plugins:RendererPlugins = {
mark: { module: require('markdown-it-mark') },
footnote: { module: require('markdown-it-footnote') },
sub: { module: require('markdown-it-sub') },
@@ -40,29 +60,119 @@ const plugins = {
};
const defaultNoteStyle = require('./defaultNoteStyle');
function slugify(s) {
function slugify(s:string):string {
return uslug(s);
}
// Share across all instances of MdToHtml
const inMemoryCache = new InMemoryCache(20);
class MdToHtml {
constructor(options = null) {
export interface ExtraRendererRule {
id: string,
module: any,
}
export interface Options {
resourceBaseUrl?: string,
ResourceModel?: any,
pluginOptions?: any,
tempDir?: string,
fsDriver?: any,
extraRendererRules?: ExtraRendererRule[],
}
interface PluginAsset {
mime?: string,
inline?: boolean,
name?: string,
text?: string,
}
// Types are a bit of a mess when it comes to plugin assets. Something
// called "pluginAsset" in this class might refer to sublty different
// types. The logic should be cleaned up before types are added.
interface PluginAssets {
[pluginName:string]: PluginAsset[];
}
interface PluginContext {
css: any
pluginAssets: any,
cache: any,
userData: any,
}
interface RenderResultPluginAsset {
name: string,
path: string,
mime: string,
}
interface RenderResult {
html: string,
pluginAssets: RenderResultPluginAsset[];
cssStrings: string[],
}
export interface RuleOptions {
context: PluginContext,
theme: any,
postMessageSyntax: string,
ResourceModel: any,
resourceBaseUrl: string,
resources: any, // resourceId: Resource
// Used by checkboxes to specify how it should be rendered
checkboxRenderingType?: number,
// Used by the keyword highlighting plugin (mobile only)
highlightedKeywords?: any[],
// Use by resource-rendering logic to signify that it should be rendered
// as a plain HTML string without any attached JavaScript. Used for example
// when exporting to HTML.
plainResourceRendering?: boolean,
// Use in mobile app to enable long-pressing an image or a linkg
// to display a context menu. Used in `image.ts` and `link_open.ts`
enableLongPress?: boolean,
// Used in mobile app when enableLongPress = true. Tells for how long
// the resource should be pressed before the menu is shown.
longPressDelay?: number,
// Use by `link_open` rule.
// linkRenderingType = 1 is the regular rendering and clicking on it is handled via embedded JS (in onclick attribute)
// linkRenderingType = 2 gives a plain link with no JS. Caller needs to handle clicking on the link.
linkRenderingType?: number,
}
export default class MdToHtml {
private resourceBaseUrl_:string;
private ResourceModel_:any;
private contextCache_:any;
private fsDriver_:any;
private cachedOutputs_:any = {};
private lastCodeHighlightCacheKey_:string = null;
private cachedHighlightedCode_:any = {};
// Markdown-It plugin options (not Joplin plugin options)
private pluginOptions_:any = {};
private extraRendererRules_:RendererRules = {};
private allProcessedAssets_:any = {};
public constructor(options:Options = null) {
if (!options) options = {};
// Must include last "/"
this.resourceBaseUrl_ = 'resourceBaseUrl' in options ? options.resourceBaseUrl : null;
this.cachedOutputs_ = {};
this.lastCodeHighlightCacheKey_ = null;
this.cachedHighlightedCode_ = {};
this.ResourceModel_ = options.ResourceModel;
this.pluginOptions_ = options.pluginOptions ? options.pluginOptions : {};
this.contextCache_ = inMemoryCache;
this.tempDir_ = options.tempDir;
this.fsDriver_ = {
writeFile: (/* path, content, encoding = 'base64'*/) => { throw new Error('writeFile not set'); },
exists: (/* path*/) => { throw new Error('exists not set'); },
@@ -74,24 +184,26 @@ class MdToHtml {
if (options.fsDriver.exists) this.fsDriver_.exists = options.fsDriver.exists;
if (options.fsDriver.cacheCssToFile) this.fsDriver_.cacheCssToFile = options.fsDriver.cacheCssToFile;
}
if (options.extraRendererRules) {
for (const rule of options.extraRendererRules) {
this.loadExtraRendererRule(rule.id, rule.module);
}
}
}
fsDriver() {
private fsDriver() {
return this.fsDriver_;
}
tempDir() {
return this.tempDir_;
}
static pluginNames() {
public static pluginNames() {
const output = [];
for (const n in rules) output.push(n);
for (const n in plugins) output.push(n);
return output;
}
pluginOptions(name) {
private pluginOptions(name:string) {
let o = this.pluginOptions_[name] ? this.pluginOptions_[name] : {};
o = Object.assign({
enabled: true,
@@ -99,12 +211,18 @@ class MdToHtml {
return o;
}
pluginEnabled(name) {
private pluginEnabled(name:string) {
return this.pluginOptions(name).enabled;
}
processPluginAssets(pluginAssets) {
const files = [];
// `module` is a file that has already been `required()`
public loadExtraRendererRule(id:string, module:any) {
if (this.extraRendererRules_[id]) throw new Error(`A renderer rule with this ID has already been loaded: ${id}`);
this.extraRendererRules_[id] = module;
}
private processPluginAssets(pluginAssets:PluginAssets):RenderResult {
const files:RenderResultPluginAsset[] = [];
const cssStrings = [];
for (const pluginName in pluginAssets) {
for (const asset of pluginAssets[pluginName]) {
@@ -140,29 +258,59 @@ class MdToHtml {
}
return {
html: '',
pluginAssets: files,
cssStrings: cssStrings,
};
}
async allAssets(theme) {
const assets = {};
// This return all the assets for all the plugins. Since it is called
// on each render, the result is cached.
private allProcessedAssets(theme:any, codeTheme:string) {
const cacheKey:string = theme.cacheKey + codeTheme;
if (this.allProcessedAssets_[cacheKey]) return this.allProcessedAssets_[cacheKey];
const assets:any = {};
for (const key in rules) {
if (!this.pluginEnabled(key)) continue;
const rule = rules[key];
if (rule.style) {
assets[key] = rule.style(theme);
if (rule.assets) {
assets[key] = rule.assets(theme);
}
}
assets['highlight.js'] = [{ name: codeTheme }];
const output = this.processPluginAssets(assets);
this.allProcessedAssets_ = {
[cacheKey]: output,
};
return output;
}
// This is similar to allProcessedAssets() but used only by the Rich Text editor
public async allAssets(theme:any) {
const assets:any = {};
for (const key in rules) {
if (!this.pluginEnabled(key)) continue;
const rule = rules[key];
if (rule.assets) {
assets[key] = rule.assets(theme);
}
}
const processedAssets = this.processPluginAssets(assets);
processedAssets.cssStrings.splice(0, 0, noteStyle(theme));
processedAssets.cssStrings.splice(0, 0, noteStyle(theme).join('\n'));
const output = await this.outputAssetsToExternalAssets_(processedAssets);
return output.pluginAssets;
}
async outputAssetsToExternalAssets_(output) {
private async outputAssetsToExternalAssets_(output:any) {
for (const cssString of output.cssStrings) {
output.pluginAssets.push(await this.fsDriver().cacheCssToFile(cssString));
}
@@ -170,7 +318,7 @@ class MdToHtml {
return output;
}
removeMarkdownItWrappingParagraph_(html) {
private removeMarkdownItWrappingParagraph_(html:string) {
// <p></p>\n
if (html.length < 8) return html;
if (html.substr(0, 3) !== '<p>') return html;
@@ -178,12 +326,12 @@ class MdToHtml {
return html.substring(3, html.length - 5);
}
clearCache() {
public clearCache() {
this.cachedOutputs_ = {};
}
// "theme" is the theme as returned by themeStyle()
async render(body, theme = null, options = null) {
public async render(body:string, theme:any = null, options:any = null):Promise<RenderResult> {
options = Object.assign({}, {
// In bodyOnly mode, the rendered Markdown is returned without the wrapper DIV
bodyOnly: false,
@@ -213,23 +361,24 @@ class MdToHtml {
const cachedOutput = this.cachedOutputs_[cacheKey];
if (cachedOutput) return cachedOutput;
const context = {
css: {},
pluginAssets: {},
cache: this.contextCache_,
};
const ruleOptions = Object.assign({}, options, {
resourceBaseUrl: this.resourceBaseUrl_,
ResourceModel: this.ResourceModel_,
});
const context:PluginContext = {
css: {},
pluginAssets: {},
cache: this.contextCache_,
userData: {},
};
const markdownIt = new MarkdownIt({
breaks: !this.pluginEnabled('softbreaks'),
typographer: this.pluginEnabled('typographer'),
linkify: true,
html: true,
highlight: (str, lang) => {
highlight: (str:string, lang:string) => {
let outputCodeHtml = '';
// The strings includes the last \n that is part of the fence,
@@ -253,10 +402,6 @@ class MdToHtml {
this.cachedHighlightedCode_[cacheKey] = hlCode;
}
context.pluginAssets['highlight.js'] = [
{ name: options.codeTheme },
];
outputCodeHtml = hlCode;
} catch (error) {
outputCodeHtml = markdownIt.utils.escapeHtml(trimmedStr);
@@ -296,11 +441,18 @@ class MdToHtml {
// Using the `context` object, a plugin can define what additional assets they need (css, fonts, etc.) using context.pluginAssets.
// The calling application will need to handle loading these assets.
for (const key in rules) {
const allRules = Object.assign({}, rules, this.extraRendererRules_);
for (const key in allRules) {
if (!this.pluginEnabled(key)) continue;
const rule = rules[key];
const ruleInstall = rule.install ? rule.install : rule;
markdownIt.use(ruleInstall(context, { ...ruleOptions }));
const rule = allRules[key];
markdownIt.use(rule.plugin, {
context: context,
...ruleOptions,
...(ruleOptions.plugins[key] ? ruleOptions.plugins[key] : {}),
});
}
markdownIt.use(markdownItAnchor, { slugify: slugify });
@@ -311,18 +463,13 @@ class MdToHtml {
}
}
// const extraPlugins = eventManager.filterEmit('mdToHtmlPlugins', {});
// for (const key in extraPlugins) {
// markdownIt.use(extraPlugins[key].module, extraPlugins[key].options);
// }
setupLinkify(markdownIt);
const renderedBody = markdownIt.render(body);
const renderedBody = markdownIt.render(body, context);
let cssStrings = noteStyle(options.theme);
let output = this.processPluginAssets(context.pluginAssets);
let output = { ...this.allProcessedAssets(options.theme, options.codeTheme) };
cssStrings = cssStrings.concat(output.cssStrings);
if (options.userCss) cssStrings.push(options.userCss);
@@ -354,9 +501,4 @@ class MdToHtml {
return output;
}
injectedJavaScript() {
return '';
}
}
module.exports = MdToHtml;

View File

@@ -1,24 +1,21 @@
import { RuleOptions } from '../../MdToHtml';
let checkboxIndex_ = -1;
const pluginAssets:Function[] = [];
pluginAssets[1] = function() {
function pluginAssets(theme:any) {
return [
{
inline: true,
mime: 'text/css',
text: `
/*
FOR THE MARKDOWN EDITOR
*/
/* Remove the indentation from the checkboxes at the root of the document
(otherwise they are too far right), but keep it for their children to allow
nested lists. Make sure this value matches the UL margin. */
/*
.md-checkbox .checkbox-wrapper {
display: flex;
align-items: center;
}
*/
li.md-checkbox {
list-style-type: none;
}
@@ -26,30 +23,16 @@ pluginAssets[1] = function() {
li.md-checkbox input[type=checkbox] {
margin-left: -1.71em;
margin-right: 0.7em;
}`,
},
];
};
pluginAssets[2] = function(theme:any) {
return [
{
inline: true,
mime: 'text/css',
text: `
/* https://stackoverflow.com/questions/7478336/only-detect-click-event-on-pseudo-element#comment39751366_7478344 */
/* Not doing this trick anymore. See Modules/TinyMCE/JoplinLists/src/main/ts/ui/Buttons.ts */
/*
ul.joplin-checklist li {
pointer-events: none;
}
*/
ul.joplin-checklist {
list-style:none;
}
/*
FOR THE RICH TEXT EDITOR
*/
ul.joplin-checklist li::before {
content:"\\f14a";
font-family:"Font Awesome 5 Free";
@@ -68,7 +51,7 @@ pluginAssets[2] = function(theme:any) {
}`,
},
];
};
}
function createPrefixTokens(Token:any, id:string, checked:boolean, label:string, postMessageSyntax:string, sourceToken:any):any[] {
let token = null;
@@ -129,9 +112,8 @@ function createSuffixTokens(Token:any):any[] {
];
}
// @ts-ignore: Keep the function signature as-is despite unusued arguments
function installRule(markdownIt:any, mdOptions:any, ruleOptions:any, context:any) {
const pluginOptions = { renderingType: 1, ...ruleOptions.plugins['checkbox'] };
function checkboxPlugin(markdownIt:any, options:RuleOptions) {
const renderingType = options.checkboxRenderingType || 1;
markdownIt.core.ruler.push('checkbox', (state:any) => {
const tokens = state.tokens;
@@ -180,14 +162,14 @@ function installRule(markdownIt:any, mdOptions:any, ruleOptions:any, context:any
const currentList = lists[lists.length - 1];
if (pluginOptions.renderingType === 1) {
if (renderingType === 1) {
checkboxIndex_++;
const id = `md-checkbox-${checkboxIndex_}`;
// Prepend the text content with the checkbox markup and the opening <label> tag
// then append the </label> tag at the end of the text content.
const prefix = createPrefixTokens(Token, id, checked, label, ruleOptions.postMessageSyntax, token);
const prefix = createPrefixTokens(Token, id, checked, label, options.postMessageSyntax, token);
const suffix = createSuffixTokens(Token);
token.children = markdownIt.utils.arrayReplaceAt(token.children, 0, prefix);
@@ -214,20 +196,12 @@ function installRule(markdownIt:any, mdOptions:any, ruleOptions:any, context:any
currentListItem.attrSet('class', (`${currentListItem.attrGet('class') || ''} checked`).trim());
}
}
if (!('checkbox' in context.pluginAssets)) {
context.pluginAssets['checkbox'] = pluginAssets[pluginOptions.renderingType](ruleOptions.theme);
}
}
}
});
}
export default {
install: function(context:any, ruleOptions:any) {
return function(md:any, mdOptions:any) {
installRule(md, mdOptions, ruleOptions, context);
};
},
style: pluginAssets[2],
plugin: checkboxPlugin,
assets: pluginAssets,
};

View File

@@ -1,11 +1,11 @@
function installRule(markdownIt) {
function plugin(markdownIt:any) {
const defaultRender =
markdownIt.renderer.rules.code_inline ||
function(tokens, idx, options, env, self) {
function(tokens:any, idx:any, options:any, _env:any, self:any) {
return self.renderToken(tokens, idx, options);
};
markdownIt.renderer.rules.code_inline = (tokens, idx, options, env, self) => {
markdownIt.renderer.rules.code_inline = (tokens:any[], idx:number, options:any, env:any, self:any) => {
const token = tokens[idx];
let tokenClass = token.attrGet('class');
if (!tokenClass) tokenClass = '';
@@ -15,8 +15,6 @@ function installRule(markdownIt) {
};
}
module.exports = function(context, ruleOptions) {
return function(md, mdOptions) {
installRule(md, mdOptions, ruleOptions);
};
export default {
plugin,
};

View File

@@ -8,7 +8,7 @@
// So we modify the code below to allow highlight() to return an object that tells how to render
// the code.
function installRule(markdownIt:any) {
function plugin(markdownIt:any) {
// @ts-ignore: Keep the function signature as-is despite unusued arguments
markdownIt.renderer.rules.fence = function(tokens:any[], idx:number, options:any, env:any, slf:any) {
let token = tokens[idx],
@@ -63,8 +63,7 @@ function installRule(markdownIt:any) {
};
}
export default function() {
return function(md:any) {
installRule(md);
};
}
export default {
plugin,
};

View File

@@ -1,6 +1,6 @@
const fountain = require('../../vendor/fountain.min.js');
const fountainCss = function() {
const pluginAssets = function() {
return [
{
inline: true,
@@ -102,7 +102,7 @@ const fountainCss = function() {
];
};
function renderFountainScript(markdownIt, content) {
function renderFountainScript(markdownIt:any, content:string) {
const result = fountain.parse(content);
return `
@@ -118,30 +118,19 @@ function renderFountainScript(markdownIt, content) {
`;
}
function addContextAssets(context) {
if ('fountain' in context.pluginAssets) return;
context.pluginAssets['fountain'] = fountainCss();
}
function installRule(markdownIt, mdOptions, ruleOptions, context) {
const defaultRender = markdownIt.renderer.rules.fence || function(tokens, idx, options, env, self) {
function plugin(markdownIt:any) {
const defaultRender = markdownIt.renderer.rules.fence || function(tokens:any[], idx:number, options:any, _env:any, self:any) {
return self.renderToken(tokens, idx, options);
};
markdownIt.renderer.rules.fence = function(tokens, idx, options, env, self) {
markdownIt.renderer.rules.fence = function(tokens:any[], idx:number, options:any, env:any, self:any) {
const token = tokens[idx];
if (token.info !== 'fountain') return defaultRender(tokens, idx, options, env, self);
addContextAssets(context);
return renderFountainScript(markdownIt, token.content);
};
}
module.exports = {
install: function(context, ruleOptions) {
return function(md, mdOptions) {
installRule(md, mdOptions, ruleOptions, context);
};
},
style: fountainCss,
export default {
plugin,
assets: pluginAssets,
};

View File

@@ -1,7 +1,11 @@
// This plugin is used only on mobile, to highlight search results.
import { RuleOptions } from "lib/joplin-renderer/MdToHtml";
const stringUtils = require('../../stringUtils.js');
const md5 = require('md5');
function createHighlightedTokens(Token, splitted) {
function createHighlightedTokens(Token:any, splitted:string[]) {
let token;
const output = [];
@@ -30,10 +34,11 @@ function createHighlightedTokens(Token, splitted) {
return output;
}
function installRule(markdownIt, mdOptions, ruleOptions) {
// function installRule(markdownIt, mdOptions, ruleOptions) {
function plugin(markdownIt:any, ruleOptions:RuleOptions) {
const divider = md5(Date.now().toString() + Math.random().toString());
markdownIt.core.ruler.push('highlight_keywords', state => {
markdownIt.core.ruler.push('highlight_keywords', (state:any) => {
const keywords = ruleOptions.highlightedKeywords;
if (!keywords || !keywords.length) return;
@@ -60,8 +65,6 @@ function installRule(markdownIt, mdOptions, ruleOptions) {
});
}
module.exports = function(context, ruleOptions) {
return function(md, mdOptions) {
installRule(md, mdOptions, ruleOptions);
};
};
export default {
plugin,
}

View File

@@ -1,39 +1,40 @@
// const Resource = require('lib/models/Resource.js');
import { RuleOptions } from "lib/joplin-renderer/MdToHtml";
const htmlUtils = require('../../htmlUtils.js');
const utils = require('../../utils');
function renderImageHtml(before, src, after, ruleOptions) {
function renderImageHtml(before:string, src:string, after:string, ruleOptions:RuleOptions) {
const r = utils.imageReplacement(ruleOptions.ResourceModel, src, ruleOptions.resources, ruleOptions.resourceBaseUrl);
if (typeof r === 'string') return r;
if (r) return `<img ${before} ${htmlUtils.attributesHtml(r)} ${after}/>`;
return `[Image: ${src}]`;
}
function installRule(markdownIt, mdOptions, ruleOptions) {
function plugin(markdownIt:any, ruleOptions:RuleOptions) {
const Resource = ruleOptions.ResourceModel;
const htmlBlockDefaultRender =
markdownIt.renderer.rules.html_block ||
function(tokens, idx, options, env, self) {
function(tokens:any[], idx:number, options:any, _env:any, self:any) {
return self.renderToken(tokens, idx, options);
};
const htmlInlineDefaultRender =
markdownIt.renderer.rules.html_inline ||
function(tokens, idx, options, env, self) {
function(tokens:any[], idx:number, options:any, _env:any, self:any) {
return self.renderToken(tokens, idx, options);
};
const imageRegex = /<img(.*?)src=["'](.*?)["'](.*?)>/gi;
const handleImageTags = function(defaultRender) {
return function(tokens, idx, options, env, self) {
const handleImageTags = function(defaultRender:Function) {
return function(tokens:any[], idx:number, options:any, env:any, self:any) {
const token = tokens[idx];
const content = token.content;
if (!content.match(imageRegex)) return defaultRender(tokens, idx, options, env, self);
return content.replace(imageRegex, (v, before, src, after) => {
return content.replace(imageRegex, (_v:any, before:string, src:string, after:string) => {
if (!Resource.isResourceUrl(src)) return `<img${before}src="${src}"${after}>`;
return renderImageHtml(before, src, after, ruleOptions);
});
@@ -46,8 +47,4 @@ function installRule(markdownIt, mdOptions, ruleOptions) {
markdownIt.renderer.rules.html_inline = handleImageTags(htmlInlineDefaultRender);
}
module.exports = function(context, ruleOptions) {
return function(md, mdOptions) {
installRule(md, mdOptions, ruleOptions);
};
};
export default { plugin }

View File

@@ -1,11 +1,13 @@
import { RuleOptions } from 'lib/joplin-renderer/MdToHtml';
// const Resource = require('lib/models/Resource.js');
const utils = require('../../utils');
const htmlUtils = require('../../htmlUtils.js');
function installRule(markdownIt, mdOptions, ruleOptions) {
function plugin(markdownIt:any, ruleOptions:RuleOptions) {
const defaultRender = markdownIt.renderer.rules.image;
markdownIt.renderer.rules.image = (tokens, idx, options, env, self) => {
markdownIt.renderer.rules.image = (tokens:any[], idx:number, options:any, env:any, self:any) => {
const Resource = ruleOptions.ResourceModel;
const token = tokens[idx];
@@ -19,15 +21,13 @@ function installRule(markdownIt, mdOptions, ruleOptions) {
if (r) {
let js = '';
if (ruleOptions.enableLongPress) {
const longPressDelay = ruleOptions.longPressDelay ? ruleOptions.longPressDelay : 500;
const id = r['data-resource-id'];
const longPressHandler = `${ruleOptions.postMessageSyntax}('longclick:${id}')`;
const touchStart = `t=setTimeout(()=>{t=null; ${longPressHandler};}, ${ruleOptions.longPressDelay});`;
const cancel = 'if (!!t) clearTimeout(t); t=null';
const touchStart = `t=setTimeout(()=>{t=null; ${longPressHandler};}, ${longPressDelay});`;
const touchEnd = 'if (!!t) clearTimeout(t); t=null';
js = ` ontouchstart="${touchStart}" ontouchend="${touchEnd}"`;
js = ` ontouchstart="${touchStart}" ontouchend="${cancel}" ontouchcancel="${cancel}" ontouchmove="${cancel}"`;
}
return `<img data-from-md ${htmlUtils.attributesHtml(Object.assign({}, r, { title: title }))}${js}/>`;
@@ -36,8 +36,4 @@ function installRule(markdownIt, mdOptions, ruleOptions) {
};
}
module.exports = function(context, ruleOptions) {
return function(md, mdOptions) {
installRule(md, mdOptions, ruleOptions);
};
};
export default { plugin };

View File

@@ -1,8 +1,4 @@
/* eslint prefer-const: 0*/
// Based on https://github.com/waylonflinn/markdown-it-katex
'use strict';
import { RuleOptions } from "lib/joplin-renderer/MdToHtml";
let katex = require('katex');
const md5 = require('md5');
@@ -46,7 +42,7 @@ function katexStyle() {
// Test if potential opening or closing delimieter
// Assumes that there is a "$" at state.src[pos]
function isValidDelim(state, pos) {
function isValidDelim(state:any, pos:number) {
let prevChar,
nextChar,
max = state.posMax,
@@ -71,7 +67,7 @@ function isValidDelim(state, pos) {
};
}
function math_inline(state, silent) {
function math_inline(state:any, silent:boolean) {
let start, match, token, res, pos;
if (state.src[state.pos] !== '$') {
@@ -146,7 +142,7 @@ function math_inline(state, silent) {
return true;
}
function math_block(state, start, end, silent) {
function math_block(state:any, start:number, end:number, silent:boolean) {
let firstLine,
lastLine,
next,
@@ -212,80 +208,71 @@ function math_block(state, start, end, silent) {
return true;
}
const cache_ = {};
const cache_:any = {};
module.exports = {
install: function(context) {
function renderToStringWithCache(latex:string, katexOptions:any) {
const cacheKey = md5(escape(latex) + escape(stringifySafe(katexOptions)));
if (cacheKey in cache_) {
return cache_[cacheKey];
} else {
const beforeMacros = stringifySafe(katexOptions.macros);
const output = katex.renderToString(latex, katexOptions);
const afterMacros = stringifySafe(katexOptions.macros);
// Don't cache the formulas that add macros, otherwise
// they won't be added on second run.
if (beforeMacros === afterMacros) cache_[cacheKey] = output;
return output;
}
}
export default {
plugin: function(markdownIt:any, options:RuleOptions) {
// Keep macros that persist across Katex blocks to allow defining a macro
// in one block and re-using it later in other blocks.
// https://github.com/laurent22/joplin/issues/1105
context.__katex = { macros: {} };
if (!options.context.userData.__katex) options.context.userData.__katex = { macros: {} };
const addContextAssets = () => {
context.pluginAssets['katex'] = katexStyle();
};
const katexOptions:any = {}
katexOptions.macros = options.context.userData.__katex.macros;
katexOptions.trust = true;
function renderToStringWithCache(latex, options) {
const cacheKey = md5(escape(latex) + escape(stringifySafe(options)));
if (cacheKey in cache_) {
return cache_[cacheKey];
} else {
const beforeMacros = stringifySafe(options.macros);
const output = katex.renderToString(latex, options);
const afterMacros = stringifySafe(options.macros);
// Don't cache the formulas that add macros, otherwise
// they won't be added on second run.
if (beforeMacros === afterMacros) cache_[cacheKey] = output;
return output;
// set KaTeX as the renderer for markdown-it-simplemath
const katexInline = function(latex:string) {
katexOptions.displayMode = false;
try {
return `<span class="joplin-editable"><span class="joplin-source" data-joplin-language="katex" data-joplin-source-open="$" data-joplin-source-close="$">${markdownIt.utils.escapeHtml(latex)}</span>${renderToStringWithCache(latex, katexOptions)}</span>`;
} catch (error) {
console.error('Katex error for:', latex, error);
return latex;
}
}
return function(md, options) {
// Default options
options = options || {};
options.macros = context.__katex.macros;
options.trust = true;
// set KaTeX as the renderer for markdown-it-simplemath
const katexInline = function(latex) {
options.displayMode = false;
try {
return `<span class="joplin-editable"><span class="joplin-source" data-joplin-language="katex" data-joplin-source-open="$" data-joplin-source-close="$">${md.utils.escapeHtml(latex)}</span>${renderToStringWithCache(latex, options)}</span>`;
} catch (error) {
console.error('Katex error for:', latex, error);
return latex;
}
};
const inlineRenderer = function(tokens, idx) {
addContextAssets();
return katexInline(tokens[idx].content);
};
const katexBlock = function(latex) {
options.displayMode = true;
try {
return `<div class="joplin-editable"><pre class="joplin-source" data-joplin-language="katex" data-joplin-source-open="$$&#10;" data-joplin-source-close="&#10;$$&#10;">${md.utils.escapeHtml(latex)}</pre>${renderToStringWithCache(latex, options)}</div>`;
} catch (error) {
console.error('Katex error for:', latex, error);
return latex;
}
};
const blockRenderer = function(tokens, idx) {
addContextAssets();
return `${katexBlock(tokens[idx].content)}\n`;
};
md.inline.ruler.after('escape', 'math_inline', math_inline);
md.block.ruler.after('blockquote', 'math_block', math_block, {
alt: ['paragraph', 'reference', 'blockquote', 'list'],
});
md.renderer.rules.math_inline = inlineRenderer;
md.renderer.rules.math_block = blockRenderer;
};
const inlineRenderer = function(tokens:any[], idx:number) {
return katexInline(tokens[idx].content);
};
const katexBlock = function(latex:string) {
katexOptions.displayMode = true;
try {
return `<div class="joplin-editable"><pre class="joplin-source" data-joplin-language="katex" data-joplin-source-open="$$&#10;" data-joplin-source-close="&#10;$$&#10;">${markdownIt.utils.escapeHtml(latex)}</pre>${renderToStringWithCache(latex, katexOptions)}</div>`;
} catch (error) {
console.error('Katex error for:', latex, error);
return latex;
}
};
const blockRenderer = function(tokens:any[], idx:number) {
return `${katexBlock(tokens[idx].content)}\n`;
};
markdownIt.inline.ruler.after('escape', 'math_inline', math_inline);
markdownIt.block.ruler.after('blockquote', 'math_block', math_block, {
alt: ['paragraph', 'reference', 'blockquote', 'list'],
});
markdownIt.renderer.rules.math_inline = inlineRenderer;
markdownIt.renderer.rules.math_block = blockRenderer;
},
style: katexStyle,
assets: katexStyle,
};

View File

@@ -1,18 +1,13 @@
import { RuleOptions } from 'lib/joplin-renderer/MdToHtml';
const Entities = require('html-entities').AllHtmlEntities;
const htmlentities = new Entities().encode;
const utils = require('../../utils');
const urlUtils = require('../../urlUtils.js');
const { getClassNameForMimeType } = require('font-awesome-filetypes');
function installRule(markdownIt, mdOptions, ruleOptions) {
const pluginOptions = {
// linkRenderingType = 1 is the regular rendering and clicking on it is handled via embedded JS (in onclick attribute)
// linkRenderingType = 2 gives a plain link with no JS. Caller needs to handle clicking on the link.
linkRenderingType: 1,
...ruleOptions.plugins['link_open'],
};
markdownIt.renderer.rules.link_open = function(tokens, idx) {
function plugin(markdownIt:any, ruleOptions:RuleOptions) {
markdownIt.renderer.rules.link_open = function(tokens:any[], idx:number) {
const token = tokens[idx];
let href = utils.getAttr(token.attrs, 'href');
const resourceHrefInfo = urlUtils.parseResourceUrl(href);
@@ -47,7 +42,7 @@ function installRule(markdownIt, mdOptions, ruleOptions) {
if (!mime) {
iconType = 'fa-joplin';
}
// Icons are defined in lib/renderers/noteStyle.js using inline svg
// Icons are defined in lib/renderers/noteStyle using inline svg
// The icons are taken from fork-awesome but use the font-awesome naming scheme in order
// to be more compatible with the getClass library
icon = `<span class="resource-icon ${iconType}"></span>`;
@@ -65,22 +60,19 @@ function installRule(markdownIt, mdOptions, ruleOptions) {
let js = `${ruleOptions.postMessageSyntax}(${JSON.stringify(href)}, { resourceId: ${JSON.stringify(resourceId)} }); return false;`;
if (ruleOptions.enableLongPress && !!resourceId) {
const longPressDelay = ruleOptions.longPressDelay ? ruleOptions.longPressDelay : 500;
const onClick = `${ruleOptions.postMessageSyntax}(${JSON.stringify(href)})`;
const onLongClick = `${ruleOptions.postMessageSyntax}("longclick:${resourceId}")`;
const touchStart = `t=setTimeout(()=>{t=null; ${onLongClick};}, ${longPressDelay});`;
const touchEnd = `if (!!t) {clearTimeout(t); t=null; ${onClick};}`;
js = `ontouchstart='${touchStart}' ontouchend='${touchEnd}'`;
const touchStart = `t=setTimeout(()=>{t=null; ${onLongClick};}, ${ruleOptions.longPressDelay});`;
const cancel = 'if (!!t) {clearTimeout(t); t=null;';
const touchEnd = `${cancel} ${onClick};}`;
js = `ontouchstart='${touchStart}' ontouchend='${touchEnd}' ontouchcancel='${cancel} ontouchmove="${cancel}'`;
} else {
js = `onclick='${js}'`;
}
if (hrefAttr.indexOf('#') === 0 && href.indexOf('#') === 0) js = ''; // If it's an internal anchor, don't add any JS since the webview is going to handle navigating to the right place
if (ruleOptions.plainResourceRendering || pluginOptions.linkRenderingType === 2) {
if (ruleOptions.plainResourceRendering || ruleOptions.linkRenderingType === 2) {
return `<a data-from-md ${resourceIdAttr} title='${htmlentities(title)}' href='${htmlentities(href)}' type='${htmlentities(mime)}'>`;
} else {
return `<a data-from-md ${resourceIdAttr} title='${htmlentities(title)}' href='${hrefAttr}' ${js} type='${htmlentities(mime)}'>${icon}`;
@@ -88,9 +80,4 @@ function installRule(markdownIt, mdOptions, ruleOptions) {
};
}
module.exports = function(context, ruleOptions) {
return function(md, mdOptions) {
installRule(md, mdOptions, ruleOptions);
};
};
export default { plugin };

View File

@@ -1,49 +1,35 @@
function style() {
return [
{ name: 'mermaid.min.js' },
{ name: 'mermaid_render.js' },
{
inline: true,
// Note: Mermaid is buggy when rendering below a certain width (500px?)
// so set an arbitrarily high width here for the container. Once the
// diagram is rendered it will be reset to 100% in mermaid_render.js
text: '.mermaid { background-color: white; width: 640px; }',
mime: 'text/css',
},
];
}
function addContextAssets(context:any) {
if ('mermaid' in context.pluginAssets) return;
context.pluginAssets['mermaid'] = style();
}
// @ts-ignore: Keep the function signature as-is despite unusued arguments
function installRule(markdownIt:any, mdOptions:any, ruleOptions:any, context:any) {
const defaultRender:Function = markdownIt.renderer.rules.fence || function(tokens:any[], idx:number, options:any, env:any, self:any) {
return self.renderToken(tokens, idx, options, env, self);
};
markdownIt.renderer.rules.fence = function(tokens:any[], idx:number, options:{}, env:any, self:any) {
const token = tokens[idx];
if (token.info !== 'mermaid') return defaultRender(tokens, idx, options, env, self);
addContextAssets(context);
const contentHtml = markdownIt.utils.escapeHtml(token.content);
return `
<div class="joplin-editable">
<pre class="joplin-source" data-joplin-language="mermaid" data-joplin-source-open="\`\`\`mermaid&#10;" data-joplin-source-close="&#10;\`\`\`&#10;">${contentHtml}</pre>
<div class="mermaid">${contentHtml}</div>
</div>
`;
};
}
export default {
install: function(context:any, ruleOptions:any) {
return function(md:any, mdOptions:any) {
installRule(md, mdOptions, ruleOptions, context);
assets: function() {
return [
{ name: 'mermaid.min.js' },
{ name: 'mermaid_render.js' },
{
inline: true,
// Note: Mermaid is buggy when rendering below a certain width (500px?)
// so set an arbitrarily high width here for the container. Once the
// diagram is rendered it will be reset to 100% in mermaid_render.js
text: '.mermaid { background-color: white; width: 640px; }',
mime: 'text/css',
},
];
},
plugin: function(markdownIt:any) {
const defaultRender:Function = markdownIt.renderer.rules.fence || function(tokens:any[], idx:number, options:any, env:any, self:any) {
return self.renderToken(tokens, idx, options, env, self);
};
markdownIt.renderer.rules.fence = function(tokens:any[], idx:number, options:{}, env:any, self:any) {
const token = tokens[idx];
if (token.info !== 'mermaid') return defaultRender(tokens, idx, options, env, self);
const contentHtml = markdownIt.utils.escapeHtml(token.content);
return `
<div class="joplin-editable">
<pre class="joplin-source" data-joplin-language="mermaid" data-joplin-source-open="\`\`\`mermaid&#10;" data-joplin-source-close="&#10;\`\`\`&#10;">${contentHtml}</pre>
<div class="mermaid">${contentHtml}</div>
</div>
`;
};
},
style: style,
};

View File

@@ -1,7 +1,19 @@
/* global mermaid */
function mermaidReady() {
return typeof mermaid !== 'undefined';
// The Mermaid initialization code renders the Mermaid code within any element with class "mermaid" or
// ID "mermaid". However in some cases some elements might have this ID but not be Mermaid code.
// For example, Markdown code like this:
//
// # Mermaid
//
// Will generate this HTML:
//
// <h1 id="mermaid">Mermaid</h1>
//
// And that's going to make the lib set the `mermaid` object to the H1 element.
// So below, we double-check that what we have really is an instance of the library.
return typeof mermaid !== 'undefined' && mermaid !== null && typeof mermaid === 'object' && !!mermaid.init;
}
function mermaidInit() {

View File

@@ -1,53 +1,50 @@
import { RuleOptions } from 'lib/joplin-renderer/MdToHtml';
const md5 = require('md5');
const htmlUtils = require('../../htmlUtils');
// @ts-ignore: Keep the function signature as-is despite unusued arguments
function installRule(markdownIt:any, mdOptions:any, ruleOptions:any, context:any) {
markdownIt.core.ruler.push('sanitize_html', (state:any) => {
const tokens = state.tokens;
export default {
plugin: function(markdownIt:any, ruleOptions:RuleOptions) {
markdownIt.core.ruler.push('sanitize_html', (state:any) => {
const tokens = state.tokens;
const walkHtmlTokens = (tokens:any[]) => {
if (!tokens || !tokens.length) return;
const walkHtmlTokens = (tokens:any[]) => {
if (!tokens || !tokens.length) return;
for (const token of tokens) {
if (!['html_block', 'html_inline'].includes(token.type)) {
for (const token of tokens) {
if (!['html_block', 'html_inline'].includes(token.type)) {
walkHtmlTokens(token.children);
continue;
}
const cacheKey = md5(escape(token.content));
let sanitizedContent = ruleOptions.context.cache.value(cacheKey);
// For html_inline, the content is only a fragment of HTML, as it will be rendered, but
// it's not necessarily valid HTML. For example this HTML:
//
// <a href="#">Testing</a>
//
// will be rendered as three tokens:
//
// html_inline: <a href="#">
// text: Testing
// html_inline: </a>
//
// So the sanitizeHtml function must handle this kind of non-valid HTML.
if (!sanitizedContent) {
sanitizedContent = htmlUtils.sanitizeHtml(token.content, { addNoMdConvClass: true });
}
token.content = sanitizedContent;
ruleOptions.context.cache.setValue(cacheKey, sanitizedContent, 1000 * 60 * 60);
walkHtmlTokens(token.children);
continue;
}
};
const cacheKey = md5(escape(token.content));
let sanitizedContent = context.cache.value(cacheKey);
// For html_inline, the content is only a fragment of HTML, as it will be rendered, but
// it's not necessarily valid HTML. For example this HTML:
//
// <a href="#">Testing</a>
//
// will be rendered as three tokens:
//
// html_inline: <a href="#">
// text: Testing
// html_inline: </a>
//
// So the sanitizeHtml function must handle this kind of non-valid HTML.
if (!sanitizedContent) {
sanitizedContent = htmlUtils.sanitizeHtml(token.content, { addNoMdConvClass: true });
}
token.content = sanitizedContent;
context.cache.setValue(cacheKey, sanitizedContent, 1000 * 60 * 60);
walkHtmlTokens(token.children);
}
};
walkHtmlTokens(tokens);
});
}
export default function(context:any, ruleOptions:any) {
return function(md:any, mdOptions:any) {
installRule(md, mdOptions, ruleOptions, context);
};
}
walkHtmlTokens(tokens);
});
},
};

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More